Programs & Examples On #Points

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

TS1086: An accessor cannot be declared in ambient context

I had this same issue, and these 2 commands saved my life. My underlying problem is that I am always messing up with global install and local install. Maybe you are facing a similar issue, and hopefully running these commands will solve your problem too.

ng update --next @angular/cli --force
npm install typescript@latest

Pandas Merging 101

In this answer, I will consider practical examples.

The first one, is of pandas.concat.

The second one, of merging dataframes from the index of one and the column of another one.

1. pandas.concat

Considering the following DataFrames with the same column names:

Preco2018 with size (8784, 5)

DataFrame 1

Preco 2019 with size (8760, 5)

DataFrame 2

That have the same column names.

You can combine them using pandas.concat, by simply

import pandas as pd

frames = [Preco2018, Preco2019]

df_merged = pd.concat(frames)

Which results in a DataFrame with the following size (17544, 5)

DataFrame result of the combination of two dataframes

If you want to visualize, it ends up working like this

How concat works


2. Merge by Column and Index

In this part, I will consider a specific case: If one wants to merge the index of one dataframe and the column of another dataframe.

Let's say one has the dataframe Geo with 54 columns, being one of the columns the Date Data, which is of type datetime64[ns].

enter image description here

And the dataframe Price that has one column with the price and the index corresponds to the dates

enter image description here

In this specific case, to merge them, one uses pd.merge

merged = pd.merge(Price, Geo, left_index=True, right_on='Data')

Which results in the following dataframe

enter image description here

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch

var data = { "results":[  _x000D_
  [  _x000D_
     {  _x000D_
  [  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
     {  _x000D_
var scatterSeries = []; _x000D_
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';_x000D_

code sample -

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

The problem is that you are using gulp 4 and the syntax in gulfile.js is of gulp 3. So either downgrade your gulp to 3.x.x or make use of gulp 4 syntaxes.

Syntax Gulp 3:

gulp.task('default', ['sass'], function() {....} );

Syntax Gulp 4:

gulp.task('default', gulp.series(sass), function() {....} );

You can read more about gulp and gulp tasks on:

Trying to merge 2 dataframes but get ValueError

In one of your dataframes the year is a string and the other it is an int64 you can convert it first and then join (e.g. df['year']=df['year'].astype(int) or as RafaelC suggested df.year.astype(int))

Edit: Also note the comment by Anderson Zhu: Just in case you have None or missing values in one of your dataframes, you need to use Int64 instead of int. See the reference here.

How to format JSON in notepad++

Always google so you can locate the latest package for both NPP and NPP Plugins.

I googled "notepad++ 64bit". Downloaded the free latest version at Notepad++ (64-bit) - Free download and software. Installed notepad++ by double-click on npp.?.?.?.Installer.x64.exe, installed the .exe to default Windows 64bit path which is, "C:\Program Files".

Then, I googled "notepad++ 64 json viewer plug". Knowing SourceForge.Net is a renowned download site, downloaded JSToolNpp [email protected]. I unzipped and copied JSMinNPP.dll to notePad++ root dir.

I loaded my newly installed notepad++ 64bit. I went to Settings and selected [import plug-in]. I pointed to the location of JSMinNPP.dll and clicked open.

I reloaded notepad++, went to PlugIns menu. To format one-line json string to multi-line json doc, I clicked JSTool->JSFormat or reverse multi-line json doc to one-line json string by JSTool->JSMin (json-Minified)!

All items are in this picture.

Constraint Layout Vertical Align Center

May be i did not fully understand the problem, but, centering all view inside a ConstraintLayout seems very simple. This is what I used:

< xmlns:android=""

enter image description here

Last two lines did the trick!

Flutter - Wrap text on overflow, like insert ellipsis or fade

I think the parent Container needs to be given a maxWidth of the proper size. It looks like the Text box will fill whatever space it is given above.

Visual Studio Code pylint: Unable to import 'protorpc'

I had same problem for pyodbc , I had two version of python on my Ubuntu (python3.8 and python3.9), problem was: package installed on python3.8 location but my interpreter was for python3.9. i installed python3.8 interpreter in command palette and it fixed.

Display rows with one or more NaN values in pandas dataframe

Use df[df.isnull().any(axis=1)] for python 3.6 or above.

Running Tensorflow in Jupyter Notebook

Although it's a long time after this question is being asked since I was searching so much for the same problem and couldn't find the extant solutions helpful, I write what fixed my trouble for anyone with the same issue: The point is, Jupyter should be installed in your virtual environment, meaning, after activating the tensorflow environment, run the following in the command prompt (in tensorflow virtual environment):

conda install jupyter
jupyter notebook

and then the jupyter will pop up.

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

I believe this can be solved by adding a project reference to Microsoft.EntityFrameworkCore.SqlServer.Design

Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

Microsoft.EntityFrameworkCore.SqlServer wasn't directly installed in my project, but the .Design package will install it anyway as a prerequisite.

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

Note: this solution and any other "edit the policy.xml" solution disables safety measures against arbitrary code execution vulnerabilities in ImageMagick. If you need to process input that you do not control 100%, you should use a different program (not ImageMagick).

If you're still here, you are trying to edit images that you have complete control over, know are safe, and cannot be edited by users.

There is an /etc/ImageMagick/policy.xml file that is installed by yum. It disallows almost everything (for security and to protect your system from getting overloaded with ImageMagick calls).

If you're getting a ReadImage error as above, you can change the line to:

<policy domain="coder" rights="read" pattern="LABEL" />

which should fix the issue.

The file has a bunch of documentation in it, so you should read that. For example, if you need more permissions, you can combine them like:

<policy domain="coder" rights="read|write" pattern="LABEL" />

...which is preferable to removing all permissions checks (i.e., deleting or commenting out the line).

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

I got the same error message when introducing webpack to a project I created with npm init.

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. - configuration.output.path: The provided value "dist/assets" is not an absolute path!

I started over using yarn which fixed the problem for me:

brew update
brew install yarn
brew upgrade yarn
yarn init
yarn add webpack webpack-dev-server path
touch webpack.config.js
yarn add babel-loader babel-core babel-preset-es2015 babel-preset-react --dev
yarn add html-webpack-plugin
yarn start

I found the following link helpful: Setup a React Environment Using webpack and Babel

Using media breakpoints in Bootstrap 4-alpha

I answered a similar question here

As @Syden said, the mixins will work. Another option is using SASS map-get like this..

@media (min-width: map-get($grid-breakpoints, sm)){
  .something {
    padding: 10px;

@media (min-width: map-get($grid-breakpoints, md)){
  .something {
    padding: 20px;

Bootstrap 4 Breakpoints demo

How to send custom headers with requests in Swagger UI?

DISCLAIMER: this solution is not using Header.

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

public YourResult Authorize([FromBody]BasicAuthCredentials credentials)

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

How can I mock an ES6 module import using Jest?

You have to mock the module and set the spy by yourself:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency', () => ({
  doSomething: jest.fn()

describe('myModule', () => {
  it('calls the dependency with double the input', () => {

Angular2: Cannot read property 'name' of undefined

The variable selectedHero is null in the template so you cannot bind as is. You need to use the elvis operator ?. for this case:

<input [ngModel]="selectedHero?.name" (ngModelChange)=" = $event" />

The separation of the [(ngModel)] into [ngModel] and (ngModelChange) is also needed because you can't assign to an expression that uses the elvis operator.

I also think you mean to use:

<h2>{{selectedHero?.name}} details!</h2>

instead of:

<h2>{{}} details!</h2>

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

If you want to avoid having to use -f, then you can use just

git pull

instead of

git pull --rebase

The non-rebase will fetch the changes from origin/dev and merge them into your FixForBug branch. Then, you will be able to run

git push origin FixForBug

without using -f.

sudo: docker-compose: command not found

If you have tried installing via the official docker-compose page, where you need to download the binary using curl:

curl -L`uname -s`-`uname -m` > /usr/local/bin/docker-compose

Then do not forget to add executable flag to the binary:

chmod +x /usr/local/bin/docker-compose

If docker-compose is installed using python-pip

sudo apt-get -y install python-pip
sudo pip install docker-compose

try using pip show --files docker-compose to see where it is installed.

If docker-compose is installed in user path, then try:

sudo "PATH=$PATH" docker-compose

As I see from your updated post, docker-compose is installed in user path /home/user/.local/bin and if this path is not in your local path $PATH, then try:

sudo "PATH=$PATH:/home/user/.local/bin" docker-compose

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

Follow the following steps,

  1. Update visual studio to latest version (it matters)
  2. Remove all binding redirects from web.config
  3. Add this to the .csproj file:

  4. Build the project
  5. In the bin folder there should be a (WebAppName).dll.config file
  6. It should have redirects in it, copy these to the web.config
  7. Remove the above snipped from the .csproj file

It should work

how to set start value as "0" in chartjs?

If you need use it as a default configuration, just place min: 0 inside the node defaults.scale.ticks, as follows:

defaults: {
  global: {...},
  scale: {
    ticks: { min: 0 },


Error:Conflict with dependency ''

In project ':app' you can add the following to your app/build.gradle file :

android {
 configurations.all {
    resolutionStrategy.force ''

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)

Here is the result. enter image description here

Service located in another namespace

To access services in two different namespaces you can use url like this:


To list out all your namespaces you can use:

kubectl get namespace

And for service in that namespace you can simply use:

kubectl get services -n <namespace-name>

this will help you.

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Is not required for packages in Python 3.3+

If you have in your project and you use find_packages() within it, it is necessary to have an file in every directory for packages to be automatically found.

Packages are only recognized if they include an file

UPD: If you want to use implicit namespace packages without you just have to use find_namespace_packages() instead


How to label scatterplot points by name?

Well I did not think this was possible until I went and checked. In some previous version of Excel I could not do this. I am currently using Excel 2013.

This is what you want to do in a scatter plot:

  1. right click on your data point

  2. select "Format Data Labels" (note you may have to add data labels first)

  3. put a check mark in "Values from Cells"
  4. click on "select range" and select your range of labels you want on the points

Example Graph

UPDATE: Colouring Individual Labels

In order to colour the labels individually use the following steps:

  1. select a label. When you first select, all labels for the series should get a box around them like the graph above.
  2. Select the individual label you are interested in editing. Only the label you have selected should have a box around it like the graph below.
  3. On the right hand side, as shown below, Select "TEXT OPTIONS".
  4. Expand the "TEXT FILL" category if required.
  5. Second from the bottom of the category list is "COLOR", select the colour you want from the pallet.

If you have the entire series selected instead of the individual label, text formatting changes should apply to all labels instead of just one.


How to draw a line with matplotlib?

As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2)).

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

You can try with the following way,


So that the parent jar will be fetching from the repository.

What's the fastest way of checking if a point is inside a polygon in python

Your test is good, but it measures only some specific situation: we have one polygon with many vertices, and long array of points to check them within polygon.

Moreover, I suppose that you're measuring not matplotlib-inside-polygon-method vs ray-method, but matplotlib-somehow-optimized-iteration vs simple-list-iteration

Let's make N independent comparisons (N pairs of point and polygon)?

# ... your code...
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]

M = 10000
start_time = time()
# Ray tracing
for i in range(M):
    x,y = np.random.random(), np.random.random()
    inside1 = ray_tracing_method(x,y, polygon)
print "Ray Tracing Elapsed time: " + str(time()-start_time)

# Matplotlib mplPath
start_time = time()
for i in range(M):
    x,y = np.random.random(), np.random.random()
    inside2 = path.contains_points([[x,y]])
print "Matplotlib contains_points Elapsed time: " + str(time()-start_time)


Ray Tracing Elapsed time: 0.548588991165
Matplotlib contains_points Elapsed time: 0.103765010834

Matplotlib is still much better, but not 100 times better. Now let's try much simpler polygon...

lenpoly = 5
# ... same code


Ray Tracing Elapsed time: 0.0727779865265
Matplotlib contains_points Elapsed time: 0.105288982391

onchange equivalent in angular2

In Angular you can define event listeners like in the example below:

<!-- Here you can call public methods from parental component -->
<input (change)="method_name()"> 

How to create multiple output paths in Webpack config

You definitely can return array of configurations from your webpack.config file. But it's not an optimal solution if you just want a copy of artifacts to be in the folder of your project's documentation, since it makes webpack build your code twice doubling the overall time to build.

In this case I'd recommend to use the FileManagerWebpackPlugin plugin instead:

const FileManagerPlugin = require('filemanager-webpack-plugin');
// ...
plugins: [
    // ...
    new FileManagerPlugin({
      onEnd: {
        copy: [{
          source: './dist/*.*',
          destination: './public/',

Plotting lines connecting points

You can just pass a list of the two points you want to connect to plt.plot. To make this easily expandable to as many points as you want, you could define a function like so.

import matplotlib.pyplot as plt

x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5,  1, -0.5, -1]

plt.plot(x,y, 'ro')

def connectpoints(x,y,p1,p2):
    x1, x2 = x[p1], x[p2]
    y1, y2 = y[p1], y[p2]



enter image description here

Note, that function is a general function that can connect any two points in your list together.

To expand this to 2N points, assuming you always connect point i to point i+1, we can just put it in a for loop:

import numpy as np
for i in np.arange(0,len(x),2):

In that case of always connecting point i to point i+1, you could simply do:

for i in np.arange(0,len(x),2):

In python, how do I cast a class object to a dict

I think this will work for you.

class A(object):
    def __init__(self, a, b, c, sum, version='old'):
        self.a = a
        self.b = b
        self.c = c
        self.sum = 6
        self.version = version

    def __int__(self):
        return self.sum + 9000

    def __iter__(self):
        return self.__dict__.iteritems()

a = A(1,2,3,4,5)
print dict(a)


{'a': 1, 'c': 3, 'b': 2, 'sum': 6, 'version': 5}

Spring Boot REST API - request timeout?

You can try server.connection-timeout=5000 in your From the official documentation:

server.connection-timeout= # Time in milliseconds that connectors will wait for another HTTP request before closing the connection. When not set, the connector's container-specific default will be used. Use a value of -1 to indicate no (i.e. infinite) timeout.

On the other hand, you may want to handle timeouts on the client side using Circuit Breaker pattern as I have already described in my answer here:

Angular2 change detection: ngOnChanges not firing for nested object

In my case it was changes in object value which the ngOnChange was not capturing. A few object values are modified in response of api call. Reinitializing the object fixed the issue and caused the ngOnChange to trigger in the child component.

Something like

 this.pagingObj = new Paging(); //This line did the magic
 this.pagingObj.pageNumber = response.PageNumber;

How can I get the values of data attributes in JavaScript code?

You could also grab the attributes with the getAttribute() method which will return the value of a specific HTML attribute.

var elem = document.getElementById('the-span');_x000D_
var typeId = elem.getAttribute('data-typeId');_x000D_
var type   = elem.getAttribute('data-type');_x000D_
var points = elem.getAttribute('data-points');_x000D_
var important = elem.getAttribute('data-important');_x000D_
console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`_x000D_
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>

Thymeleaf using path variables to th:href

Your code looks syntactically correct, but I think your property doesn't exist to create the URL.

I just tested it, and it works fine for me.

Try using category.idCategory instead of, for example…

  <tr th:each="category : ${categories}">
    <td th:text="${category.idCategory}"></td>
    <td th:text="${}"></td>
      <a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

If you use CMake you have to set WIN32 flag in add_executable

add_executable(${name} WIN32 ${source_files})

See CMake Doc for more information.

Android M Permissions: onRequestPermissionsResult() not being called

for kotlin users, here my extension to check and validate permissions without override onRequestPermissionResult

 * @param permissionToValidate (request and check currently permission)
 * @return recursive boolean validation callback (no need OnRequestPermissionResult)
 * */
internal fun Activity.validatePermission(
    permissionToValidate: String,
    recursiveCall: (() -> Boolean) = { false }
): Boolean {
    val permission = ContextCompat.checkSelfPermission(

    if (permission != PackageManager.PERMISSION_GRANTED) {
        if (recursiveCall()) {
            return false

        return this.validatePermission(permissionToValidate) { true }

    return true


How to get docker-compose to always re-create containers from fresh images?

docker-compose up --build


docker-compose build --no-cache

Warning comparison between pointer and integer

It should be

if (*message == '\0')

In C, simple quotes delimit a single character whereas double quotes are for strings.

Why use Redux over Facebook Flux?

I'm an early adopter and implemented a mid-large single page application using the Facebook Flux library.

As I'm a little late to the conversation I'll just point out that despite my best hopes Facebook seem to consider their Flux implementation to be a proof of concept and it has never received the attention it deserves.

I'd encourage you to play with it, as it exposes more of the inner working of the Flux architecture which is quite educational, but at the same time it does not provide many of the benefits that libraries like Redux provide (which aren't that important for small projects, but become very valuable for bigger ones).

We have decided that moving forward we will be moving to Redux and I suggest you do the same ;)

WARNING: Exception encountered during context initialization - cancelling refresh attempt

In my case, I'm using j-hipster and I had to do ./mvnw clean to overcome this warning.

CORS with spring-boot and angularjs not working

Extending WebSecurityConfigurerAdapter class and overriding configure() method in your @EnableWebSecurity class would work : Below is sample class

protected void configure(final HttpSecurity http) throws Exception {


        public CorsConfiguration getCorsConfiguration(final HttpServletRequest request) {
            return new CorsConfiguration().applyPermitDefaultValues();

Change the location of the ~ directory in a Windows install of Git Bash

I'd share what I did, which works not only for Git, but MSYS/MinGW as well.

The HOME environment variable is not normally set for Windows applications, so creating it through Windows did not affect anything else. From the Computer Properties (right-click on Computer - or whatever it is named - in Explorer, and select Properties, or Control Panel -> System and Security -> System), choose Advanced system settings, then Environment Variables... and create a new one, HOME, and assign it wherever you like.

If you can't create new environment variables, the other answer will still work. (I went through the details of how to create environment variables precisely because it's so dificult to find.)

Maven and Spring Boot - non resolvable parent pom - (Unknown host)

Obviously it's a problem with your internet connection. Check, if you can reach with your browser. If yes, check if you need to configure a proxy server. If no, you should contact your internet provider.

Here is the documentation, how you configure a proxy server for Maven:

Webpack - webpack-dev-server: command not found

The script webpack-dev-server is already installed inside ./node_modules directory. You can either install it again globally by

sudo npm install -g webpack-dev-server

or run it like this

./node_modules/webpack-dev-server/bin/webpack-dev-server.js -d --config --content-base public/ --progress --colors

. means look it in current directory.

Git pull till a particular commit

I've found the updated answer from this video, the accepted answer didn't work for me.

First clone the latest repo from git (if haven't) using git clone <HTTPs link of the project> (or using SSH) then go to the desire branch using git checkout <branch name> .

Use the command

git log

to check the latest commits. Copy the shal of the particular commit. Then use the command

git fetch origin <Copy paste the shal here>

After pressing enter key. Now use the command

git checkout FETCH_HEAD

Now the particular commit will be available to your local. Change anything and push the code using git push origin <branch name> . That's all. Check the video for reference.

Using a Glyphicon as an LI bullet point (Bootstrap 3)

Using Font Awesome 5, the markup is a bit more complex than the previouis answer. Per the FA documentation, the markup should be:

<ul class="fa-ul">
  <li><span class="fa-li"><i class="fas fa-check-square"></i></span>List icons can</li>
  <li><span class="fa-li"><i class="fas fa-check-square"></i></span>be used to</li>
  <li><span class="fa-li"><i class="fas fa-spinner fa-pulse"></i></span>replace bullets</li>
  <li><span class="fa-li"><i class="far fa-square"></i></span>in lists</li>

Calculate percentage Javascript

<div id="contentse "><br>
      <h2>Percentage Calculator</h2>
    <form action="/charactercount" class="align-items-center" style="border: 1px solid #eee;padding:15px;" method="post" enctype="multipart/form-data" name="form">
        <input type="hidden" name="csrfmiddlewaretoken" value="NCBdw9beXfKV07Tc1epTBPqJ0gzfkmHNXKrAauE34n3jn4TGeL8Vv6miOShhqv6O">
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        <br><div class="input-float" style="float: left;"> what is <input type="text" id="aa" required=""> % of <input type="text" id="ab"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculatea()"> &nbsp; <input type="text" id="ac" readonly="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><br style="clear: both;"> </div><br>
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        <div class="input-float" style="float: left;"><input type="text" id="ba"> is what percent of <input type="text" id="bb"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculateb()"> &nbsp; <input type="text" id="bc" readonly=""> &nbsp; % </div><br style="clear: both;"></div><br>
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        Find percentage change(increase/decrease) <br><br>
        <div class="input-float" style="float: left;">from <input type="text" id="ca"> to <input type="text" id="cb">&nbsp;?  </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculatec()"> &nbsp; <input type="text" id="cc" readonly="">&nbsp;%</div><br style="clear: both;"></div>

Live example here: setool-percentage-calculator

How to customize the configuration file of the official PostgreSQL Docker image?

Using docker compose you can mount a volume with Example:

version: '2'

    image: postgres:10.9-alpine
      - postgres:/var/lib/postgresql/data:z
      - ./docker/postgres/
      - 5432:5432

Error inflating class

Make sure your drawables for the menu are in the correct folder, mine where put in drawablev21 hence this caused a nullpointer to the resource.

Fixed it buy moving my icons to drawables folder

Using an authorization header with Fetch in React Native

Example fetch with authorization header:

fetch('URL_GOES_HERE', { 
   method: 'post', 
   headers: new Headers({
     'Authorization': 'Basic '+btoa('username:password'), 
     'Content-Type': 'application/x-www-form-urlencoded'
   body: 'A=1&B=2'

Run / Open VSCode from Mac Terminal

To set it up, launch VS Code. Then open the Command Palette (??P) and type shell command to find the Shell Command: Install 'code' command in PATH command.enter image description here

Attribute Error: 'list' object has no attribute 'split'

I think you've actually got a wider confusion here.

The initial error is that you're trying to call split on the whole list of lines, and you can't split a list of strings, only a string. So, you need to split each line, not the whole thing.

And then you're doing for points in Type, and expecting each such points to give you a new x and y. But that isn't going to happen. Types is just two values, x and y, so first points will be x, and then points will be y, and then you'll be done. So, again, you need to loop over each line and get the x and y values from each line, not loop over a single Types from a single line.

So, everything has to go inside a loop over every line in the file, and do the split into x and y once for each line. Like this:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")

    for line in readfile:
        Type = line.split(",")
        x = Type[1]
        y = Type[2]


As a side note, you really should close the file, ideally with a with statement, but I'll get to that at the end.

Interestingly, the problem here isn't that you're being too much of a newbie, but that you're trying to solve the problem in the same abstract way an expert would, and just don't know the details yet. This is completely doable; you just have to be explicit about mapping the functionality, rather than just doing it implicitly. Something like this:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = readfile.readlines()
    Types = [line.split(",") for line in readlines]
    xs = [Type[1] for Type in Types]
    ys = [Type[2] for Type in Types]
    for x, y in zip(xs, ys):


Or, a better way to write that might be:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    # Use with to make sure the file gets closed
    with open(filename, "r") as readfile:
        # no need for readlines; the file is already an iterable of lines
        # also, using generator expressions means no extra copies
        types = (line.split(",") for line in readfile)
        # iterate tuples, instead of two separate iterables, so no need for zip
        xys = ((type[1], type[2]) for type in types)
        for x, y in xys:


Finally, you may want to take a look at NumPy and Pandas, libraries which do give you a way to implicitly map functionality over a whole array or frame of data almost the same way you were trying to.

foreach loop in angularjs

you have to use nested angular.forEach loops for JSON as shown below:

 var values = [

        angular.forEach(value,function(v1,k1){//this is nested angular.forEach loop

Plot width settings in ipython notebook

If you use %pylab inline you can (on a new line) insert the following command:

%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)

This will set all figures in your document (unless otherwise specified) to be of the size (10, 6), where the first entry is the width and the second is the height.

See this SO post for more details.

Error: Cannot find module 'webpack'

I was having this issue on OS X and it seemed to be caused by a version mismatch between my globally installed webpack and my locally installed webpack-dev-server. Updating both to the latest version got rid of the issue.

how do I get the bullet points of a <ul> to center with the text?

You can do that with list-style-position: inside; on the ul element :

ul {
    list-style-position: inside;

See working fiddle

Managing jQuery plugin dependency in webpack

For global access to jquery then several options exist. In my most recent webpack project, I wanted global access to jquery so I added the following to my plugins declarations:

 plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"

This then means that jquery is accessible from within the JavaScript source code via global references $ and jQuery.

Of course, you need to have also installed jquery via npm:

$ npm i jquery --save

For a working example of this approach please feel free to fork my app on github

What are Keycloak's OAuth2 / OpenID Connect endpoints?

With version 1.9.3.Final, Keycloak has a number of OpenID endpoints available. These can be found at /auth/realms/{realm}/.well-known/openid-configuration. Assuming your realm is named demo, that endpoint will produce a JSON response similar to this.

  "issuer": "http://localhost:8080/auth/realms/demo",
  "authorization_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/auth",
  "token_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/token",
  "token_introspection_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/token/introspect",
  "userinfo_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/userinfo",
  "end_session_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/logout",
  "jwks_uri": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/certs",
  "grant_types_supported": [
  "response_types_supported": [
    "id_token token",
    "code id_token",
    "code token",
    "code id_token token"
  "subject_types_supported": [
  "id_token_signing_alg_values_supported": [
  "response_modes_supported": [
  "registration_endpoint": "http://localhost:8080/auth/realms/demo/clients-registrations/openid-connect"

As far as I have found, these endpoints implement the Oauth 2.0 spec.

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

You can use toStringAsFixed in order to display the limited digits after decimal points. toStringAsFixed returns a decimal-point string-representation. toStringAsFixed accepts an argument called fraction Digits which is how many digits after decimal we want to display. Here is how to use it.

double pi = 3.1415926;
const val = pi.toStringAsFixed(2); // 3.14

ReferenceError: describe is not defined NodeJs

if you are using vscode, want to debug your files

I used tdd before, it throw ReferenceError: describe is not defined

But, when I use bdd, it works!

waste half day to solve it....

      "type": "node",
      "request": "launch",
      "name": "Mocha Tests",
      "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
      "args": [
        "bdd",// set to bdd, not tdd
      "internalConsoleOptions": "openOnSessionStart"

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

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

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


Android Error [Attempt to invoke virtual method 'void' on a null object reference]

Try this hope it will work, my code is works fine

Toolbar toolbar = findViewById(;


IndexError: too many indices for array

I think the problem is given in the error message, although it is not very easy to spot:

IndexError: too many indices for array
xs  = data[:, col["l1"     ]]

'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None).

This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None) does not throw an Error, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile function.

I highly recommend in your for loop inserting:


This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1 list (i.e. one file) that is giving the issue.

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

I had this problem.

Solution: Update the path of the image.

If the path contains (for example: \n or \t or \a) it adds to the corruption. Therefore, change every back-slash "\" with front-slash "/" and it will not make create error but fix the issue of reading path.

Also double check the file path/name. any typo in the name or path also gives the same error.

- java.lang.NullPointerException - setText on null object reference

private void fillTextView (int id, String text) {
    TextView tv = (TextView) findViewById(id);

If this is where you're getting the null pointer exception, there was no view found for the id that you passed into findViewById(), and the actual exception is thrown when you try to call a function setText() on null. You should post your XML for R.layout.activity_main, as it's hard to tell where things went wrong just by looking at your code.

More reading on null pointers: What is a NullPointerException, and how do I fix it?

In Chart.js set chart title, name of x axis and y axis?

            // style={{ width: "50%", height: "50%" }}
              scales: {
                yAxes: [
                    scaleLabel: {
                      display: true,
                      labelString: "Probability",
                xAxes: [
                    scaleLabel: {
                      display: true,
                      labelString: "Hours",

Maven Jacoco Configuration - Exclude classes/packages from report not working

Use sonar.coverage.exclusions property.

mvn clean install -Dsonar.coverage.exclusions=**/*

This should exclude the classes from coverage calculation.

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

Spring Boot Multiple Datasource

once you start work with jpa and some driver is in your class path spring boot right away puts it inside as your data source (e.g h2 ) for using the defult data source therefore u will need only to define

spring.datasource.url= jdbc:mysql://localhost:3306/

if we go one step farther and u want to use two I would reccomend to use two data sources such as explained here : Spring Boot Configure and Use Two DataSources

How to decode a QR-code image in (preferably pure) Python?

For Windows using ZBar


To decode:

from PIL import Image
from pyzbar import pyzbar

img ='My-Image.jpg')
output = pyzbar.decode(img)

Alternatively, you can also try using ZBarLight by setting it up as mentioned here:

Oracle listener not running and won't start

In my case somehow windows listener service had stopped working so I was not able to connect to Qracle using SQL Developer. However I was able to connect through sqlplus.

Below solution worked for me:

First, ensure that your listener service is running.

C:\Documents and Settings\ME>lsnrctl status 

If the listener service is not running, re-start the listener service using the Windows task manager or use the DOS command line utility to re-start the Windows service with the net start command:

C:\Documents and Settings\ME>net start OracleOraDb10g_home1TNSListener 

Try to start the listener service using lsnrctl from DOS prompt.

lsnrctl start

How to plot a function curve in R

As sjdh also mentioned, ggplot2 comes to the rescue. A more intuitive way without making a dummy data set is to use xlim:

eq <- function(x){sin(x)}
base <- ggplot() + xlim(0, 30)
base + geom_function(fun=eq)

Additionally, for a smoother graph we can set the number of points over which the graph is interpolated using n:

base + geom_function(fun=eq, n=10000)

Plotting a fast Fourier transform in Python

There are already great solutions on this page, but all have assumed the dataset is uniformly/evenly sampled/distributed. I will try to provide a more general example of randomly sampled data. I will also use this MATLAB tutorial as an example:

Adding the required modules:

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
import scipy.signal

Generating sample data:

N = 600 # Number of samples
t = np.random.uniform(0.0, 1.0, N) # Assuming the time start is 0.0 and time end is 1.0
S = 1.0 * np.sin(50.0 * 2 * np.pi * t) + 0.5 * np.sin(80.0 * 2 * np.pi * t)
X = S + 0.01 * np.random.randn(N) # Adding noise

Sorting the data set:

order = np.argsort(t)
ts = np.array(t)[order]
Xs = np.array(X)[order]


T = (t.max() - t.min()) / N # Average period
Fs = 1 / T # Average sample rate frequency
f = Fs * np.arange(0, N // 2 + 1) / N; # Resampled frequency vector
X_new, t_new = scipy.signal.resample(Xs, N, ts)

Plotting the data and resampled data:

plt.xlim(0, 0.1)
plt.plot(t_new, X_new, label="resampled")
plt.plot(ts, Xs, label="org")

Enter image description here

Now calculating the FFT:

Y = scipy.fftpack.fft(X_new)
P2 = np.abs(Y / N)
P1 = P2[0 : N // 2 + 1]
P1[1 : -2] = 2 * P1[1 : -2]

plt.plot(f, P1)

Enter image description here

P.S. I finally got time to implement a more canonical algorithm to get a Fourier transform of unevenly distributed data. You may see the code, description, and example Jupyter notebook here.

Difference between WebStorm and PHPStorm

I couldn't find any major points on JetBrains' website and even Google didn't help that much.

You should train your search-fu twice as harder.


NOTE: PhpStorm includes all the functionality of WebStorm (HTML/CSS Editor, JavaScript Editor) and adds full-fledged support for PHP and Databases/SQL.

Their forum also has quite few answers for such question.

Basically: PhpStorm = WebStorm + PHP + Database support

WebStorm comes with certain (mainly) JavaScript oriented plugins bundled by default while they need to be installed manually in PhpStorm (if necessary).

At the same time: plugins that require PHP support would not be able to install in WebStorm (for obvious reasons).

P.S. Since WebStorm has different release cycle than PhpStorm, it can have new JS/CSS/HTML oriented features faster than PhpStorm (it's all about platform builds used).

For example: latest stable PhpStorm is v7.1.4 while WebStorm is already on v8.x. But, PhpStorm v8 will be released in approximately 1 month (accordingly to their road map), which means that stable version of PhpStorm will include some of the features that will only be available in WebStorm v9 (quite few months from now, lets say 2-3-5) -- if using/comparing stable versions ONLY.

UPDATE (2016-12-13): Since 2016.1 version PhpStorm and WebStorm use the same version/build numbers .. so there is no longer difference between the same versions: functionality present in WebStorm 2016.3 is the same as in PhpStorm 2016.3 (if the same plugins are installed, of course).

Everything that I know atm. is that PHPStorm doesn't support JS part like Webstorm

That's not correct (your wording). Missing "extra" technology in PhpStorm (for example: node, angularjs) does not mean that basic JavaScript support has missing functionality. Any "extras" can be easily installed (or deactivated, if not required).

UPDATE (2016-12-13): Here is the list of plugins that are bundled with WebStorm 2016.3 but require manual installation in PhpStorm 2016.3 (if you need them, of course):

  • Cucumber.js
  • Dart
  • EditorConfig
  • EJS
  • Handelbars/Mustache
  • Java Server Pages (JSP) Integration
  • Karma
  • LiveEdit
  • Meteor
  • PhoneGap/Cordova Plugin
  • Polymer & Web Components
  • Pug (ex-Jade)
  • Spy-js
  • Stylus support
  • Yeoman

Exposing the current state name with ui router

this is how I do it


var module = angular.module('yourModuleName', ['ui.router']); ['$rootScope', '$state', '$stateParams',
                      function ($rootScope,   $state,   $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams; 


<pre id="uiRouterInfo">
      $state = {{$}}
      $stateParams = {{$stateParams}}
      $state full url = {{ $state.$current.url.source }}    


Where should my npm modules be installed on Mac OS X?

npm root -g

to check the npm_modules global location

Transport endpoint is not connected

I get this error from the sshfs command from Fedora 17 linux to debian linux on the Mindstorms EV3 brick over the LAN and through a wireless connection.

Bash command:

el@defiant /mnt $ sshfs [email protected]:/root -p 22 /mnt/ev3
fuse: bad mount point `/mnt/ev3': Transport endpoint is not connected

This is remedied with the following command and trying again:

fusermount -u /mnt/ev3

These additional sshfs options prevent the above error from concurring:

sudo sshfs -d -o allow_other -o reconnect -o ServerAliveInterval=15 [email protected]:/var/lib/redmine/plugins /mnt -p 12345 -C

In order to use allow_other above, you need to uncomment the last line in /etc/fuse.conf:

# Set the maximum number of FUSE mounts allowed to non-root users.
# The default is 1000.
#mount_max = 1000

# Allow non-root users to specify the 'allow_other' or 'allow_root'
# mount options.


Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.

# Change minor ticks to show every 5. (20/4 = 5)

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

How to create JNDI context in Spring Boot with Embedded Tomcat Container

In SpringBoot 2.1, I found another solution. Extend standard factory class method getTomcatWebServer. And then return it as a bean from anywhere.

public class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        System.setProperty("catalina.useNaming", "true");
        return new TomcatWebServer(tomcat, getPort() >= 0);

public class TomcatConfiguration {
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new CustomTomcatServletWebServerFactory();

        return factory;

Loading resources from context.xml doesn't work though. Will try to find out.

The listener supports no services

Check local_listener definition in your spfile or pfile. In my case, the problem was with pfile, I had moved the pfile from a similar environment and it had LISTENER_sid as LISTENER and not just LISTENER.

How to clear a chart from a canvas so that hover events cannot be triggered?

First put chart in some variable then history it next time before init

#Check if myChart object exist then distort it

    if($scope.myChart) {

    $scope.myChart  = new Chart(targetCanvas

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

if path.exists(Score_file):
      try : 
         with open(Score_file , "rb") as prev_Scr:

            return Unpickler(prev_Scr).load()

    except EOFError : 

        return dict() 

chart.js load totally new data

I had huge problems with this

First I tried .clear() then I tried .destroy() and I tried setting my chart reference to null

What finally fixed the issue for me: deleting the <canvas> element and then reappending a new <canvas> to the parent container

There's a million ways to do this:

var resetCanvas = function () {
  $('#results-graph').remove(); // this is my <canvas> element
  $('#graph-container').append('<canvas id="results-graph"><canvas>');
  canvas = document.querySelector('#results-graph'); // why use jQuery?
  ctx = canvas.getContext('2d');
  ctx.canvas.width = $('#graph').width(); // resize to parent width
  ctx.canvas.height = $('#graph').height(); // resize to parent height

  var x = canvas.width/2;
  var y = canvas.height/2;
  ctx.font = '10pt Verdana';
  ctx.textAlign = 'center';
  ctx.fillText('This text is centered on the canvas', x, y);

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

Just make sure that the controller name is the same as yours DeliveryController if you renamed it (it will not change automatically!). if you rename the project name too you should delete the reference to this project from the Bin folder. Don't forget to specify the method get or post.

How do I change the font size of a UILabel in Swift?

In swift3, suppose your UILable name is myLable and you want to change its font size do this

myLable.font = UIFont.systemFont(ofSize: 10)

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

only start listner then u can connect with database. command run on editor:

lsnrctl start

its work fine.

git error: failed to push some refs to remote

before push you have to add and commit the changes or do git push -f origin master

python to arduino serial read & write

You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.

while running:  
    # Serial write section
    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    time.sleep(6) # with the port open, the response will be buffered 
                  # so wait a bit longer for response here

    # Serial read section
    msg = # read everything in the input buffer
    print ("Message from arduino: ")
    print (msg)

The Python function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.

On the Arduino side, you should consider what happens in your loop function when no data is available.

void loop()
  // serial read section
  while (Serial.available()) // this will be skipped if no data present, leading to
                             // the code sitting in the delay function below
    delay(30);  //delay to allow buffer to fill 
    if (Serial.available() >0)
      char c =;  //gets one byte from serial buffer
      readString += c; //makes the string readString

Instead, wait at the start of the loop function until data arrives:

void loop()
  while (!Serial.available()) {} // wait for data to arrive
  // serial read section
  while (Serial.available())
    // continue as before


Here's what I get when interfacing with your Arduino app from Python:

>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
>>> s.readline()
'Arduino received: 2\r\n'

So that seems to be working fine.

In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:

import serial
import syslog
import time

#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X

ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino

i = 0

while (i < 4):
    # Serial write section

    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    time.sleep(1) # I shortened this to match the new value in your Arduino code

    # Serial read section
    msg = # read all characters in buffer
    print ("Message from arduino: ")
    print (msg)
    i = i + 1
    print "Exiting"

Here's the output of the above now:

$ python
Python value sent:
Message from arduino:
Arduino received: 63
Arduino sends: 1

Python value sent:
Message from arduino:
Arduino received: 63
Arduino sends: 1

Python value sent:
Message from arduino:
Arduino received: 63
Arduino sends: 1

Python value sent:
Message from arduino:
Arduino received: 63
Arduino sends: 1


Multidimensional arrays in Swift

For future readers, here is an elegant solution(5x5):

var matrix = [[Int]](repeating: [Int](repeating: 0, count: 5), count: 5)

and a dynamic approach:

var matrix = [[Int]]() // creates an empty matrix
var row = [Int]() // fill this row
matrix.append(row) // add this row

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

I had this problem on my developent environment with Visual Studio.

What helped me was to Clean Solution in Visual Studio and then do a rebuild.

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.

Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .map(e -> new DataSet(e.getKey(), e.getValue()))

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;

Extracting text OpenCV

this is a VB.NET version of the answer from dhanushka using EmguCV.

A few functions and structures in EmguCV need different consideration than the C# version with OpenCVSharp

Imports Emgu.CV
Imports Emgu.CV.Structure
Imports Emgu.CV.CvEnum
Imports Emgu.CV.Util

        Dim input_file As String = "C:\your_input_image.png"
        Dim large As Mat = New Mat(input_file)
        Dim rgb As New Mat
        Dim small As New Mat
        Dim grad As New Mat
        Dim bw As New Mat
        Dim connected As New Mat
        Dim morphanchor As New Point(0, 0)

        '//downsample and use it for processing
        CvInvoke.PyrDown(large, rgb)
        CvInvoke.CvtColor(rgb, small, ColorConversion.Bgr2Gray)

        '//morphological gradient
        Dim morphKernel As Mat = CvInvoke.GetStructuringElement(ElementShape.Ellipse, New Size(3, 3), morphanchor)
        CvInvoke.MorphologyEx(small, grad, MorphOp.Gradient, morphKernel, New Point(0, 0), 1, BorderType.Isolated, New MCvScalar(0))

        '// binarize
        CvInvoke.Threshold(grad, bw, 0, 255, ThresholdType.Binary Or ThresholdType.Otsu)

        '// connect horizontally oriented regions
        morphKernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, New Size(9, 1), morphanchor)
        CvInvoke.MorphologyEx(bw, connected, MorphOp.Close, morphKernel, morphanchor, 1, BorderType.Isolated, New MCvScalar(0))

        '// find contours
        Dim mask As Mat = Mat.Zeros(bw.Size.Height, bw.Size.Width, DepthType.Cv8U, 1)  '' MatType.CV_8UC1
        Dim contours As New VectorOfVectorOfPoint
        Dim hierarchy As New Mat

        CvInvoke.FindContours(connected, contours, hierarchy, RetrType.Ccomp, ChainApproxMethod.ChainApproxSimple, Nothing)

        '// filter contours
        Dim idx As Integer
        Dim rect As Rectangle
        Dim maskROI As Mat
        Dim r As Double
        For Each hierarchyItem In hierarchy.GetData
            rect = CvInvoke.BoundingRectangle(contours(idx))
            maskROI = New Mat(mask, rect)
            maskROI.SetTo(New MCvScalar(0, 0, 0))

            '// fill the contour
            CvInvoke.DrawContours(mask, contours, idx, New MCvScalar(255), -1)

            '// ratio of non-zero pixels in the filled region
            r = CvInvoke.CountNonZero(maskROI) / (rect.Width * rect.Height)

            '/* assume at least 45% of the area Is filled if it contains text */
            '/* constraints on region size */
            '/* these two conditions alone are Not very robust. better to use something 
            'Like the number of significant peaks in a horizontal projection as a third condition */
            If r > 0.45 AndAlso rect.Height > 8 AndAlso rect.Width > 8 Then
                'draw green rectangle
                CvInvoke.Rectangle(rgb, rect, New MCvScalar(0, 255, 0), 2)
            End If
            idx += 1
        rgb.Save(IO.Path.Combine(Application.StartupPath, "rgb.jpg"))

Start redis-server with config file

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

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


sudo apt-get install redis-server

start with conf:

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

stop with conf:

redis-ctl shutdown

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


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

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


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

Remove x-axis label/text in chart.js

Inspired by christutty's answer, here is a solution that modifies the source but has not been tested thoroughly. I haven't had any issues yet though.

In the defaults section, add this line around line 71:

// Boolean - Omit x-axis labels
omitXLabels: true,

Then around line 2215, add this in the buildScale method:

//if omitting x labels, replace labels with empty strings           
    var newLabels=[];
    for(var i=0;i<labels.length;i++){

This preserves the tool tips also.

import error: 'No module named' *does* exist

If you have a script with the same name as your module in another directory, it will use that instead. For example:

|  |
|  |
|  |

This will make it so that the first is being used, not the second one.

Removing Data From ElasticSearch

Deleting the index will delete the mapping and type along. you can delete all rows by the following query

curl -XDELETE 'localhost:9200/twitter/tweet/_query?pretty' -d'
   "query": { 

However for above query you need to install delete-by-query plugin as of Elasticsearch's 2.0.0-beta1 delete-by-query was removed from main api

Install delete-by-query plugin

sudo bin/plugin install delete-by-query

For more

Bootstrap Align Image with text

Try using .pull-left to left align image along with text.


<p>At the time all text elements goes here.At the time all text elements goes here. At the time all text elements goes here.<img src="images/hello-missing.jpg" class="pull-left img-responsive" style="padding:15px;" /> to uncovering the truth .</p>

Peak signal detection in realtime timeseries data

Here is a (non-idiomatic) Scala version of the smoothed z-score algorithm:

  * Smoothed zero-score alogrithm shamelessly copied from
  * Uses a rolling mean and a rolling deviation (separate) to identify peaks in a vector
  * @param y - The input vector to analyze
  * @param lag - The lag of the moving window (i.e. how big the window is)
  * @param threshold - The z-score at which the algorithm signals (i.e. how many standard deviations away from the moving mean a peak (or signal) is)
  * @param influence - The influence (between 0 and 1) of new signals on the mean and standard deviation (how much a peak (or signal) should affect other values near it)
  * @return - The calculated averages (avgFilter) and deviations (stdFilter), and the signals (signals)
private def smoothedZScore(y: Seq[Double], lag: Int, threshold: Double, influence: Double): Seq[Int] = {
  val stats = new SummaryStatistics()

  // the results (peaks, 1 or -1) of our algorithm
  val signals = mutable.ArrayBuffer.fill(y.length)(0)

  // filter out the signals (peaks) from our original list (using influence arg)
  val filteredY =[mutable.ArrayBuffer]

  // the current average of the rolling window
  val avgFilter = mutable.ArrayBuffer.fill(y.length)(0d)

  // the current standard deviation of the rolling window
  val stdFilter = mutable.ArrayBuffer.fill(y.length)(0d)

  // init avgFilter and stdFilter
  y.take(lag).foreach(s => stats.addValue(s))

  avgFilter(lag - 1) = stats.getMean
  stdFilter(lag - 1) = Math.sqrt(stats.getPopulationVariance) // getStandardDeviation() uses sample variance (not what we want)

  // loop input starting at end of rolling window
  y.zipWithIndex.slice(lag, y.length - 1).foreach {
    case (s: Double, i: Int) =>
      // if the distance between the current value and average is enough standard deviations (threshold) away
      if (Math.abs(s - avgFilter(i - 1)) > threshold * stdFilter(i - 1)) {
        // this is a signal (i.e. peak), determine if it is a positive or negative signal
        signals(i) = if (s > avgFilter(i - 1)) 1 else -1
        // filter this signal out using influence
        filteredY(i) = (influence * s) + ((1 - influence) * filteredY(i - 1))
      } else {
        // ensure this signal remains a zero
        signals(i) = 0
        // ensure this value is not filtered
        filteredY(i) = s

      // update rolling average and deviation
      filteredY.slice(i - lag, i).foreach(s => stats.addValue(s))
      avgFilter(i) = stats.getMean
      stdFilter(i) = Math.sqrt(stats.getPopulationVariance) // getStandardDeviation() uses sample variance (not what we want)


  signals.zipWithIndex.foreach {
    case(x: Int, idx: Int) =>
      if (x == 1) {
        println(idx + " " + y(idx))

  val data = { case (s: Double, i: Int) => Map("x" -> i, "y" -> s, "name" -> "y", "row" -> "data") } ++ { case (s: Double, i: Int) => Map("x" -> i, "y" -> s, "name" -> "avgFilter", "row" -> "data") } ++ { case (s: Double, i: Int) => Map("x" -> i, "y" -> (s - threshold * stdFilter(i)), "name" -> "lower", "row" -> "data") } ++ { case (s: Double, i: Int) => Map("x" -> i, "y" -> (s + threshold * stdFilter(i)), "name" -> "upper", "row" -> "data") } ++ { case (s: Int, i: Int) => Map("x" -> i, "y" -> s, "name" -> "signal", "row" -> "signal") }

  Vegas("Smoothed Z")
    .encodeX("x", Quant)
    .encodeY("y", Quant)
    .encodeRow("row", Ordinal)

  return signals

Here's a test that returns the same results as the Python and Groovy versions:

val y = List(1d, 1d, 1.1d, 1d, 0.9d, 1d, 1d, 1.1d, 1d, 0.9d, 1d, 1.1d, 1d, 1d, 0.9d, 1d, 1d, 1.1d, 1d, 1d,
  1d, 1d, 1.1d, 0.9d, 1d, 1.1d, 1d, 1d, 0.9d, 1d, 1.1d, 1d, 1d, 1.1d, 1d, 0.8d, 0.9d, 1d, 1.2d, 0.9d, 1d,
  1d, 1.1d, 1.2d, 1d, 1.5d, 1d, 3d, 2d, 5d, 3d, 2d, 1d, 1d, 1d, 0.9d, 1d,
  1d, 3d, 2.6d, 4d, 3d, 3.2d, 2d, 1d, 1d, 0.8d, 4d, 4d, 2d, 2.5d, 1d, 1d, 1d)

val lag = 30
val threshold = 5d
val influence = 0d

smoothedZScore(y, lag, threshold, influence)

vegas chart of result

Gist here

Plot mean and standard deviation

You may find an answer with this example :

Demo of errorbar function with different ways of specifying error bars.

Errors can be specified as a constant value (as shown in ``),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.

N x 1:
    Error varies for each point, but the error values are symmetric (i.e. the
    lower and upper values are equal).

2 x N:
    Error varies for each point, and the lower and upper limits (in that order)
    are different (asymmetric case)

In addition, this example demonstrates how to use log scale with errorbar.
import numpy as np
import matplotlib.pyplot as plt

# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]

fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')

ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')

Which plots this:

enter image description here

What is the optimal algorithm for the game 2048?

This is not a direct answer to OP's question, this is more of the stuffs (experiments) I tried so far to solve the same problem and obtained some results and have some observations that I want to share, I am curious if we can have some further insights from this.

I just tried my minimax implementation with alpha-beta pruning with search-tree depth cutoff at 3 and 5. I was trying to solve the same problem for a 4x4 grid as a project assignment for the edX course ColumbiaX: CSMM.101x Artificial Intelligence (AI).

I applied convex combination (tried different heuristic weights) of couple of heuristic evaluation functions, mainly from intuition and from the ones discussed above:

  1. Monotonicity
  2. Free Space Available

In my case, the computer player is completely random, but still i assumed adversarial settings and implemented the AI player agent as the max player.

I have 4x4 grid for playing the game.


If I assign too much weights to the first heuristic function or the second heuristic function, both the cases the scores the AI player gets are low. I played with many possible weight assignments to the heuristic functions and take a convex combination, but very rarely the AI player is able to score 2048. Most of the times it either stops at 1024 or 512.

I also tried the corner heuristic, but for some reason it makes the results worse, any intuition why?

Also, I tried to increase the search depth cut-off from 3 to 5 (I can't increase it more since searching that space exceeds allowed time even with pruning) and added one more heuristic that looks at the values of adjacent tiles and gives more points if they are merge-able, but still I am not able to get 2048.

I think it will be better to use Expectimax instead of minimax, but still I want to solve this problem with minimax only and obtain high scores such as 2048 or 4096. I am not sure whether I am missing anything.

Below animation shows the last few steps of the game played by the AI agent with the computer player:

enter image description here

Any insights will be really very helpful, thanks in advance. (This is the link of my blog post for the article: and the youtube video:

The following animation shows the last few steps of the game played where the AI player agent could get 2048 scores, this time adding the absolute value heuristic too:

enter image description here

The following figures show the game tree explored by the player AI agent assuming the computer as adversary for just a single step:

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--


enter image description here

Simple linked list in C++

This is the most simple example I can think of in this case and is not tested. Please consider that this uses some bad practices and does not go the way you normally would go with C++ (initialize lists, separation of declaration and definition, and so on). But that are topics I can't cover here.

#include <iostream>
using namespace std;

class LinkedList{
    // Struct inside the class LinkedList
    // This is one node which is not needed by the caller. It is just
    // for internal work.
    struct Node {
        int x;
        Node *next;

// public member
    // constructor
        head = NULL; // set head to NULL

    // destructor
        Node *next = head;
        while(next) {              // iterate over all elements
            Node *deleteMe = next;
            next = next->next;     // save pointer to the next element
            delete deleteMe;       // delete the current entry
    // This prepends a new value at the beginning of the list
    void addValue(int val){
        Node *n = new Node();   // create new Node
        n->x = val;             // set value
        n->next = head;         // make the node point to the next node.
                                //  If the list is empty, this is NULL, so the end of the list --> OK
        head = n;               // last but not least, make the head point at the new node.

    // returns the first element in the list and deletes the Node.
    // caution, no error-checking here!
    int popValue(){
        Node *n = head;
        int ret = n->x;

        head = head->next;
        delete n;
        return ret;

// private member
    Node *head; // this is the private member variable. It is just a pointer to the first Node

int main() {
    LinkedList list;


    cout << list.popValue() << endl;
    cout << list.popValue() << endl;
    cout << list.popValue() << endl;
    // because there is no error checking in popValue(), the following
    // is undefined behavior. Probably the program will crash, because
    // there are no more values in the list.
    // cout << list.popValue() << endl;
    return 0;

I would strongly suggest you to read a little bit about C++ and Object oriented programming. A good starting point could be this:

EDIT: added a pop function and some output. As you can see the program pushes 3 values 5, 10, 20 and afterwards pops them. The order is reversed afterwards because this list works in stack mode (LIFO, Last in First out)

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.


Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:



Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like


All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this


NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.


After adding all five (5) JAR files the "Libraries" folder should look something like this:


IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:



That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while ( {



At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

How to use Monitor (DDMS) tool to debug application

I think that I got a solution for this. You don't have to start monitor but you can use DDMS instead almost like in Eclipse.

Start Android Studio-> pick breakpoint-> Run-> Debug-> Go to %sdk\tools in Terminal window and run ddms.bat to run DDMS without Monitor running (since it won't let you run ADB). You can now start profiling or debug step-by-step.

Hope this helps you.

See image here

Visual Studio breakpoints not being hit

If any of your components are Strong Named (signed), then all need to be. If you, as I did, add a project and reference it from a Strong Named project/component, neglecting to sign your new component, debugging will be as if your new component is an external one and you will not be able to step into it. So make sure all your components are signed, or none.

enter image description here

Convert floats to ints in Pandas?

To modify the float output do this:

df= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)


0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000

pd.options.display.float_format = '{:,.0f}'.format


0  0
1  1
2  2
3  3
4  4

multiple plot in one figure in Python

Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.

In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')

SSRS expression to format two decimal places does not show zeros

If you want to always display some value after decimal for example "12.00" or "12.23" Then use just like below , it worked for me

FormatNumber("145.231000",2) Which will display 145.23

FormatNumber("145",2) Which will display 145.00

Spark java.lang.OutOfMemoryError: Java heap space

Have a look at the start up scripts a Java heap size is set there, it looks like you're not setting this before running Spark worker.

# Set SPARK_MEM if it isn't already set since we also use it for this process
export SPARK_MEM

# Set JAVA_OPTS to be able to load native libraries and to set heap size

You can find the documentation to deploy scripts here.

The program can't start because MSVCR110.dll is missing from your computer

You can download the required files from the Microsoft website or online or reinstall the Visual studio 2012 to fix this.

Get distance between two points in canvas

To find the distance between 2 points, you need to find the length of the hypotenuse in a right angle triangle with a width and height equal to the vertical and horizontal distance:

Math.hypot(endX - startX, endY - startY)

iOS 7 - Failing to instantiate default view controller

Using Interface Builder :

Check if 'Is initial view controller' is set. You can set it using below steps :

  1. Select your view controller (which is to be appeared as initial screen).
  2. Select Attribute inspector from Utilities window.
  3. Select 'Is Initial View Controller' from View Controller section (if not).

If you have done this step and still getting error then uncheck and do it again.

Steps to solve problem

Using programmatically :

Objective-C :

        self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

        UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"]; // <storyboard id>

        self.window.rootViewController = viewController;
        [self.window makeKeyAndVisible];

        return YES;

Swift :

        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

        var objMainViewController: MainViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainController") as! MainViewController

        self.window?.rootViewController = objMainViewController


        return true

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I had a same issue. It was working fine on the local machine but it had issues on the server. I have changed the SMTP setting. It works fine for me.

If you're using GoDaddy Plesk Hosting, use the following SMTP details.

Host =
Port = 25 

How do I compute the intersection point of two lines?

Unlike other suggestions, this is short and doesn't use external libraries like numpy. (Not that using other libraries is's nice not need to, especially for such a simple problem.)

def line_intersection(line1, line2):
    xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
    ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])

    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]

    div = det(xdiff, ydiff)
    if div == 0:
       raise Exception('lines do not intersect')

    d = (det(*line1), det(*line2))
    x = det(d, xdiff) / div
    y = det(d, ydiff) / div
    return x, y

print line_intersection((A, B), (C, D))

And FYI, I would use tuples instead of lists for your points. E.g.

A = (X, Y)

EDIT: Initially there was a typo. That was fixed Sept 2014 thanks to @zidik.

This is simply the Python transliteration of the following formula, where the lines are (a1, a2) and (b1, b2) and the intersection is p. (If the denominator is zero, the lines have no unique intersection.)

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

One more possible solution: I have a staging server that serves the site and the Cloudfront assets over HTTP. I had my origin set to "Match Viewer" instead of "HTTP Only". I also use the HTTPS Everywhere extension, which redirected all the http://* URLs to the https://* version. Since the staging server isn't available over SSL and Cloudfront was matching the viewer, it couldn't find the assets at and cached a bunch of 502s instead.

Convert list of dictionaries to a pandas DataFrame

Pyhton3: Most of the solutions listed previously work. However, there are instances when row_number of the dataframe is not required and the each row (record) has to be written individually.

The following method is useful in that case.

import csv

my file= 'C:\Users\John\Desktop\export_dataframe.csv'

records_to_save = data2 #used as in the thread. 

colnames = list[records_to_save[0].keys()] 
# remember colnames is a list of all keys. All values are written corresponding
# to the keys and "None" is specified in case of missing value 

with open(myfile, 'w', newline="",encoding="utf-8") as f:
    writer = csv.writer(f)
    for d in records_to_save:
        writer.writerow([d.get(r, "None") for r in colnames])

Load arrayList data into JTable

Basic method for beginners like me.

public void loadDataToJtable(ArrayList<String> liste){
    rows = table.getRowCount();

    cols = table.getColumnCount();

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

            for ( int k  = 0; k < cols ; k++) {
            for (int h = 0; h < list1.size(); h++) {
                String b =  list1.get(h);
                b = table.getValueAt(i, k).toString();

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

I had this error come up. I followed all of the solutions here but nothing worked. I was using Visual Studio 2013 Professional. I couldn't get the individual project rebuilds to work and I finally figured out there was a circular dependency in my references. Visual Studio does a pretty good job normally of warning you if you are adding a reference to something that references back, but for some reason it didn't in this instance. I added a reference to a project that referenced the project I was working on - and it accepted it. VS bug perhaps?

How to connect to mysql with laravel?

Laravel makes it very easy to manage your database connections through app/config/database.php.

As you noted, it is looking for a database called 'database'. The reason being that this is the default name in the database configuration file.

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database', <------ Default name for database
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',

Change this to the name of the database that you would like to connect to like this:

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'my_awesome_data', <------ change name for database
    'username'  => 'root',            <------ remember credentials
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',

Once you have this configured correctly you will easily be able to access your database!

Happy Coding!

How do I change Bootstrap 3 column order on mobile layout?

October 2017

I would like to add another Bootstrap 4 solution. One that worked for me.

The CSS "Order" property, combined with a media query, can be used to re-order columns when they get stacked in smaller screens.

Something like this:

@media only screen and (max-width: 768px) {
    #first {
        order: 2;
    #second {
        order: 4;
    #third {
        order: 1;
    #fourth {
        order: 3;

CodePen Link:

Adjust the screen size and you'll see the columns get stacked in a different order.

I'll tie this in with the original poster's question. With CSS, the navbar, sidebar, and content can be targeted and then order properties applied within a media query.

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.


Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

Matplotlib connect scatterplot points with line - Python

I think @Evert has the right answer:

plt.plot(dates, values)

Which is pretty much the same as

plt.plot(dates, values, '-o')

or whatever linestyle you prefer.

Stored Procedure error ORA-06550

Could you try this one:

create or replace 
procedure point_triangle
    dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME  || ':' || thisteam.S);


I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     FooReaderPrivate* d;

====== In a separate file =====
class FooReaderPrivate {
     FooReaderPrivate(FooReader*) : parent(p) { }
     FooReader* parent;

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

Bootstrap 3: how to make head of dropdown link clickable in navbar

Here is my solution which uses JQuery in your header, and works on Mobile.

On mobile the top links require two taps: one to dropdown the menu and one to go to its link.

      if ($(this).next().is(':visible')) {_x000D_
        location.href = $(this).attr('href');;_x000D_

GenyMotion Unable to start the Genymotion virtual device

I was struggling with this for a while and finally found a solution on Windows 10.


Network and Sharing Center > Change Adapter Settings > Right Click on VirtualBox Host-Only Network ( If you have multiple do the following to all of them ) > Properties > Check the VirtualBox NDUS6 Bridged Networking Driver

SOAP vs REST (differences)

Although SOAP and REST share similarities over the HTTP protocol, SOAP is a more rigid set of messaging patterns than REST. The rules in SOAP are relevant because we can’t achieve any degree of standardization without them. REST needs no processing as an architecture style and is inherently more versatile. In the spirit of information exchange, both SOAP and REST depend on well-established laws that everybody has decided to abide by. The choice of SOAP vs. REST is dependent on the programming language you are using the environment you are using and the specifications.

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
 $('#cmd').click(function () {
        var doc = new jsPDF();
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){'sample-file.pdf'); }


and it will work.

Proper way to return JSON using node or Express

You can use a middleware to set the default Content-Type, and set Content-Type differently for particular APIs. Here is an example:

const express = require('express');
const app = express();

const port = process.env.PORT || 3000;

const server = app.listen(port);

server.timeout = 1000 * 60 * 10; // 10 minutes

// Use middleware to set the default Content-Type
app.use(function (req, res, next) {
    res.header('Content-Type', 'application/json');

app.get('/api/endpoint1', (req, res) => {
    res.send(JSON.stringify({value: 1}));

app.get('/api/endpoint2', (req, res) => {
    // Set Content-Type differently for this particular API
    res.set({'Content-Type': 'application/xml'});
        <body>Don't forget me this weekend!</body>

Bootstrap 3 breakpoints and media queries

for bootstrap 3 I have the following code in my navbar component

 * Navbar styling.
@mobile:          ~"screen and (max-width: @{screen-xs-max})";
@tablet:          ~"screen and (min-width: @{screen-sm-min})";
@normal:          ~"screen and (min-width: @{screen-md-min})";
@wide:            ~"screen and (min-width: @{screen-lg-min})";
@grid-breakpoint: ~"screen and (min-width: @{grid-float-breakpoint})";

then you can use something like

@media wide { selector: style }

This uses whatever value you have the variables set to.

Escaping allows you to use any arbitrary string as property or variable value. Anything inside ~"anything" or ~'anything' is used as is with no changes except interpolation.

Find all matches in workbook using Excel VBA

Using the Range.Find method, as pointed out above, along with a loop for each worksheet in the workbook, is the fastest way to do this. The following, for example, locates the string "Question?" in each worksheet and replaces it with the string "Answered!".

Sub FindAndExecute()

Dim Sh As Worksheet
Dim Loc As Range

For Each Sh In ThisWorkbook.Worksheets
    With Sh.UsedRange
        Set Loc = .Cells.Find(What:="Question?")
        If Not Loc Is Nothing Then
            Do Until Loc Is Nothing
                Loc.Value = "Answered!"
                Set Loc = .FindNext(Loc)
        End If
    End With
    Set Loc = Nothing

End Sub

What is a None value?

This is what the Python documentation has got to say about None:

The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.

Changed in version 2.4: Assignments to None are illegal and raise a SyntaxError.

Note The names None and debug cannot be reassigned (assignments to them, even as an attribute name, raise SyntaxError), so they can be considered “true” constants.

  1. Let's confirm the type of None first

    print type(None)
    print None.__class__


    <type 'NoneType'>
    <type 'NoneType'>

Basically, NoneType is a data type just like int, float, etc. You can check out the list of default types available in Python in 8.15. types — Names for built-in types.

  1. And, None is an instance of NoneType class. So we might want to create instances of None ourselves. Let's try that

    print types.IntType()
    print types.NoneType()


    TypeError: cannot create 'NoneType' instances

So clearly, cannot create NoneType instances. We don't have to worry about the uniqueness of the value None.

  1. Let's check how we have implemented None internally.

    print dir(None)


    ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', 
     '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
     '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Except __setattr__, all others are read-only attributes. So, there is no way we can alter the attributes of None.

  1. Let's try and add new attributes to None

    setattr(types.NoneType, 'somefield', 'somevalue')
    setattr(None, 'somefield', 'somevalue')
    None.somefield = 'somevalue'


    TypeError: can't set attributes of built-in/extension type 'NoneType'
    AttributeError: 'NoneType' object has no attribute 'somefield'
    AttributeError: 'NoneType' object has no attribute 'somefield'

The above seen statements produce these error messages, respectively. It means that, we cannot create attributes dynamically on a None instance.

  1. Let us check what happens when we assign something None. As per the documentation, it should throw a SyntaxError. It means, if we assign something to None, the program will not be executed at all.

    None = 1


    SyntaxError: cannot assign to None

We have established that

  1. None is an instance of NoneType
  2. None cannot have new attributes
  3. Existing attributes of None cannot be changed.
  4. We cannot create other instances of NoneType
  5. We cannot even change the reference to None by assigning values to it.

So, as mentioned in the documentation, None can really be considered as a true constant.

Happy knowing None :)

Bootstrap Accordion button toggle "data-parent" not working

Bootstrap 4

Use the data-parent="" attribute on the collapse element (instead of the trigger element)

<div id="accordion">
  <div class="card">
    <div class="card-header">
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne">
          Collapsible #1 trigger
    <div id="collapseOne" class="collapse show" data-parent="#accordion">
      <div class="card-body">
        Collapsible #1 element
  ... (more cards/collapsibles inside #accordion parent)

Bootstrap 3

See this issue on GitHub:

There is a "bug" that makes the accordion dependent on the .panel class when using the data-parent attribute. To workaround it, you can wrap each accordion group in a 'panel' div..

<div class="accordion" id="myAccordion">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
        <div id="collapsible-1" class="collapse">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
        <div id="collapsible-2" class="collapse">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
        <div id="collapsible-3" class="collapse">


As mentioned in the comments, each section doesn't have to be a .panel. However...

  • .panel must be a direct child of the element used as data-parent=
  • each accordion section (data-toggle=) must be a direct child of the .panel (

Getting distance between two points based on latitude/longitude

I arrived at a much simpler and robust solution which is using geodesic from geopy package since you'll be highly likely using it in your project anyways so no extra package installation needed.

Here is my solution:

from geopy.distance import geodesic

origin = (30.172705, 31.526725)  # (latitude, longitude) don't confuse
dist = (30.288281, 31.732326)

print(geodesic(origin, dist).meters)  # 23576.805481751613
print(geodesic(origin, dist).kilometers)  # 23.576805481751613
print(geodesic(origin, dist).miles)  # 14.64994773134371


Gaussian fit for Python

Actually, you do not need to do a first guess. Simply doing

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

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

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

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

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

plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')

works fine. This is simpler because making a guess is not trivial. I had more complex data and did not manage to do a proper first guess, but simply removing the first guess worked fine :)

P.S.: use numpy.exp() better, says a warning of scipy

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

    image: traefik:v2.2.1
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
      - "80:80"
      - "8080:8080"
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

Could not load file or assembly System.Net.Http, Version= with ASP.NET (MVC 4) Web API OData Prerelease

Or you could do this from NuGet Package Manager Console

 Install-Package Microsoft.AspNet.WebApi -Version 5.0.0

And then you will be able to add the reference to System.Web.Http.WebHost 5.0

Adding +1 to a variable inside a function

You could also pass points to the function: Small example:

def test(points):
    addpoint = raw_input ("type ""add"" to add a point")
    if addpoint == "add":
        points = points + 1
        print "asd"
    return points;
if __name__ == '__main__':
    points = 0
    for i in range(10):
        points = test(points)
        print points

How do I read a response from Python Requests?

If you push for example image to some API and want the result address(response) back you could do:

import requests
url = ''
data = {"name": filename}
files = {'file': open(full_file_path, 'rb')}
response =, data=data, files=files)
current_url = response.text

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Building on Maciej Gurban's answer (which is fantastic... if you like this, please just up vote his answer). If you're building a service to query you can return the currently active service with the setup below. This could replace other breakpoint detection libraries entirely (like enquire.js if you put in some events). Note that I've added a container with an ID to the DOM elements to speed up DOM traversal.


<div id="detect-breakpoints">
    <div class="breakpoint device-xs visible-xs"></div>
    <div class="breakpoint device-sm visible-sm"></div>
    <div class="breakpoint device-md visible-md"></div>
    <div class="breakpoint device-lg visible-lg"></div>

COFFEESCRIPT (AngularJS, but this is easily convertible)

# this simple service allows us to query for the currently active breakpoint of our responsive app
myModule = angular.module('module').factory 'BreakpointService', ($log) ->

  # alias could be: xs, sm, md, lg or any over breakpoint grid prefix from Bootstrap 3
  isBreakpoint: (alias) ->
    return $('#detect-breakpoints .device-' + alias).is(':visible')

  # returns xs, sm, md, or lg
  getBreakpoint: ->
    currentBreakpoint = undefined
    $visibleElement = $('#detect-breakpoints .breakpoint:visible')
    breakpointStringsArray = [['device-xs', 'xs'], ['device-sm', 'sm'], ['device-md', 'md'], ['device-lg', 'lg']]
    # note: _. is the lodash library
    _.each breakpointStringsArray, (breakpoint) ->
      if $visibleElement.hasClass(breakpoint[0])
        currentBreakpoint = breakpoint[1]
    return currentBreakpoint


var myModule;

myModule = angular.module('modules').factory('BreakpointService', function($log) {
  return {
    isBreakpoint: function(alias) {
      return $('#detect-breakpoints .device-' + alias).is(':visible');
    getBreakpoint: function() {
      var $visibleElement, breakpointStringsArray, currentBreakpoint;
      currentBreakpoint = void 0;
      $visibleElement = $('#detect-breakpoints .breakpoint:visible');
      breakpointStringsArray = [['device-xs', 'xs'], ['device-sm', 'sm'], ['device-md', 'md'], ['device-lg', 'lg']];
      _.each(breakpointStringsArray, function(breakpoint) {
        if ($visibleElement.hasClass(breakpoint[0])) {
          currentBreakpoint = breakpoint[1];
      return currentBreakpoint;

How do I tell Gradle to use specific JDK version?

I added this line in my GRADLE_HOME/bin/gradle file - export JAVA_HOME=/path/to/java/version

ImportError: No module named pip

I think none of these answers above can fix your problem.

I was also confused by this problem once. You should manually install pip following the official guide pip installation (which currently involves running a single Python script)

after that, just sudo pip install Django. The error will be gone.

iOS 7 status bar back to iOS 6 default style in iPhone app?

I found here is the best alternatives and solution for this navigation bar issue in iOS7!!

I hope it will clear our all queries and worries.

Is there a 'foreach' function in Python 3?

Yes, although it uses the same syntax as a for loop.

for x in ['a', 'b']: print(x)

Updating PartialView mvc 4

So, say you have your View with PartialView, which have to be updated by button click:

<div class="target">
    @{ Html.RenderAction("UpdatePoints");}

<input class="button" value="update" />

There are some ways to do it. For example you may use jQuery:

<script type="text/javascript">
        $('.button').on("click", function(){        
            $.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){

PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points

If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:

public ActionResult UpdatePoints()
    ViewBag.points =  _Repository.Points;
    return PartialView("UpdatePoints");

Bootstrap 3 grid with no gap

The grid system in Bootstrap 3 requires a bit of a lateral shift in your thinking from Bootstrap 2. A column in BS2 (col-*) is NOT synonymous with a column in BS3 (col-sm-*, etc), but there is a way to achieve the same result.

Check out this update to your fiddle: (code copied below).

First of all, you don't need to specify a col for each screen size if you want 50/50 columns at all sizes. col-sm-6 applies not only to small screens, but also medium and large, meaning class="col-sm-6 col-md-6" is redundant (the benefit comes in if you want to change the column widths at different size screens, such as col-sm-6 col-md-8).

As for the margins issue, the negative margins provide a way to align blocks of text in a more flexible way than was possible in BS2. You'll notice in the jsfiddle, the text in the first column aligns visually with the text in the paragraph outside the row -- except at "xs" window sizes, where the columns aren't applied.

If you need behavior closer to what you had in BS2, where there is padding between each column and there are no visual negative margins, you will need to add an inner-div to each column. See the inner-content in my jsfiddle. Put something like this in each column, and they will behave the way old col-* elements did in BS2.

jsfiddle HTML

<div class="container">
    <p class="other-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquam sed sem nec viverra. Phasellus fringilla metus vitae libero posuere mattis. Integer sit amet tincidunt felis. Maecenas et pharetra leo. Etiam venenatis purus et nibh laoreet blandit.</p>
    <div class="row">
        <div class="col-sm-6 my-column">
            Col 1
            <p class="inner-content">Inner content - THIS element is more synonymous with a Bootstrap 2 col-*.</p>
        <div class="col-sm-6 my-column">
            Col 2

and the CSS

.row {
    border: blue 1px solid;
.my-column {
    background-color: green;
    padding-top: 10px;
    padding-bottom: 10px;
.my-column:first-child {
    background-color: red;

.inner-content {
    background: #eee;
    border: #999;
    border-radius: 5px;
    padding: 15px;

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

Here's some code with a dummy geom_blank layer,

range_act <- range(range(results$act), range(results$pred))

d <- reshape2::melt(results, id.vars = "pred")

dummy <- data.frame(pred = range_act, value = range_act,
                    variable = "act", stringsAsFactors=FALSE)

ggplot(d, aes(x = pred, y = value)) +
  facet_wrap(~variable, scales = "free") +
  geom_point(size = 2.5) + 
  geom_blank(data=dummy) + 

enter image description here

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

Phonegap Cordova installation Windows

I too struggled a lot with phonegap steps.

The correct documentation is at the following link.

There is no more cordova command, It is replaced with phonegap.

Can't install via pip because of egg_info error

I was trying to install pyautogui and followed instructions from the first answer but was unsuccessful. The difference for me was running pip install pillow and then running pip install pyautogui

I don't know what this means, but I hope this helps some people out.

Which JDK version (Language Level) is required for Android Studio?

Normally, I would go with what the documentation says but if the instructor explicitly said to stick with JDK 6, I'd use JDK 6 because you would want your development environment to be as close as possible to the instructors. It would suck if you ran into an issue and having the thought in the back of your head that maybe it's because you're on JDK 7 that you're having the issue. Btw, I haven't touched Android recently but I personally never ran into issues when I was on JDK 7 but mind you, I only code Android apps casually.

How to use Tomcat 8 in Eclipse?

If you have untarred your own version of tomcat v8 with a root user into a custom directory (linux) then the default permissions on the TOMCATROOT/lib directory do not allow normal user access.

Eclipse will not be able to see the catalina.jar to check the version. So no amount of fiddling aorund with the will help!

just add chmod u+x lib/ to allow normal user access to the libs.

How to plot two columns of a pandas data frame using points?

For this (and most plotting) I would not rely on the Pandas wrappers to matplotlib. Instead, just use matplotlib directly:

import matplotlib.pyplot as plt
plt.scatter(df['col_name_1'], df['col_name_2']) # Depending on whether you use IPython or interactive mode, etc.

and remember that you can access a NumPy array of the column's values with df.col_name_1.values for example.

I ran into trouble using this with Pandas default plotting in the case of a column of Timestamp values with millisecond precision. In trying to convert the objects to datetime64 type, I also discovered a nasty issue: < Pandas gives incorrect result when asking if Timestamp column values have attr astype >.

Scatter plot and Color mapping in Python

Here is an example

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)

plt.scatter(x, y, c=t)

Here you are setting the color based on the index, t, which is just an array of [1, 2, ..., 100]. enter image description here

Perhaps an easier-to-understand example is the slightly simpler

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
plt.scatter(x, y, c=t)

enter image description here

Note that the array you pass as c doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples. The plotting routine will scale the colormap such that the minimum/maximum values in c correspond to the bottom/top of the colormap.


You can change the colormap by adding

import as cm
plt.scatter(x, y, c=t, cmap=cm.cmap_name)

Importing is optional as you can call colormaps as cmap="cmap_name" just as well. There is a reference page of colormaps showing what each looks like. Also know that you can reverse a colormap by simply calling it as cmap_name_r. So either

plt.scatter(x, y, c=t, cmap=cm.cmap_name_r)
# or
plt.scatter(x, y, c=t, cmap="cmap_name_r")

will work. Examples are "jet_r" or cm.plasma_r. Here's an example with the new 1.5 colormap viridis:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')

enter image description here


You can add a colorbar by using

plt.scatter(x, y, c=t, cmap='viridis')

enter image description here

Note that if you are using figures and subplots explicitly (e.g. fig, ax = plt.subplots() or ax = fig.add_subplot(111)), adding a colorbar can be a bit more involved. Good examples can be found here for a single subplot colorbar and here for 2 subplots 1 colorbar.

R color scatter plot points based on values

Also it'd work to just specify ifelse() twice:

plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))

Java - Find shortest path between 2 points in a distance weighted map

You can see a complete example using java 8, recursion and streams -> Dijkstra algorithm with java

How can I expand and collapse a <div> using javascript?

So, first of all, your Javascript isn't even using jQuery. There are a couple ways to do this. For example:

First way, using the jQuery toggle method:

<div class="expandContent">
        <a href="#">Click Here to Display More Content</a>
<div class="showMe" style="display:none">
        This content was hidden, but now shows up



Another way is simply to use the jQuery show method:

<div class="expandContent">
        <a href="#">Click Here to Display More Content</a>
<div class="showMe" style="display:none">
        This content was hidden, but now shows up



Yet a third way is to use the slideToggle method of jQuery which allows for some effects. Such as $('#showMe').slideToggle('slow'); which will slowly display the hidden div.

How to draw interactive Polyline on route google maps v2 android

Using the google maps projection api to draw the polylines on an overlay view enables us to do a lot of things. Check this repo that has an example.

enter image description here

Matplotlib scatter plot legend

Other answers seem a bit complex, you can just add a parameter 'label' in scatter function and that will be the legend for your plot.

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0],label='Low Outlier')
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0],label='LoLo')
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1],label='Lo')
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2],label='Average')
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3],label='Hi')
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4],label='HiHi')
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4],label='High Outlier')

plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=4)

This is your output:


How can I get a user's media from Instagram without authenticating as a user?

Since Instagram changed the way they provide this data, none of above methods work nowadays. Here is the new way to get user's media:
query_id - permanent value: 17888483320059182 (note it might be changed in future).
id - id of the user. It may come with list of users. To get the list of users you can use following request: GET
first - amount of items to get.
after - id of the last item if you want to get items from that id.

Multiple axis line chart in excel

There is a way of displaying 3 Y axis see here.

Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.

Conversion between UTF-8 ArrayBuffer and String

function stringToUint(string) {
    var string = btoa(unescape(encodeURIComponent(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
    return new Uint8Array(uintArray);

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;

I have done, with some help from the internet, these little functions, they should solve your problems! Here is the working JSFiddle.


Since the source of the Uint8Array is external and you can't use atob you just need to remove it(working fiddle):

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(encodedString));
    return decodedString;

Warning: escape and unescape is removed from web standards. See this.

Is there an equivalent of lsusb for OS X

I typically run this command to list USB devices on Mac OS X, along with details about them:

ioreg -p IOUSB -l -w 0

Inline labels in Matplotlib

@Jan Kuiken's answer is certainly well-thought and thorough, but there are some caveats:

  • it does not work in all cases
  • it requires a fair amount of extra code
  • it may vary considerably from one plot to the next

A much simpler approach is to annotate the last point of each plot. The point can also be circled, for emphasis. This can be accomplished with one extra line:

from matplotlib import pyplot as plt

for i, (x, y) in enumerate(samples):
    plt.plot(x, y)
    plt.text(x[-1], y[-1], 'sample {i}'.format(i=i))

A variant would be to use ax.annotate.

Parsing jQuery AJAX response

Since you are using $.ajax, and not $.getJSON, your return type is plain text. you need to now convert data into a JSON object.

you can either do this by changing your $.ajax to $.getJSON (which is a shorthand for $.ajax, only preconfigured to fetch json).

Or you can parse the data string into JSON after you receive it, like so:

    success: function (data) {
         var obj = $.parseJSON(data);

Step-by-step debugging with IPython

Running from inside Emacs' IPython-shell and breakpoint set via pdb.set_trace() should work.

Checked with python-mode.el, M-x ipython RET etc.

A JOIN With Additional Conditions Using Query Builder or Eloquent

If you have some params, you can do this.

    $results = DB::table('rooms')
    ->leftJoin('bookings', function($join) use ($param1, $param2)
        $join->on('', '=', 'bookings.room_type_id');

    ->where('bookings.room_type_id', '=', NULL)

and then return your query

return $results;

Create own colormap using matplotlib and plot color scale

This seems to work for me.

def make_Ramp( ramp_colors ): 
    from colour import Color
    from matplotlib.colors import LinearSegmentedColormap

    color_ramp = LinearSegmentedColormap.from_list( 'my_list', [ Color( c1 ).rgb for c1 in ramp_colors ] )
    plt.figure( figsize = (15,3))
    plt.imshow( [list(np.arange(0, len( ramp_colors ) , 0.1)) ] , interpolation='nearest', origin='lower', cmap= color_ramp )
    return color_ramp

custom_ramp = make_Ramp( ['#754a28','#893584','#68ad45','#0080a5' ] ) 

custom color ramp

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points


Now try:

plot sin(x) with points pointtype 5


You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

How to change dot size in gnuplot

Use the pointtype and pointsize options, e.g.

plot "./points.dat" using 1:2 pt 7 ps 10  

where pt 7 gives you a filled circle and ps 10 is the size.

See: Plotting data.

Error to run Android Studio

On ubuntu I have tried all the methods that are described here but none worked.

What I did in the end was to:

  • download JDK from oracle, extract the archive

  • edit android-studio/bin/ and add at the top

    export JAVA_HOME=/path/to/jdk

  • save the file and cd android-studio/bin and launch Android Studio: ./

Android Studio installation on Windows 7 fails, no JDK found

You need 1.7 JDK installed on your system. Add a system variable with:

Common CSS Media Queries Break Points

If you go to your google analytics you can see which screen resolutions your visitors to the website use:

Audience > Technology > Browser & OS > Screen Resolution ( in the menu above the stats)

My site gets about 5,000 visitors a month and the dimensions used for the free version of are pretty accurate summary of my visitors' screen resolutions.

This could save you from needing to be too perfectionistic.

How to read a configuration file in Java

app.config Sample Code

Source code:

Properties prop = new Properties();
String fileName = "app.config";
InputStream is = null;
try {
    is = new FileInputStream(fileName);
} catch (FileNotFoundException ex) {
try {
} catch (IOException ex) {


Properties Sample Code

Java "user.dir" property - what exactly does it mean?

Typically this is the directory where your app (java) was started (working dir). "Typically" because it can be changed, eg when you run an app with Runtime.exec(String[] cmdarray, String[] envp, File dir)

What is ToString("N0") format?

Checkout the following article on MSDN about examples of the N format. This is also covered in the Standard Numeric Format Strings article.

Relevant excerpts:

//       Formatting of 1054.32179:
//          N:                     1,054.32 
//          N0:                    1,054 
//          N1:                    1,054.3 
//          N2:                    1,054.32 
//          N3:                    1,054.322 

When precision specifier controls the number of fractional digits in the result string, the result string reflects a number that is rounded to a representable result nearest to the infinitely precise result. If there are two equally near representable results:

  • On the .NET Framework and .NET Core up to .NET Core 2.0, the runtime selects the result with the greater least significant digit (that is, using MidpointRounding.AwayFromZero).
  • On .NET Core 2.1 and later, the runtime selects the result with an even least significant digit (that is, using MidpointRounding.ToEven).

AngularJS: Basic example to use authentication in Single Page Application

I've created a github repo summing up this article basically:

ng-login Github repo


I'll try to explain as good as possible, hope I help some of you out there:

(1) app.js: Creation of authentication constants on app definition

var loginApp = angular.module('loginApp', ['ui.router', 'ui.bootstrap'])
/*Constants regarding user login defined here*/
.constant('USER_ROLES', {
    all : '*',
    admin : 'admin',
    editor : 'editor',
    guest : 'guest'
}).constant('AUTH_EVENTS', {
    loginSuccess : 'auth-login-success',
    loginFailed : 'auth-login-failed',
    logoutSuccess : 'auth-logout-success',
    sessionTimeout : 'auth-session-timeout',
    notAuthenticated : 'auth-not-authenticated',
    notAuthorized : 'auth-not-authorized'

(2) Auth Service: All following functions are implemented in auth.js service. The $http service is used to communicate with the server for the authentication procedures. Also contains functions on authorization, that is if the user is allowed to perform a certain action.

.factory('Auth', [ '$http', '$rootScope', '$window', 'Session', 'AUTH_EVENTS', 
function($http, $rootScope, $window, Session, AUTH_EVENTS) {

authService.login() = [...]
authService.isAuthenticated() = [...]
authService.isAuthorized() = [...]
authService.logout() = [...]

return authService;
} ]);

(3) Session: A singleton to keep user data. The implementation here depends on you.

angular.module('loginApp').service('Session', function($rootScope, USER_ROLES) {

    this.create = function(user) {
        this.user = user;
        this.userRole = user.userRole;
    this.destroy = function() {
        this.user = null;
        this.userRole = null;
    return this;

(4) Parent controller: Consider this as the "main" function of your application, all controllers inherit from this controller, and it's the backbone of the authentication of this app.

<body ng-controller="ParentController">

(5) Access control: To deny access on certain routes 2 steps have to be implemented:

a) Add data of the roles allowed to access each route, on ui router's $stateProvider service as can be seen below (same can work for ngRoute).

.config(function ($stateProvider, USER_ROLES) {
  $stateProvider.state('dashboard', {
    url: '/dashboard',
    templateUrl: 'dashboard/index.html',
    data: {
      authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor]

b) On $rootScope.$on('$stateChangeStart') add the function to prevent state change if the user is not authorized.

$rootScope.$on('$stateChangeStart', function (event, next) {
    var authorizedRoles =;
    if (!Auth.isAuthorized(authorizedRoles)) {
      if (Auth.isAuthenticated()) {
        // user is not allowed
      } else {
        // user is not logged in

(6) Auth interceptor: This is implemented, but can't be checked on the scope of this code. After each $http request, this interceptor checks the status code, if one of the below is returned, then it broadcasts an event to force the user to log-in again.

.factory('AuthInterceptor', [ '$rootScope', '$q', 'Session', 'AUTH_EVENTS',
function($rootScope, $q, Session, AUTH_EVENTS) {
    return {
        responseError : function(response) {
                401 : AUTH_EVENTS.notAuthenticated,
                403 : AUTH_EVENTS.notAuthorized,
                419 : AUTH_EVENTS.sessionTimeout,
                440 : AUTH_EVENTS.sessionTimeout
            }[response.status], response);
            return $q.reject(response);
} ]);

P.S. A bug with the form data autofill as stated on the 1st article can be easily avoided by adding the directive that is included in directives.js.

P.S.2 This code can be easily tweaked by the user, to allow different routes to be seen, or display content that was not meant to be displayed. The logic MUST be implemented server-side, this is just a way to show things properly on your ng-app.

Font scaling based on width of container

Use CSS Variables

No one has mentioned CSS variables yet, and this approach worked best for me, so:

Let's say you've got a column on your page that is 100% of the width of a mobile user's screen, but has a max-width of 800px, so on desktop there's some space on either side of the column. Put this at the top of your page:

<script>'--column-width', Math.min(window.innerWidth, 800)+'px'); </script>

And now you can use that variable (instead of the built-in vw unit) to set the size of your font. E.g.

p {
  font-size: calc( var(--column-width) / 100 );

It's not a pure CSS approach, but it's pretty close.

format a number with commas and decimals in C# ( MVC3)

If you are using string variables you can format the string directly using a : then specify the format (e.g. N0, P2, etc).

decimal Number = 2000.55512016465m;
$"{Number:N}" #Outputs 2,000.55512016465

You can also specify the number of decimal places to show by adding a number to the end like

$"{Number:N1}" #Outputs 2,000.5
$"{Number:N2}" #Outputs 2,000.55
$"{Number:N3}" #Outputs 2,000.555
$"{Number:N4}" #Outputs 2,000.5551

plotting different colors in matplotlib

@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...

There are a number of different ways you could do this. To begin with, matplotlib will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))

enter image description here

If you want to control which colors matplotlib cycles through, use ax.set_color_cycle:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.set_color_cycle(['red', 'black', 'yellow'])
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))

enter image description here

If you'd like to explicitly specify the colors that will be used, just pass it to the color kwarg (html colors names are accepted, as are rgb tuples and hex strings):

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))

enter image description here

Finally, if you'd like to automatically select a specified number of colors from an existing colormap:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
number = 5
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, number)]

for i, color in enumerate(colors, start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))

enter image description here

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.

To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data to an array before not after you try to slice it:

R = np.array(mean_data)[:,0]

instead of

R = np.array(mean_data[:,0])

But, assuming mean_data has a shape nx3, instead of

R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]

You can simply do

A = np.array(mean_data).mean(axis=0)

which averages over the 0th axis and returns a length-n array

But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:

How can I stop Chrome from going into debug mode?

If you were unfamiliar with the tools, it was likely that at some point while in the debugger you toggled a setting that was causing the debugger to stop the application.

I suggest you "Disable all break points":

Enter image description here


Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file

This one shows you how to use it to stream back a file

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
    // do work here                            

Label points in geom_point

The ggrepel package works great for repelling overlapping text labels away from each other. You can use either geom_label_repel() (draws rectangles around the text) or geom_text_repel() functions.


nba <- read.csv("", sep = ",")

nbaplot <- ggplot(nba, aes(x= MIN, y = PTS)) + 
  geom_point(color = "blue", size = 3)

### geom_label_repel
nbaplot + 
  geom_label_repel(aes(label = Name),
                  box.padding   = 0.35, 
                  point.padding = 0.5,
                  segment.color = 'grey50') +

enter image description here

### geom_text_repel
# only label players with PTS > 25 or < 18
# align text vertically with nudge_y and allow the labels to 
# move horizontally with direction = "x"
ggplot(nba, aes(x= MIN, y = PTS, label = Name)) + 
  geom_point(color = dplyr::case_when(nba$PTS > 25 ~ "#1b9e77", 
                                      nba$PTS < 18 ~ "#d95f02",
                                      TRUE ~ "#7570b3"), 
             size = 3, alpha = 0.8) +
  geom_text_repel(data          = subset(nba, PTS > 25),
                  nudge_y       = 32 - subset(nba, PTS > 25)$PTS,
                  size          = 4,
                  box.padding   = 1.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  geom_label_repel(data         = subset(nba, PTS < 18),
                  nudge_y       = 16 - subset(nba, PTS < 18)$PTS,
                  size          = 4,
                  box.padding   = 0.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  scale_x_continuous(expand = expand_scale(mult = c(0.2, .2))) +
  scale_y_continuous(expand = expand_scale(mult = c(0.1, .1))) +
  theme_classic(base_size = 16)

Edit: To use ggrepel with lines, see this and this.

Created on 2019-05-01 by the reprex package (v0.2.0).

An attempt was made to access a socket in a way forbidden by its access permissions

My windows firewall was blocking port 8080 so i changed it to 5000 and it worked!

How to debug (only) JavaScript in Visual Studio?

The debugger should automatically attach to the browser with Visual Studio 2012. You can use the debugger keyword to halt at a certain point in the application or use the breakpoints directly inside VS.

You can also detatch the default debugger in Visual Studio and use the Developer Tools which come pre loaded with Internet Explorer or FireBug etc.

To do this goto Visual Studio -> Debug -> Detatch All and then click Start debugging in Internet Explorer. You can then set breakpoints at this level. enter image description here

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

Your problem is that you have 64-bit eclipse running but you have 32 bit JRE.So please download JRE for 64 bit windows and let it install on the default location. Finally add that path till bin in your PATH variable. Try it should work.

notifyDataSetChange not working from custom adapter

If adapter is set to AutoCompleteTextView then notifyDataSetChanged() doesn't work.

Need this to update adapter:

myAutoCompleteAdapter = new ArrayAdapter<String>(MainActivity.this, 
        android.R.layout.simple_dropdown_item_1line, myList);



How to change default JRE for all Eclipse workspaces?

On windows I've tried different approaches - setting JAVA_HOME, JRE_HOME and extending the PATH to point to the desiered jre18 but nothing helped - disabling the JRE17 in the java control panel didn't helped either

What helped me out was to force eclipse to use the appropriate JRE in the eclipse.ini file e.g.

-vm C:\java\jdk1.8.0_111\jre\bin\javaw.exe

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

If you remove [DataType(DataType.Date)] from your model, the input field in Chrome is rendered as type="datetime" and won't show the datepicker either.

How can I set the initial value of Select2 when using AJAX?

The issue of being forced to trigger('change') drove me nuts, as I had custom code in the change trigger, which should only trigger when the user changes the option in the dropdown. IMO, change should not be triggered when setting an init value at the start.

I dug deep and found the following:



Regex using javascript to return just numbers

var result = input.match(/\d+/g).join([])

compare differences between two tables in mysql

Based on Haim's answer here's a simplified example if you're looking to compare values that exist in BOTH tables, otherwise if there's a row in one table but not the other it will also return it....

Took me a couple of hours to figure out. Here's a fully tested simply query for comparing "tbl_a" and "tbl_b"

    tbl_a.ID, tbl_a.col FROM tbl_a
    tbl_b.ID, tbl_b.col FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
ID, col

So you need to add the extra "where in" clause:

WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)


For ease of reading if you want to indicate the table names you can use the following:

SELECT tbl, ID, col
    tbl_a.ID, tbl_a.col, "name_to_display1" as "tbl" FROM tbl_a
    tbl_b.ID, tbl_b.col, "name_to_display2" as "tbl" FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
ID, col

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

vue.js 2 how to watch store values from vuex

You could also subscribe to the store mutations:

store.subscribe((mutation, state) => {

How do I pull my project from github?

There are few steps to be followed (For Windows)

  1. Open Git Bash and generate ssh key Paste the text below, substituting in your GitHub email address.

    ssh-keygen -t rsa -b 4096 -C "[email protected]"

    This creates a new ssh key, using the provided email as a label.

    Generating public/private rsa key pair.

    When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.

    Enter a file in which to save the key (/c/Users/you/.ssh/id_rsa):[Press enter]

    At the prompt, type a secure passphrase. For more information, see "Working with SSH key passphrases".

    Enter passphrase (empty for no passphrase): [Type a passphrase] Enter same passphrase again: [Type passphrase again]

  2. Add the key to SSH Agent

    Type the following in Git Bash (99999 is just an example) to see agent is up and running. eval $(ssh-agent -s) Agent pid 99999

    then type this.

    ssh-add ~/.ssh/id_rsa

    then Copy the SSH key to your clipboard using this command

    clip < ~/.ssh/

  3. Add the SSH Key to the Git Account

    In GitHib site, click on the image on top right corner, and select settings. In the subsequent page, click SSH and GPG keys option. This will open up the SSH key page. Click on the New SSH key. In the "Title" field, add a descriptive label for the new key. Paste your key into the "Key" field.

  4. Clone the Repository

    Open VS Code (or any IDE/CLI which has command prompt etc.). Go to the directory in which you want to clone, using cd commands, and type the below line. git config --global github.user yourGitUserName git config --global your_email git clone [email protected]:yourGitUserName/YourRepoName.git

how to destroy bootstrap modal window completely?

My approach would be to use the clone() method of jQuery. It creates a copy of your element, and that's what you want : a copy of your first unaltered modal, that you can replace at your wish : Demo (jsfiddle)

var myBackup = $('#myModal').clone();

// Delegated events because we make a copy, and the copied button does not exist onDomReady
$('body').on('click','#myReset',function() {
    var myClone = myBackup.clone();

The markup I used is the most basic, so you just need to bind on the right elements / events, and you should have your wizard reset.

Be careful to bind with delegated events, or rebind at each reset the inner elements of your modal so that each new modal behave the same way.

Convert HTML to PDF in .NET

Winnovative offer a .Net PDF library that supports HTML input. They offer an unlimited free trial. Depending on how you wish to deploy your project, this might be sufficient.

How does the data-toggle attribute work? (What's its API?)

The data-toggle attribute simple tell Bootstrap what exactly to do by giving it the name of the toggle action it is about to perform on a target element. If you specify collapse. It means bootstrap will collapse or uncollapse the element pointed by data-target of the action you clicked

Note: the target element must have the appropriate class for bootstrap to carry out the action

Source action:
data-toggle = collapse //type of toggle
data-target = #myDiv

class=collapse //I can collapse

This is same for other type of toggle actions like tab, modal, dropdown

Amazon S3 direct file upload from client browser - private key disclosure

If you don't have any server side code, you security depends on the security of the access to your JavaScript code on the client side (ie everybody who has the code could upload something).

So I would recommend, to simply create a special S3 bucket which is public writeable (but not readable), so you don't need any signed components on the client side.

The bucket name (a GUID eg) will be your only defense against malicious uploads (but a potential attacker could not use your bucket to transfer data, because it is write only to him)

Read binary file as string in Ruby

First, you should open the file as a binary file. Then you can read the entire file in, in one command.

file ="path-to-file.tar.gz", "rb")
contents =

That will get you the entire file in a string.

After that, you probably want to file.close. If you don’t do that, file won’t be closed until it is garbage-collected, so it would be a slight waste of system resources while it is open.

Save array in mysql database

The way things like that are done is with serializing the array, which means "making a string out of it". To better understand this, have a look on this:

$array = array("my", "litte", "array", 2);

$serialized_array = serialize($array); 
$unserialized_array = unserialize($serialized_array); 

var_dump($serialized_array); // gives back a string, perfectly for db saving!
var_dump($unserialized_array); // gives back the array again

Connect multiple devices to one device via Bluetooth

Bluetooth 4.0 Allows you in a Bluetooth piconet one master can communicate up to 7 active slaves, there can be some other devices up to 248 devices which sleeping.

Also you can use some slaves as bridge to participate with more devices.

Maximum size of an Array in Javascript

You could try something like this to test and trim the length:

var longArray = [1, 2, 3, 4, 5, 6, 7, 8];_x000D_
if (longArray.length >= 6) {_x000D_
  longArray.length = 3;_x000D_
alert(longArray); //1, 2, 3

How to sort with a lambda?

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
    return a.mProperty > b.mProperty; 

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

Visual Studio 2017: Display method references

In previous posts I have read that this feature IS available on VS 2015 community if you FIRST install SQL Server express (free) and THEN install VS. I have tried it and it worked. I just had to reinstall Windows and am going thru the same procedure now and it did not work... so will try again :). I know it worked 6 months ago when I tried.


Add a default value to a column through a migration

Here's how you should do it:

change_column :users, :admin, :boolean, :default => false

But some databases, like PostgreSQL, will not update the field for rows previously created, so make sure you update the field manaully on the migration too.

How to merge two PDF files into one in Java?

package article14;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.util.PDFMergerUtility;

public class Pdf
    public static void main(String args[])
        new Pdf().createNew();
        new Pdf().combine();

    public void combine()
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        String folder ="pdf";
        File _folder = new File(folder);
        File[] filesInFolder;
        filesInFolder = _folder.listFiles();
        for (File string : filesInFolder)
        catch(Exception e)


public void createNew()
    PDDocument document = null;
        String filename="test.pdf";
        document=new PDDocument();
        PDPage blankPage = new PDPage();
        document.addPage( blankPage ); filename );
    catch(Exception e)



Why does modulus division (%) only work with integers?

The constraints are in the standards:

C11(ISO/IEC 9899:201x) §6.5.5 Multiplicative operators

Each of the operands shall have arithmetic type. The operands of the % operator shall have integer type.

C++11(ISO/IEC 14882:2011) §5.6 Multiplicative operators

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. The usual arithmetic conversions are performed on the operands and determine the type of the result.

The solution is to use fmod, which is exactly why the operands of % are limited to integer type in the first place, according to C99 Rationale §6.5.5 Multiplicative operators:

The C89 Committee rejected extending the % operator to work on floating types as such usage would duplicate the facility provided by fmod

Check if a variable is of function type

There are several ways so I will summarize them all

  1. Best way is:
    function foo(v) {if (v instanceof Function) {/* do something */} };
    Most performant (no string comparison) and elegant solution - the instanceof operator has been supported in browsers for a very long time, so don't worry - it will work in IE 6.
  2. Next best way is:
    function foo(v) {if (typeof v === "function") {/* do something */} };
    disadvantage of typeof is that it is susceptible to silent failure, bad, so if you have a typo (e.g. "finction") - in this case the `if` will just return false and you won't know you have an error until later in your code
  3. The next best way is:
    function isFunction(functionToCheck) {
        var getType = {};
        return functionToCheck && === '[object Function]';
    This has no advantage over solution #1 or #2 but is a lot less readable. An improved version of this is
    function isFunction(x) {
        return == '[object Function]';
    but still lot less semantic than solution #1

How to detect a docker daemon port

  1. Prepare extra configuration file. Create a file named /etc/systemd/system/docker.service.d/docker.conf. Inside the file docker.conf, paste below content:
ExecStart=/usr/bin/dockerd -H tcp:// -H unix:///var/run/docker.sock

Note that if there is no directory like docker.service.d or a file named docker.conf then you should create it.

  1. Restart Docker. After saving this file, reload the configuration by systemctl daemon-reload and restart Docker by systemctl restart docker.service.

  2. Check your Docker daemon. After restarting docker service, you can see the port in the output of systemctl status docker.service like /usr/bin/dockerd -H tcp:// -H unix:///var/run/docker.sock.

Hope this may help

Thank you!

Pointer to class data member "::*"

A realworld example of a pointer-to-member could be a more narrow aliasing constructor for std::shared_ptr:

template <typename T>
template <typename U>
shared_ptr<T>::shared_ptr(const shared_ptr<U>, T U::*member);

What that constructor would be good for

assume you have a struct foo:

struct foo {
    int ival;
    float fval;

If you have given a shared_ptr to a foo, you could then retrieve shared_ptr's to its members ival or fval using that constructor:

auto foo_shared = std::make_shared<foo>();
auto ival_shared = std::shared_ptr<int>(foo_shared, &foo::ival);

This would be useful if want to pass the pointer foo_shared->ival to some function which expects a shared_ptr

How to use responsive background image in css3 in bootstrap

Set Responsive and User friendly Background

body {
background: url(image.jpg);
background-repeat: no-repeat;
width: 100%;

How to check if an email address is real or valid using PHP

You should check with SMTP.

That means you have to connect to that email's SMTP server.

After connecting to the SMTP server you should send these commands:

MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>

If you get "<[email protected]> Relay access denied" that means this email is Invalid.

There is a simple PHP class. You can use it:

How to use a variable for a key in a JavaScript object literal?

You could do the following for ES5:

var theTop = 'top'
  JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10

Or extract to a function:

function newObj (key, value) {
  return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')

var theTop = 'top'
  newObj(theTop, 10), 10

Check if string begins with something?

First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);

Then you use it like this. Caution! Makes the code extremely readable.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

This works for me in firefox


    dataType: 'json',
    //acceptFileTypes: /(\.|\/)(xml|pdf)$/i,
    //maxFileSize: 15000000,

    add: function (e, data) {
        var uploadErrors = [];

        var acceptFileTypes = /\/(pdf|xml)$/i;
        if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
            uploadErrors.push('File type not accepted');

        console.log(data.originalFiles[0]['size']) ;
        if (data.originalFiles[0]['size'] > 5000000) {
            uploadErrors.push('Filesize too big');
        if(uploadErrors.length > 0) {
        } else {
            data.context = $('<p/>').text('Uploading...').appendTo(document.body);

    done: function (e, data) {

linking jquery in html

Seeing the answers I have nothing else to add but one more thing:

in your test.html file you have written

link rel="stylesheet" type="css/text" href="test.css"/

see where you have written


there you need to change into


so it will look like that

link rel="stylesheet" type="text/css" href="test.css"/

and in this case the CSS file will be linked to HTML file

Clear text in EditText when entered

You can use the 'android:hint' attribute in your EditText also from code:

editText.setHint(CharSequence hint / int resid);

Then you don't need any onClickListener or similar. But consider that the hint value won't be passed. The editText will be stayed empty. In this case you can set your editText with your deflault value:

if(editText.getText().toString().equals("")) { 
...use your default value instead of the editText... }

Java method to swap primitives

You can't create a method swap, so that after calling swap(x,y) the values of x and y will be swapped. You could create such a method for mutable classes by swapping their contents¹, but this would not change their object identity and you could not define a general method for this.

You can however write a method that swaps two items in an array or list if that's what you want.

¹ For example you could create a swap method that takes two lists and after executing the method, list x will have the previous contents of list y and list y will have the previous contents of list x.

How can I remove a key from a Python dictionary?

Using the "del" keyword:

del dict[key]

Can I get the name of the current controller in the view?

#to get controller name:
<%= controller.controller_name %>
#=> 'users'

#to get action name, it is the method:
<%= controller.action_name %>
#=> 'show'

#to get id information:
<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>
#=> '23'

# or display nicely
<%= debug Rails.application.routes.recognize_path(request.url) %>


How to play ringtone/alarm sound in Android

You can simply play a setted ringtone with this:

Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);;

How to retrieve all keys (or values) from a std::map and put them into a vector?

The following functor retrieves the key set of a map:

#include <vector>
#include <iterator>
#include <algorithm>

template <class _Map>
std::vector<typename _Map::key_type> keyset(const _Map& map)
    std::vector<typename _Map::key_type> result;
    std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {
        return kvpair.first;
    return result;

Bonus: The following functors retrieve the value set of a map:

#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>

template <class _Map>
std::vector<typename _Map::mapped_type> valueset(const _Map& map)
    std::vector<typename _Map::mapped_type> result;
    std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {
        return kvpair.second;
    return result;

template <class _Map>
std::vector<std::reference_wrapper<typename _Map::mapped_type>> valueset(_Map& map)
    std::vector<std::reference_wrapper<typename _Map::mapped_type>> result;
    std::transform(map.begin(), map.end(), std::back_inserter(result), [](typename _Map::reference kvpair) {
        return std::ref(kvpair.second);
    return result;


int main()
    std::map<int, double> map{
        {1, 9.0},
        {2, 9.9},
        {3, 9.99},
        {4, 9.999},
    auto ks = keyset(map);
    auto vs = valueset(map);
    for (auto& k : ks) std::cout << k << '\n';
    std::cout << "------------------\n";
    for (auto& v : vs) std::cout << v << '\n';
    for (auto& v : vs) v += 100.0;
    std::cout << "------------------\n";
    for (auto& v : vs) std::cout << v << '\n';
    std::cout << "------------------\n";
    for (auto& [k, v] : map) std::cout << v << '\n';

    return 0;

Expected output:


Use of Custom Data Types in VBA

Sure you can:

Option Explicit

'***** User defined type
Public Type MyType
     MyInt As Integer
     MyString As String
     MyDoubleArr(2) As Double
End Type

'***** Testing MyType as single variable
Public Sub MyFirstSub()
    Dim MyVar As MyType

    MyVar.MyInt = 2
    MyVar.MyString = "cool"
    MyVar.MyDoubleArr(0) = 1
    MyVar.MyDoubleArr(1) = 2
    MyVar.MyDoubleArr(2) = 3

    Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub

'***** Testing MyType as an array
Public Sub MySecondSub()
    Dim MyArr(2) As MyType
    Dim i As Integer

    MyArr(0).MyInt = 31
    MyArr(0).MyString = "VBA"
    MyArr(0).MyDoubleArr(0) = 1
    MyArr(0).MyDoubleArr(1) = 2
    MyArr(0).MyDoubleArr(2) = 3
    MyArr(1).MyInt = 32
    MyArr(1).MyString = "is"
    MyArr(1).MyDoubleArr(0) = 11
    MyArr(1).MyDoubleArr(1) = 22
    MyArr(1).MyDoubleArr(2) = 33
    MyArr(2).MyInt = 33
    MyArr(2).MyString = "cool"
    MyArr(2).MyDoubleArr(0) = 111
    MyArr(2).MyDoubleArr(1) = 222
    MyArr(2).MyDoubleArr(2) = 333

    For i = LBound(MyArr) To UBound(MyArr)
        Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
End Sub

SSIS Convert Between Unicode and Non-Unicode Error

I experienced this condition when I had installed Oracle version 12 client 32 bit client connected to an Oracle 12 Server running on windows. Although both of Oracle-source and SqlServer-destination are NOT Unicode, I kept getting this message, as if the oracle columns were Unicode. I solved the problem inserting a data conversion box, and selecting type DT-STR (not unicode) for varchar2 fields and DT-WSTR (unicode) for numeric fields, then I've dropped the 'COPY OF' from the output field name. Note that I kept getting the error because I had connected the source box arrow with the conversion box BEFORE setting the convertion types. So I had to switch source box and this cleaned all the errors in the destination box.

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

My issue with the loading of that bundle file was a bad symlink. So check the link, and replace it with a fresh one if needed. Everything fell into place at that point. Not sure how that happened, but it did. First time that a syntax error happened like that.

Optimal way to Read an Excel file (.xls/.xlsx)

Using OLE Query, it's quite simple (e.g. sheetName is Sheet1):

DataTable LoadWorksheetInDataTable(string fileName, string sheetName)
    DataTable sheetData = new DataTable();
    using (OleDbConnection conn = this.returnConnection(fileName))
       // retrieve the data using data adapter
       OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "$]", conn);
    return sheetData;

private OleDbConnection returnConnection(string fileName)
    return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");

For newer Excel versions:

return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;");

You can also use Excel Data Reader an open source project on CodePlex. Its works really well to export data from Excel sheets.

The sample code given on the link specified:

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())

//6. Free resources (IExcelDataReader is IDisposable)

Reference: How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

Java 8 stream map to list of keys sorted by values

Here is the simple solution with StreamEx

EntryStream.of(countByType).sortedBy(e -> e.getValue()).keys().toList();

Detect all Firefox versions in JS

    <script type="text/javascript">
           var isChrome = /Chrome/.test(navigator.userAgent) && /Google 
           var isFirefox = 
                  navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
           if (isChrome) 
               document.write('<'+'link rel="stylesheet" 
                                  href="css/chrome.css" />');

          else if(isFirefox)
               document.write('<'+'link rel="stylesheet" 
                                  href="css/Firefox.css" />');
                document.write('<'+'link rel="stylesheet" 
                                   href="css/IE.css" />');


This works perfect for IE,Firefox and Chrome.

Simple way to understand Encapsulation and Abstraction

Encapsulation can be thought of as wrapping paper used to bind data and function together as a single unit which protects it from all kinds of external dirt (I mean external functions).

Abstraction involves absence of details and the use of a simple interface to control a complex system.

For example we can light a bulb by the pressing of a button without worrying about the underlying electrical engineering (Abstraction) .

However u cannot light the bulb in any other way. (Encapsulation)

Understanding string reversal via slicing

Using extended slice syntax

word = input ("Type a word which you want to reverse: ")
def reverse(word):
  word = word[::-1]
  return word
print (reverse(word))

Android Overriding onBackPressed()

Just call the onBackPressed() method in the activity you want to show the dialog and inside it show your dialog.

MySQL load NULL values from CSV data

Preprocess your input CSV to replace blank entries with \N.

Attempt at a regex: s/,,/,\n,/g and s/,$/,\N/g

Good luck.

flutter remove back button on appbar

  appBar: new AppBar(title: new Text("SmartDocs SPAY"),backgroundColor: Colors.blueAccent, automaticallyImplyLeading:false,
        leading: new Container(),

It is working Fine

How to use the ConfigurationManager.AppSettings

you should use []

var x = ConfigurationManager.AppSettings["APIKey"];

Find all stored procedures that reference a specific column in some table

-- Search in All Objects

FROM sys.sql_modules
WHERE definition LIKE '%' + 'ColumnName' + '%'

-- Search in Stored Procedure Only

FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'ColumnName' + '%'

css to make bootstrap navbar transparent

<nav class="navbar navbar-fixed-top navbar-light" style="background-color: transparent;">

<!--This should work just fine. it will make it transparent. hope i helped!-->

CodeIgniter: How to use WHERE clause and OR clause

What worked for me :

  $where = '';
   /* $this->db->like('ust.title',$query_data['search'])
        $where .= "(ust.title like '%".$query_data['search']."%'";
        $where .= " or usr.f_name like '%".$query_data['search']."%'";
        $where .= "or usr.l_name like '%".$query_data['search']."%')";

$datas = $this->db->join(TBL_USERS.' AS usr','')
            ->where_in('', $blog_list) 
            ->select('ust.*,usr.f_name as f_name, as email,usr.avatar as avatar, as sex')
            ->get_where(TBL_GURU_BLOG.' AS ust',[
                'ust.deleted_at'     =>  NULL,
                'ust.status'     =>  1,

I have to do this to create a query like this :

SELECT `ust`.*, `usr`.`f_name` as `f_name`, `usr`.`email` as `email`, `usr`.`avatar` as `avatar`, `usr`.`sex` as `sex` FROM `blog` AS `ust` JOIN `users` AS `usr` ON `ust`.`user_id`=`usr`.`id` WHERE (`ust`.`title` LIKE '%mer%' ESCAPE '!' OR  `usr`.`f_name` LIKE '%lok%' ESCAPE '!' OR  `usr`.`l_name` LIKE '%mer%' ESCAPE '!') AND `ust`.`id` IN('36', '37', '38') AND `ust`.`deleted_at` IS NULL AND `ust`.`status` = 1 ;

How to delete large data of table in SQL without log?

This variation of M.Ali's is working fine for me. It deletes some, clears the log and repeats. I'm watching the log grow, drop and start over.

DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;
WHILE (@Deleted_Rows > 0)
   -- Delete some small number of rows at a time
    delete top (100000) from InstallLog where DateTime between '2014-12-01' and '2015-02-01'
    SET @Deleted_Rows = @@ROWCOUNT;
    dbcc shrinkfile (MobiControlDB_log,0,truncateonly);

localhost refused to connect Error in visual studio

I had the same problem. Deleting .vs folder (including all contents, folder might be hidden) worked for me.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

How to distinguish mouse "click" and "drag"

I think the difference is that there is a mousemove between mousedown and mouseup in a drag, but not in a click.

You can do something like this:

const element = document.createElement('div')
element.innerHTML = 'test'
let moved
let downListener = () => {
    moved = false
element.addEventListener('mousedown', downListener)
let moveListener = () => {
    moved = true
element.addEventListener('mousemove', moveListener)
let upListener = () => {
    if (moved) {
    } else {
        console.log('not moved')
element.addEventListener('mouseup', upListener)

// release memory
element.removeEventListener('mousedown', downListener)
element.removeEventListener('mousemove', moveListener)
element.removeEventListener('mouseup', upListener)

Android: How to change CheckBox size?

If you want to add a custom image to checkbox then set button to null and just add background to checkbox that's solve


How can I check for existence of element in std::vector, in one line?

int elem = 42;
std::vector<int> v;
if(std::find(v.begin(), v.end(), elem) != v.end())
  //elem exists in the vector

Check Postgres access for a user

For all users on a specific database, do the following:

# psql
\c your_database
select grantee, table_catalog, privilege_type, table_schema, table_name from information_schema.table_privileges order by grantee, table_schema, table_name;

SQL multiple columns in IN clause

In Oracle you can do this:

SELECT * FROM table1 WHERE (col_a,col_b) IN (SELECT col_x,col_y FROM table2)

Short IF - ELSE statement


or in your form:


How to stop C++ console application from exiting immediately?

You could always just create a batch file. For example, if your program is called helloworld.exe, some code would be:

@echo off
call helloworld.exe
pause >nul
goto :1

How do I access command line arguments in Python?

You can use sys.argv to get the arguments as a list.

If you need to access individual elements, you can use


where i is index, 0 will give you the python filename being executed. Any index after that are the arguments passed.

Serializing an object as UTF-8 XML in .NET

Very good answer using inheritance, just remember to override the initializer

public class Utf8StringWriter : StringWriter
    public Utf8StringWriter(StringBuilder sb) : base (sb)
    public override Encoding Encoding { get { return Encoding.UTF8; } }

Specify sudo password for Ansible

Using ansible and the following shall work:



And just run the playbook with this inventory as:

ansible-playbook -i inventory copyTest.yml

Error: stray '\240' in program


Error: stray '\240' in program is simply a character encoding error message.

From my experience, it is just a matter of character encoding. For example, if you copy a piece of code from a web page or you first write it in a text editor before copying and pasting in an IDE, it can come with the character encoding of the source document or editor.

jQuery: keyPress Backspace won't fire?

According to the jQuery documentation for .keypress(), it does not catch non-printable characters, so backspace will not work on keypress, but it is caught in keydown and keyup:

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser. (

In some instances keyup isn't desired or has other undesirable effects and keydown is sufficient, so one way to handle this is to use keydown to catch all keystrokes then set a timeout of a short interval so that the key is entered, then do processing in there after.

jQuery(el).keydown( function() { 
    var that = this; setTimeout( function(){ 
           /** Code that processes backspace, etc. **/ 
     }, 100 );  
 } );

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;

    &:before {
        content: "";

    &:after {
        content: "* * *";

What is the difference between association, aggregation and composition?

For two objects, Foo and Bar the relationships can be defined

Association - I have a relationship with an object. Foo uses Bar

public class Foo { 
    void Baz(Bar bar) {

Composition - I own an object and I am responsible for its lifetime. When Foo dies, so does Bar

public class Foo {
    private Bar bar = new Bar(); 

Aggregation - I have an object which I've borrowed from someone else. When Foo dies, Bar may live on.

public class Foo { 
    private Bar bar; 
    Foo(Bar bar) { = bar; 

syntax error, unexpected T_VARIABLE

There is no semicolon at the end of that instruction causing the error.


Like RiverC pointed out, there is no semicolon at the end of the previous line!

require ("scripts/connect.php") 


It seems you have no-semicolons whatsoever.

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.

How to check whether mod_rewrite is enable on server?

If you are in linux system, you can check all enable modules for apache2(in my case) in the following folder:/etc/apache2/mods-available

cd /etc/apache2/mods-available

to type: ll -a
if you want to check the available modules for php (in this case php 7 ) folder /etc/php/7.0/mods-available

cd /etc/php/7.0/mods-available

to type: ll -a

PHP - Notice: Undefined index:

Before you extract values from $_POST, you should check if they exist. You could use the isset function for this (

How to input matrix (2D list) in Python?

you can accept a 2D list in python this way ...


arr2d = [[j for j in input().strip()] for i in range(n)] 
# n is no of rows

for characters

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = list(input().strip())


n = int(input().strip())
n = int(input().strip())
a = []
for i in range(n):

for numbers

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = [int(j) for j in input().strip().split(" ")]

where n is no of elements in columns while m is no of elements in a row.

In pythonic way, this will create a list of list

Real differences between "java -server" and "java -client"?

IIRC, it involves garbage collection strategies. The theory is that a client and server will be different in terms of short-lived objects, which is important for modern GC algorithms.

Here is a link on server mode. Alas, they don't mention client mode.

Here is a very thorough link on GC in general; this is a more basic article. Not sure if either address -server vs -client but this is relevant material.

At No Fluff Just Stuff, both Ken Sipe and Glenn Vandenburg do great talks on this kind of thing.

Get selected item value from Bootstrap DropDown with specific ID

The selector would be #demolist.dropdown-menu li a note no space between id and class. However i would suggest a more generic approach:

<div class="input-group">                                            
    <input type="TextBox" Class="form-control datebox"></input>
    <div class="input-group-btn">
    <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
    <ul class="dropdown-menu">
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
        <li><a href="#">C</a></li>

$(document).on('click', '.dropdown-menu li a', function() {

by using a class rather than id, and using parent().find(), you can have as many of these on a page as you like, with no duplicated js

check if file exists on remote host with ssh

In addition to the answers above, there's the shorthand way to do it:

ssh -q $HOST [[ -f $FILE_PATH ]] && echo "File exists" || echo "File does not exist";

-q is quiet mode, it will suppress warnings and messages.

As @Mat mentioned, one advantage of testing like this is that you can easily swap out the -f for any test operator you like: -nt, -d, -s etc...

Test Operators:

How do I detect whether a Python variable is a function?

If this is for Python 2.x or for Python 3.2+, you can also use callable(). It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: You can do this with:


If this is for Python 3.x but before 3.2, check if the object has a __call__ attribute. You can do this with:

hasattr(obj, '__call__')

The oft-suggested types.FunctionTypes approach is not correct because it fails to cover many cases that you would presumably want it to pass, like with builtins:

>>> isinstance(open, types.FunctionType)

>>> callable(open)

The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container. Don't use types.FunctionType unless you have a very specific idea of what a function is.

isPrime Function for Python Language

With n**.5, you are not squaring n, but taking the square root.

Consider the number 20; the integer factors are 1, 2, 4, 5, 10, and 20. When you divide 20 by 2 and get 10, you know that it is also divisible by 10, without having to check. When you divide it by 4 and get 5, you know it is divisible by both 4 and 5, without having to check for 5.

After reaching this halfway point in the factors, you will have no more numbers to check which you haven't already recognized as factors earlier. Therefore, you only need to go halfway to see if something is prime, and this halfway point can be found by taking the number's square root.

Also, the reason 1 isn't a prime number is because prime numbers are defined as having 2 factors, 1 and itself. i.e 2 is 1*2, 3 is 1*3, 5 is 1*5. But 1 (1*1) only has 1 factor, itself. Therefore, it doesn't meet this definition.

How to prevent the "Confirm Form Resubmission" dialog?

I found an unorthodox way to accomplish this.

Just put the script page in an iframe. Doing so allows the page to be refreshed, seemingly even on older browsers without the "confirm form resubmission" message ever appearing.

Running multiple AsyncTasks at the same time -- not possible?

It is posible. My android device version is 4.0.4 and android.os.Build.VERSION.SDK_INT is 15

I have 3 spinners

Spinner c_fruit=(Spinner) findViewById(;
Spinner c_vegetable=(Spinner) findViewById(;
Spinner c_beverage=(Spinner) findViewById(;

And also I have a Async-Tack class.

Here is my spinner loading code

RequestSend reqs_fruit = new RequestSend(this);
reqs_fruit.title="Loading fruit";

RequestSend reqs_vegetable = new RequestSend(this);
reqs_vegetable.title="Loading vegetable";

RequestSend reqs_beverage = new RequestSend(this);
reqs_beverage.title="Loading beverage";

This is working perfectly. One by one my spinners loaded. I didn't user executeOnExecutor.

Here is my Async-task class

public class RequestSend  extends AsyncTask<String, String, String > {

    private ProgressDialog dialog = null;
    public Spinner spin;
    public String where;
    public String title;
    Context con;
    Activity activity;      
    String[] items;

    public RequestSend(Context activityContext) {
        con = activityContext;
        dialog = new ProgressDialog(activityContext);
        this.activity = activityContext;

    protected void onPostExecute(String result) {
        try {
            ArrayAdapter<String> adapter = new ArrayAdapter<String> (activity, android.R.layout.simple_spinner_item, items);       
        } catch (NullPointerException e) {
            Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
        } catch (Exception e)  {
            Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();

        if (dialog != null)

    protected void onPreExecute() {

    protected String doInBackground(String... Strings) {
        try {
            } catch (NullPointerException e) {
            } catch (Exception e) {
        return null;

    public void Send_Request() throws JSONException {

        try {
            String DataSendingTo = "" + where;
            HttpClient httpClient = new DefaultHttpClient();
            //Post header
            HttpPost httpPost = new HttpPost(DataSendingTo);
            //Adding data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

            nameValuePairs.add(new BasicNameValuePair("authorized","001"));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);

            BufferedReader reader;
            try {
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    builder.append(line) ;

                JSONTokener tokener = new JSONTokener(builder.toString());
                JSONArray finalResult = new JSONArray(tokener);
                items = new String[finalResult.length()]; 
                // looping through All details and store in public String array
                for(int i = 0; i < finalResult.length(); i++) {
                    JSONObject c = finalResult.getJSONObject(i);

            } catch (ClientProtocolException e) {
            } catch (IOException e) {

        } catch (ClientProtocolException e) {
        } catch (IOException e) {

check if array is empty (vba excel)

Above methods didn´t work for me. This did:

  Dim arrayIsNothing As Boolean

    On Error Resume Next
    arrayIsNothing = IsNumeric(UBound(YOUR_ARRAY)) And False
    If Err.Number <> 0 Then arrayIsNothing = True
    On Error GoTo 0

    'Now you can test:
    if arrayIsNothing then ...

Converting a Uniform Distribution to a Normal Distribution

I thing you should try this in EXCEL: =norminv(rand();0;1). This will product the random numbers which should be normally distributed with the zero mean and unite variance. "0" can be supplied with any value, so that the numbers will be of desired mean, and by changing "1", you will get the variance equal to the square of your input.

For example: =norminv(rand();50;3) will yield to the normally distributed numbers with MEAN = 50 VARIANCE = 9.

How to filter array when object key value is in array

Old way of doing it. Many might hate this way of doing but i still many time find this is still better in my perspective.


var records = [{
    "fname": "X",
    "lname": "Y"
    "fname": "A",
    "lname": "Y"
    "fname": "B",
    "lname": "Y"
    "fname": "C",
    "lname": "Y"
    "fname": "C",
    "lname": "Y"

var newArr = [1,4,5];


var newObj = [];
for(var a = 0 ; a < records.length ; a++){
 if(newArr.indexOf(records[a].empid) > -1){

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Reference -


    "empid": 1,
    "fname": "X",
    "lname": "Y"
}, {
    "empid": 4,
    "fname": "C",
    "lname": "Y"
}, {
    "empid": 5,
    "fname": "C",
    "lname": "Y"

Link and execute external JavaScript file hosted on GitHub is not truely raw access to file asset, but a view rendered by Rails. So accessing is much heavier than needed. I don't know why is implemented as a Rails view. Instead of fix this route issue, GitHub added a X-Content-Type-Options: nosniff header.


  • Put the script to
  • Use a third party CDN like

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.

Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

Push git commits & tags simultaneously

Maybe this helps someone:

git tag 0.0.1                    # creates tag locally     
git push origin 0.0.1            # pushes tag to remote

git tag --delete 0.0.1           # deletes tag locally    
git push --delete origin 0.0.1   # deletes remote tag

Python 3 Building an array of bytes

I think Scapy is what are you looking for.

you can build and send frames (packets) with it

How to send email using simple SMTP commands via Gmail?

to send over gmail, you need to use an encrypted connection. this is not possible with telnet alone, but you can use tools like openssl

either connect using the starttls option in openssl to convert the plain connection to encrypted...

openssl s_client -starttls smtp -connect -crlf -ign_eof

or connect to a ssl sockect directly...

openssl s_client -connect -crlf -ign_eof

EHLO localhost

after that, authenticate to the server using the base64 encoded username/password

AUTH PLAIN AG15ZW1haWxAZ21haWwuY29tAG15cGFzc3dvcmQ=

to get this from the commandline:

echo -ne '\[email protected]\00password' | base64

then continue with "mail from:" like in your example

example session:

openssl s_client -connect -crlf -ign_eof
[... lots of openssl output ...]
220 ESMTP m46sm11546481eeh.9
EHLO localhost at your service, []
250-SIZE 35882577
AUTH PLAIN AG5pY2UudHJ5QGdtYWlsLmNvbQBub2l0c25vdG15cGFzc3dvcmQ=
235 2.7.0 Accepted
MAIL FROM: <[email protected]>
250 2.1.0 OK m46sm11546481eeh.9
rcpt to: <[email protected]>
250 2.1.5 OK m46sm11546481eeh.9
354  Go ahead m46sm11546481eeh.9
Subject: it works

250 2.0.0 OK 1339757532 m46sm11546481eeh.9
221 2.0.0 closing connection m46sm11546481eeh.9

Using async/await for multiple tasks

Parallel.ForEach requires a list of user-defined workers and a non-async Action to perform with each worker.

Task.WaitAll and Task.WhenAll require a List<Task>, which are by definition asynchronous.

I found RiaanDP's response very useful to understand the difference, but it needs a correction for Parallel.ForEach. Not enough reputation to respond to his comment, thus my own response.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncTest
    class Program
        class Worker
            public int Id;
            public int SleepTimeout;

            public void DoWork(DateTime testStart)
                var workerStart = DateTime.Now;
                Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
                    Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
                var workerEnd = DateTime.Now;
                Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
                   Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));

            public async Task DoWorkAsync(DateTime testStart)
                var workerStart = DateTime.Now;
                Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
                    Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
                await Task.Run(() => Thread.Sleep(SleepTimeout));
                var workerEnd = DateTime.Now;
                Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
                   Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));

        static void Main(string[] args)
            var workers = new List<Worker>
                new Worker { Id = 1, SleepTimeout = 1000 },
                new Worker { Id = 2, SleepTimeout = 2000 },
                new Worker { Id = 3, SleepTimeout = 3000 },
                new Worker { Id = 4, SleepTimeout = 4000 },
                new Worker { Id = 5, SleepTimeout = 5000 },

            var startTime = DateTime.Now;
            Console.WriteLine("Starting test: Parallel.ForEach...");
            PerformTest_ParallelForEach(workers, startTime);
            var endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WaitAll...");
            PerformTest_TaskWaitAll(workers, startTime);
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WhenAll...");
            var task = PerformTest_TaskWhenAll(workers, startTime);
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));


        static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
            Parallel.ForEach(workers, worker => worker.DoWork(testStart));

        static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
            Task.WaitAll(workers.Select(worker => worker.DoWorkAsync(testStart)).ToArray());

        static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
            return Task.WhenAll(workers.Select(worker => worker.DoWorkAsync(testStart)));

The resulting output is below. Execution times are comparable. I ran this test while my computer was doing the weekly anti virus scan. Changing the order of the tests did change the execution times on them.

Starting test: Parallel.ForEach...
Worker 1 started on thread 9, beginning 0.02 seconds after test start.
Worker 2 started on thread 10, beginning 0.02 seconds after test start.
Worker 3 started on thread 11, beginning 0.02 seconds after test start.
Worker 4 started on thread 13, beginning 0.03 seconds after test start.
Worker 5 started on thread 14, beginning 0.03 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.02 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.02 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.03 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.03 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.03 seconds after the test start.
Test finished after 5.03 seconds.

Starting test: Task.WaitAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.

Starting test: Task.WhenAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.

How to set text color to a text view programmatically

Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:


Please note that from API 23, getResources().getColor() is deprecated. Use instead:

textView.setTextColor(ContextCompat.getColor(context, R.color.some_color));

where the required color is defined in an xml as:

  <color name="some_color">#bdbdbd</color>


This method was deprecated in API level 23. Use getColor(int, Theme) instead.

Check this.

SQL left join vs multiple tables on FROM line?

Well the first and second queries may yield different results because a LEFT JOIN includes all records from the first table, even if there are no corresponding records in the right table.

What's the key difference between HTML 4 and HTML 5?

HTML5 has several goals which differentiate it from HTML4.

Consistency in Handling Malformed Documents

The primary one is consistent, defined error handling. As you know, HTML purposely supports 'tag soup', or the ability to write malformed code and have it corrected into a valid document. The problem is that the rules for doing this aren't written down anywhere. When a new browser vendor wants to enter the market, they just have to test malformed documents in various browsers (especially IE) and reverse-engineer their error handling. If they don't, then many pages won't display correctly (estimates place roughly 90% of pages on the net as being at least somewhat malformed).

So, HTML5 is attempting to discover and codify this error handling, so that browser developers can all standardize and greatly reduce the time and money required to display things consistently. As well, long in the future after HTML has died as a document format, historians may still want to read our documents, and having a completely defined parsing algorithm will greatly aid this.

Better Web Application Features

The secondary goal of HTML5 is to develop the ability of the browser to be an application platform, via HTML, CSS, and Javascript. Many elements have been added directly to the language that are currently (in HTML4) Flash or JS-based hacks, such as <canvas>, <video>, and <audio>. Useful things such as Local Storage (a js-accessible browser-built-in key-value database, for storing information beyond what cookies can hold), new input types such as date for which the browser can expose easy user interface (so that we don't have to use our js-based calendar date-pickers), and browser-supported form validation will make developing web applications much simpler for the developers, and make them much faster for the users (since many things will be supported natively, rather than hacked in via javascript).

Improved Element Semantics

There are many other smaller efforts taking place in HTML5, such as better-defined semantic roles for existing elements (<strong> and <em> now actually mean something different, and even <b> and <i> have vague semantics that should work well when parsing legacy documents) and adding new elements with useful semantics - <article>, <section>, <header>, <aside>, and <nav> should replace the majority of <div>s used on a web page, making your pages a bit more semantic, but more importantly, easier to read. No more painful scanning to see just what that random </div> is closing - instead you'll have an obvious </header>, or </article>, making the structure of your document much more intuitive.

Why should a Java class implement comparable?

Here is a real life sample. Note that String also implements Comparable.

class Author implements Comparable<Author>{
    String firstName;
    String lastName;

    public int compareTo(Author other){
        // compareTo should return < 0 if this is supposed to be
        // less than other, > 0 if this is supposed to be greater than 
        // other and 0 if they are supposed to be equal
        int last = this.lastName.compareTo(other.lastName);
        return last == 0 ? this.firstName.compareTo(other.firstName) : last;


 * List the authors. Sort them by name so it will look good.
public List<Author> listAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    return authors;

 * List unique authors. Sort them by name so it will look good.
public SortedSet<Author> listUniqueAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    return new TreeSet<Author>(authors);

Select rows having 2 columns equal value

select t.* from table t
    join (
        select C2, C3, C4
        from table
        group by C2, C3, C4
        having count(*) > 1
    ) t2
    using (C2, C3, C4);

Redirect HTTP to HTTPS on default virtual host without ServerName

I have use mkcert to create infinites * subdomains & localhost with valid HTTPS/SSL certs (Windows 10 XAMPP & Linux Debian 10 Apache2)

I create the certs on Windows with mkcert v1.4.0 (execute CMD as Administrator):

mkcert -install
mkcert localhost "*"

This create in Windows 10 this files (I will install it first in Windows 10 XAMPP)


Overwrite the XAMPP default certs:

copy "localhost+1.pem" C:\xampp\apache\conf\ssl.crt\server.crt
copy "localhost+1-key.pem"  C:\xampp\apache\conf\ssl.key\server.key

Now, in Apache2 for Debian 10, activate SSL & vhost_alias

a2enmod vhosts_alias
a2enmod ssl
a2ensite default-ssl
systemctl restart apache2

For vhost_alias add this Apache2 config:

nano /etc/apache2/sites-available/999-vhosts_alias.conf

With this content:

<VirtualHost *:80>
   UseCanonicalName Off
   ServerAlias *
   VirtualDocumentRoot "/var/www/html/%0/"

Add the site:

a2ensite 999-vhosts_alias

Copy the certs to /root/mkcert by SSH and let overwrite the Debian ones:

systemctl stop apache2

mv /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/certs/ssl-cert-snakeoil.pem.bak
mv /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/ssl-cert-snakeoil.key.bak

cp "localhost+1.pem" /etc/ssl/certs/ssl-cert-snakeoil.pem
cp "localhost+1-key.pem" /etc/ssl/private/ssl-cert-snakeoil.key

chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key

systemctl start apache2

Edit the SSL config

nano /etc/apache2/sites-enabled/default-ssl.conf

At the start edit the file with this content:

<IfModule mod_ssl.c>
    <VirtualHost *:443>

            UseCanonicalName Off
            ServerAlias *
            ServerAdmin webmaster@localhost

            # DocumentRoot /var/www/html/
            VirtualDocumentRoot /var/www/html/%0/


Last restart:

systemctl restart apache2

NOTE: don´t forget to create the folders for your subdomains in /var/www/html/


addEventListener for keydown on Canvas

Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.

In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )

Android video streaming example

I was facing the same problem and found a solution to get the code to work.

The code given in the android-Sdk/samples/android-?/ApiDemos works fine. Copy paste each folder in the android project and then in the put the path of the video you want to stream in the path variable. It is left blank in the code.

The following video stream worked for me:

I know that RTSP protocol is to be used for streaming, but mediaplayer class supports http for streaming as mentioned in the code.

I googled for the format of the video and found that the video if converted to mp4 or 3gp using Quicktime Pro works fine for streaming.

I tested the final apk on android 2.1. The application dosent work on emulators well. Try it on devices.

I hope this helps..

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
$(info ************  TEST VERSION ************)
$(info ************ RELEASE VERSIOIN **********)

Easy way to make a confirmation dialog in Angular?

Method 1

One simple way to confirm is to use the native browser confirm alert. The template can have a button or link.

<button type=button class="btn btn-primary"  (click)="clickMethod('name')">Delete me</button>

And the component method can be something like below.

clickMethod(name: string) {
  if(confirm("Are you sure to delete "+name)) {
    console.log("Implement delete functionality here");

Method 2

Another way to get a simple confirmation dialog is to use the angular bootstrap components like ng-bootstrap or ngx-bootstrap. You can simply install the component and use the modal component.

  1. Examples of modals using ng-bootstrap
  2. Examples of modals using ngx-bootstrap.

Method 3

Provided below is another way to implement a simple confirmation popup using angular2/material that I implemented in my project.


import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';

  imports: [
  declarations: [
  providers: [ ... ],
  bootstrap: [ AppComponent ],
  entryComponents: [ConfirmationDialog]
export class AppModule { }


import { Component, Input } from '@angular/core';
import { MdDialog, MdDialogRef } from '@angular/material';

  selector: 'confirm-dialog',
  templateUrl: '/app/confirm-dialog/confirmation-dialog.html',
export class ConfirmationDialog {
  constructor(public dialogRef: MdDialogRef<ConfirmationDialog>) {}

  public confirmMessage:string;


<h1 md-dialog-title>Confirm</h1>
<div md-dialog-content>{{confirmMessage}}</div>
<div md-dialog-actions>
  <button md-button style="color: #fff;background-color: #153961;" (click)="dialogRef.close(true)">Confirm</button>
  <button md-button (click)="dialogRef.close(false)">Cancel</button>


<button (click)="openConfirmationDialog()">Delete me</button>


import { MdDialog, MdDialogRef } from '@angular/material';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';

  templateUrl: '/app/app.component.html',
  styleUrls: ['/app/main.css']

export class AppComponent implements AfterViewInit {
  dialogRef: MdDialogRef<ConfirmationDialog>;

  constructor(public dialog: MdDialog) {}

  openConfirmationDialog() {
    this.dialogRef =, {
      disableClose: false
    this.dialogRef.componentInstance.confirmMessage = "Are you sure you want to delete?"

    this.dialogRef.afterClosed().subscribe(result => {
      if(result) {
        // do confirmation actions
      this.dialogRef = null;

index.html => added following stylesheet

<link rel="stylesheet" href="node_modules/@angular/material/core/theming/prebuilt/indigo-pink.css">

How to make a rest post call from ReactJS code?

Here is an example:

    type: 'POST',
    url: '/some/url',
    data: data
  .done(function(result) {
  .fail(function(jqXhr) {
    console.log('failed to register');

It used jquery.ajax method but you can easily replace it with AJAX based libs like axios, superagent or fetch.

Using psql to connect to PostgreSQL in SSL mode

On psql client v12, I could not find option in psql client to activate sslmode=verify-full.

I ended up using environment variables :

PGSSLMODE=verify-full PGSSLROOTCERT=server-ca.pem psql -h your_host -U your_user -W -d your_db

UIScrollView scroll to bottom programmatically

valdyr, hope this will help you:

CGPoint bottomOffset = CGPointMake(0, [textView contentSize].height - textView.frame.size.height);

if (bottomOffset.y > 0)
 [textView setContentOffset: bottomOffset animated: YES];

Why do people write #!/usr/bin/env python on the first line of a Python script?

It probably makes sense to emphasize one thing that the most have missed, which may prevent immediate understanding. When you type python in terminal you don't normally provide a full path. Instead, the executable is up looked in PATH environment variable. In turn, when you want to execute a Python program directly, /path/to/, one must tell the shell what interpreter to use (via the hashbang, what the other contributors are explaining above).

Hashbang expects full path to an interpreter. Thus to run your Python program directly you have to provide full path to Python binary which varies significantly, especially considering a use of virtualenv. To address portability the trick with /usr/bin/env is used. The latter is originally intended to alter environment in-place and run a command in it. When no alteration is provided it runs the command in current environment, which effectively results in the same PATH lookup which does the trick.

Source from unix stackexchange

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

Uncaught ReferenceError: function is not defined with onclick

I think you put the function in the $(document).ready....... The functions are always provided out the $(document).ready.......

Is it possible to force row level locking in SQL Server?


ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);

SQL: How to properly check if a record exists

You can use:



( SELECT 1 FROM MyTable WHERE ... )

This will be more efficient than SELECT * since you're simply selecting the value 1 for each row, rather than all the fields.

There's also a subtle difference between COUNT(*) and COUNT(column name):

  • COUNT(*) will count all rows, including nulls
  • COUNT(column name) will only count non null occurrences of column name

How to turn off word wrapping in HTML?

This worked for me to stop silly work breaks from happening within Chrome textareas

word-break: keep-all;

Is there a Python equivalent to Ruby's string interpolation?

Python 3.6 and newer have literal string interpolation using f-strings:

print(f"Hello {name}!")

How to preview a part of a large pandas DataFrame, in iPython notebook?

df.head(5) # will print out the first 5 rows
df.tail(5) # will print out the 5 last rows

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

Here is the solution which worked for me.

OUTPUT: State of Cart Widget is updated, upon addition of items.

enter image description here

Create a globalKey for the widget you want to update by calling the trigger from anywhere

final GlobalKey<CartWidgetState> cartKey = GlobalKey();

Make sure it's saved in a file have global access such that, it can be accessed from anywhere. I save it in globalClass where is save commonly used variables through the app's state.

class CartWidget extends StatefulWidget {

  CartWidget({Key key}) : super(key: key);
  CartWidgetState createState() => CartWidgetState();

class CartWidgetState extends State<CartWidget> {
  Widget build(BuildContext context) {
    //return your widget
    return Container();

Call your widget from some other class.

class HomeScreen extends StatefulWidget {

  HomeScreen ({Key key}) : super(key: key);
  HomeScreenState createState() => HomeScreen State();

class HomeScreen State extends State<HomeScreen> {
  Widget build(BuildContext context) {
    return ListView(

class ChildScreen extends StatefulWidget {

  ChildScreen ({Key key}) : super(key: key);
  ChildScreenState createState() => ChildScreen State();

class ChildScreen State extends State<ChildScreen> {
  Widget build(BuildContext context) {
    return InkWell(
              onTap: (){
                // This will update the state of your inherited widget/ class
                if (cartKey.currentState != null)
                    cartKey.currentState.setState(() {});
              child: Text("Update The State of external Widget"),

How to retrieve Jenkins build parameters using the Groovy API?

Update: Jenkins 2.x solution:

With Jenkins 2 pipeline dsl, you can directly access any parameter with the trivial syntax based on the params (Map) built-in:

echo " FOOBAR value: ${params.'FOOBAR'}"

The returned value will be a String or a boolean depending on the Parameter type itself. The syntax is the same for scripted or declarative syntax. More info at:

Original Answer for Jenkins 1.x:

For Jenkins 1.x, the syntax is based on the build.buildVariableResolver built-ins:

// ... or if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)

Please note the official Jenkins Wiki page covers this in more details as well, especially how to iterate upon the build parameters:

The salient part is reproduced below:

// get parameters
def parameters = build?.actions.find{ it instanceof ParametersAction }?.parameters
parameters.each {
   println "parameter ${}:"
   println it.dump()

Are iframes considered 'bad practice'?

They are not bad, but actually helpful. I had a huge problem some time ago where I had to embed my twitter feed and it just wouldn't let md do it on the same page, so I set it on a different page, and put it in as an iframe.

They are also good because all browsers (and phone browsers) support them. They can not be considered a bad practice, as long as you use them correctly.

Description for event id from source cannot be found

Use PowerShell to create your event log and source:

New-EventLog -LogName MyApplicationLog `
    -Source MySource `
    -MessageResourceFile C:\windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll

You'll need the messages dll to avoid the problem you are seeing.

What possibilities can cause "Service Unavailable 503" error?

Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...

  1. Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]

  2. Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.

In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.

What is a Crash (technically)... in ASP.NET and what to do if it happens?

Best way to find the months between two dates

#This definition gives an array of months between two dates.
import datetime
def MonthsBetweenDates(BeginDate, EndDate):
    firstyearmonths = [mn for mn in range(BeginDate.month, 13)]<p>
    lastyearmonths = [mn for mn in range(1, EndDate.month+1)]<p>
    months = [mn for mn in range(1, 13)]<p>
    numberofyearsbetween = EndDate.year - BeginDate.year - 1<p>
    return firstyearmonths + months * numberofyearsbetween + lastyearmonths<p>

BD = datetime.datetime.strptime("2000-35", '%Y-%j')
ED = datetime.datetime.strptime("2004-200", '%Y-%j')
MonthsBetweenDates(BD, ED)

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

How do I fix "The expression of type List needs unchecked conversion...'?

If you don't want to put @SuppressWarning("unchecked") on each sf.getEntries() call, you can always make a wrapper that will return List.

See this other question

Cannot find mysql.sock

Unfortunately none of the above have worked in my case. But finally I found solutions.

To find where is mysql.sock file, simply open xampp manager, select MySQL and click on Configure on the right. On the config panel click Open Conf File, and simply search for mysql.sock by pressing the CMD+F shortcut.

In my case, the owner of the mysql.sock was changed, and I had to change it back to root admin with: chmod root:admin mysql.sock

After that the database had been accessed.

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

I had this problem despite:

  • having a main(); and
  • configuring all other projects in my solution to be static libraries.

My eventual fix was the following:

  • my main() was in a namespace, so was effectively called something::main() ...removing this namespace fixed the problem.

How do I create a file at a specific path?

I recommend using the os module to avoid trouble in cross-platform. (windows,linux,mac)

Cause if the directory doesn't exists, it will return an exception.

import os

filepath = os.path.join('c:/your/full/path', 'filename')
if not os.path.exists('c:/your/full/path'):
f = open(filepath, "a")

If this will be a function for a system or something, you can improve it by adding try/except for error control.

Python: create dictionary using dict() with integer keys?

Yes, but not with that version of the constructor. You can do this:

>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}

There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."

internal/modules/cjs/loader.js:582 throw err

Hashan Gunathilaka was correct. this strange behavior exists. I just deleted the duplicates and closed the command prompt to open again in windows. Worked fine.

How to delete multiple pandas (python) dataframes from memory to save RAM?

del statement does not delete an instance, it merely deletes a name.

When you do del i, you are deleting just the name i - but the instance is still bound to some other name, so it won't be Garbage-Collected.

If you want to release memory, your dataframes has to be Garbage-Collected, i.e. delete all references to them.

If you created your dateframes dynamically to list, then removing that list will trigger Garbage Collection.

>>> lst = [pd.DataFrame(), pd.DataFrame(), pd.DataFrame()]
>>> del lst     # memory is released

If you created some variables, you have to delete them all.

>>> a, b, c = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
>>> lst = [a, b, c]
>>> del a, b, c # dfs still in list
>>> del lst     # memory release now

Position absolute but relative to parent

Incase someone wants to postion a child div directly under a parent

#father {
   position: relative;

#son1 {
   position: absolute;
   top: 100%;

Working demo Codepen

Delete a row from a table by id

The parent of the row is not the object you think, this is what I understand from the error.
Try detecting the parent of the row first, then you can be sure what to write into getElementById part of the parent.

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

Instead of handcranking your models try using something like the website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.

Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.

EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used to create the class for me)

public class Job
        public string id { get; set; }
        public string position_title { get; set; }
        public string organization_name { get; set; }
        public string rate_interval_code { get; set; }
        public int minimum { get; set; }
        public int maximum { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
        public List<string> locations { get; set; }
        public string url { get; set; }

And an edit to your code:

        List<Job> model = null;
        var client = new HttpClient();
        var task = client.GetAsync("")
          .ContinueWith((taskwithresponse) =>
              var response = taskwithresponse.Result;
              var jsonString = response.Content.ReadAsStringAsync();
              model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);


This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.


There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:

How to reposition Chrome Developer Tools

Looks like this is on the bottom left now as an icon with overlapping windows and the "Undock into separate window." tooltip.

enter image description here

How to get value at a specific index of array In JavaScript?

Array indexes in JavaScript start at zero for the first item, so try this:

var firstArrayItem = myValues[0]

Of course, if you actually want the second item in the array at index 1, then it's myValues[1].

See Accessing array elements for more info.

Scale image to fit a bounding box

This helped me:

.img-class {
  width: <img width>;
  height: <img height>;
  content: url('/path/to/img.png');

Then on the element (you can use javascript or media queries to add responsiveness):

<div class='img-class' style='transform: scale(X);'></div>

Hope this helps!

Argparse: Required arguments listed under "optional arguments"?

Parameters starting with - or -- are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional arguments, they will still be listed under the confusing header “optional arguments” even if they are required. The missing square brackets in the usage part however show that they are indeed required.

See also the documentation:

In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.

Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.

That being said, the headers “positional arguments” and “optional arguments” in the help are generated by two argument groups in which the arguments are automatically separated into. Now, you could “hack into it” and change the name of the optional ones, but a far more elegant solution would be to create another group for “required named arguments” (or whatever you want to call them):

parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('-o', '--output', help='Output file name', default='stdout')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)
usage: [-h] [-o OUTPUT] -i INPUT


optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        Output file name

required named arguments:
  -i INPUT, --input INPUT
                        Input file name

how to refresh page in angular 2


How to implement page refresh in Angular 2+ note this is done within your component:


Common sources of unterminated string literal

The web page developer guessed wrong about which encoding is used by the viewer's browser. This can usually be solved by specifying an encoding in the page's header.

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

You may want to check out Eclipse CDT. It provides a C/C++ IDE that runs on multiple platforms (e.g. Windows, Linux, Mac OS X, etc.). Debugging with Eclipse CDT is comparable to using other tools such as Visual Studio.

You can check out the Eclipse CDT Debug tutorial that also includes a number of screenshots.

SQLite with encryption/password protection

Keep in mind, the following is not intended to be a substitute for a proper security solution.

After playing around with this for four days, I've put together a solution using only the open source System.Data.SQLite package from NuGet. I don't know how much protection this provides. I'm only using it for my own course of study. This will create the DB, encrypt it, create a table, and add data.

using System.Data.SQLite;

namespace EncryptDB
    class Program
        static void Main(string[] args)
            string connectionString = @"C:\Programming\sqlite3\db.db";
            string passwordString = "password";
            byte[] passwordBytes = GetBytes(passwordString);
            SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString + ";Version=3;");
            SQLiteCommand sqlCmd = new SQLiteCommand("CREATE TABLE data(filename TEXT, filepath TEXT, filelength INTEGER, directory TEXT)", conn);
            sqlCmd = new SQLiteCommand("INSERT INTO data VALUES('name', 'path', 200, 'dir')", conn);
        static byte[] GetBytes(string str)
            byte[] bytes = new byte[str.Length * sizeof(char)];
            bytes = System.Text.Encoding.Default.GetBytes(str);
            return bytes;

Optionally, you can remove conn.SetPassword(passwordBytes);, and replace it with conn.ChangePassword("password"); which needs to be placed after conn.Open(); instead of before. Then you won't need the GetBytes method.

To decrypt, it's just a matter of putting the password in your connection string before the call to open.

        string filename = @"C:\Programming\sqlite3\db.db";
        string passwordString = "password";
        SQLiteConnection conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;Password=" + passwordString + ";");

How do I use NSTimer?

#import "MyViewController.h"

@interface MyViewController ()

@property (strong, nonatomic) NSTimer *timer;


@implementation MyViewController

double timerInterval = 1.0f;

- (NSTimer *) timer {
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:timerInterval target:self selector:@selector(onTick:) userInfo:nil repeats:YES];
    return _timer;

- (void)viewDidLoad
    [super viewDidLoad];

    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];



How to disable a input in angular2

I prefer this solution

In HTML file:

<input [disabled]="dynamicVariable" id="name" type="text">

In TS file:

dynamicVariable = false; // true based on your condition 

How to set 00:00:00 using moment.js

You've not shown how you're creating the string 2016-01-12T23:00:00.000Z, but I assume via .format().

Anyway, .set() is using your local time zone, but the Z in the time string indicates zero time, otherwise known as UTC.

So I assume your local timezone is 23 hours from UTC?

saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format() call that outputs using your local timezone, rather than UTC.

MySQL: How to allow remote connection to mysql

some times need to use name of pc on windows

first step) put in config file of mysql:

mysqld.cnf SET bind-address=

(to let recibe connections over tcp/ip)

second step) make user in mysql, table users, with name of pc on windows propierties, NOT ip

enter image description here

jquery append external html file into my page

You can use jquery's load function here.


If you need more info, here is the link.

DTO pattern: Best way to copy properties between two objects

You can use Apache Commmons Beanutils. The API is

org.apache.commons.beanutils.PropertyUtilsBean.copyProperties(Object dest, Object orig).

It copies property values from the "origin" bean to the "destination" bean for all cases where the property names are the same.

Now I am going to off topic. Using DTO is mostly considered an anti-pattern in EJB3. If your DTO and your domain objects are very alike, there is really no need to duplicate codes. DTO still has merits, especially for saving network bandwidth when remote access is involved. I do not have details about your application architecture, but if the layers you talked about are logical layers and does not cross network, I do not see the need for DTO.

Bootstrap 3 offset on right not left

I modified Bootstrap SASS (v3.3.5) based on Rukshan's answer

Add this in the end of the calc-grid-column mixin in mixins/_grid-framework.scss, right below the $type == offset if condition.

@if ($type == offset-right) {
      .col-#{$class}-offset-right-#{$index} {
          margin-right: percentage(($index / $grid-columns));

Modify the make-grid mixin in mixins/_grid-framework.scss to generate the offset-right classes.

// Create grid for specific class
@mixin make-grid($class) {
  @include float-grid-columns($class);
  @include loop-grid-columns($grid-columns, $class, width);
  @include loop-grid-columns($grid-columns, $class, pull);
  @include loop-grid-columns($grid-columns, $class, push);
  @include loop-grid-columns($grid-columns, $class, offset);
  @include loop-grid-columns($grid-columns, $class, offset-right);

You can then use the classes like col-sm-offset-right-2 and col-md-offset-right-1

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

None of these examples on this page worked for me. This is what I used and it worked well. Some solutions said you cannot combine url with $state.go() but this is not true. The awkward thing is you must define the params for the url and also list the params. Both must be present. Tested on Angular 1.4.8 and UI Router 0.2.15.

In the state add your params to end of state and define the params:

url: 'view?index&anotherKey',
params: {'index': null, 'anotherKey': null}

In your controller your go statement will look like this:

$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' });

Then to pull the params out and use them in your new state's controller (don't forget to pass in $stateParams to your controller function):

var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
console.log(anotherKey); //it works! cannot be cast to

In my case, when I'm in an activity that extends from AppCompatActivity, it did not work(Activity) getApplicationContext (), I just putthis in its place.

Add JVM options in Tomcat

After checking (for windows use the .bat versions of everything mentioned below)

#   Do not set the variables in this script. Instead put them into a script
# in CATALINA_BASE/bin to keep your customizations separate.

Also this

#   CATALINA_OPTS   (Optional) Java runtime options used when the "start",
#                   "run" or "debug" command is executed.
#                   Include here and not in JAVA_OPTS all options, that should
#                   only be used by Tomcat itself, not by the stop process,
#                   the version command etc.
#                   Examples are heap size, GC logging, JMX ports etc

So create a under CATALINA_BASE/bin (same dir where the resides). Edit the file and set the arguments to CATALINA_OPTS

For e.g. the file would look like this if you wanted to change the heap size


Or in your case since you're using windows setenv.bat would be

set CATALINA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5

To clear the added options later just delete setenv.bat/sh

Callback functions in Java

A method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that.

Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.

jQuery ajax error function

Try this:

error: function(jqXHR, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);

If you want to inform your frontend about a validation error, try to return json:

dataType: 'json',
success: function(data, textStatus, jqXHR) {

Your asp script schould return:

{"error": true}

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>> pattern = re.compile('is')
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post


Also detailed in the one of the best books to start learning python with


Android fastboot waiting for devices

try to use compiler generated fastboot when this happes. the file path is out/host/linux(or other)/bin/fastboot and sudo is also needed. it works in most of the time.

How to check if a double is null?

I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

If you have a PEM file (e.g. server.pem) containing:

  • the trusted certificate
  • the private key

then you can import the certificate and key into a JKS keystore like this:

1) Copy the private key from the PEM file into an ascii file (e.g. server.key)

2) Copy the cert from the PEM file into an ascii file (e.g. server.crt)

3) Export the cert and key into a PKCS12 file:

$ openssl pkcs12 -export -in server.crt -inkey server.key \
                 -out server.p12 -name [some-alias] -CAfile server.pem -caname root
  • the PEM file can be used as the argument to the -CAfile option.
  • you are prompted for an 'export' password.
  • if doing this in git bash then add winpty to the start of the command so the export password can be entered.

4) Convert the PKCS12 file to a JKS keystore:

$ keytool -importkeystore -deststorepass changeit -destkeypass changeit \
          -destkeystore keystore.jks  -srckeystore server.p12 -srcstoretype PKCS12 \
          -srcstorepass changeit
  • the srcstorepass password should match the export password from step 3)

'^M' character at end of lines

Fix line endings in vi by running the following:

:set fileformat=unix


How do I change tab size in Vim?

Several of the answers on this page are 'single use' fixes to the described problem. Meaning, the next time you open a document with vim, the previous tab settings will return.

If anyone is interested in permanently changing the tab settings:

Calculate the display width of a string in Java

Use the getWidth method in the following class:

import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;

class StringMetrics {

  Font font;
  FontRenderContext context;

  public StringMetrics(Graphics2D g2) {

    font = g2.getFont();
    context = g2.getFontRenderContext();

  Rectangle2D getBounds(String message) {

    return font.getStringBounds(message, context);

  double getWidth(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getWidth();

  double getHeight(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getHeight();


How to make the HTML link activated by clicking on the <li>?

The following seems to work:

ul#menu li a {

C# Convert List<string> to Dictionary<string, string>

Use this:

var dict = list.ToDictionary(x => x);

See MSDN for more info.

As Pranay points out in the comments, this will fail if an item exists in the list multiple times.
Depending on your specific requirements, you can either use var dict = list.Distinct().ToDictionary(x => x); to get a dictionary of distinct items or you can use ToLookup instead:

var dict = list.ToLookup(x => x);

This will return an ILookup<string, string> which is essentially the same as IDictionary<string, IEnumerable<string>>, so you will have a list of distinct keys with each string instance under it.

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

When you are trying to visit a local filename through firefox browser, you have to force the file:\\\ protocol ( or else firefox will encode your space TWICE. Change the html snippet from this:

<img src="C:\Documents and Settings\screenshots\Image01.png"/>

to this:

<img src="file:\\\C:\Documents and Settings\screenshots\Image01.png"/>

or this:

<img src="file://C:\Documents and Settings\screenshots\Image01.png"/>

Then firefox is notified that this is a local filename, and it renders the image correctly in the browser, correctly encoding the string once.

Helpful link:

"E: Unable to locate package python-pip" on Ubuntu 18.04

ls /bin/python*

Identify the highest version of python listed. If the highest version is something like python2.7 then install python2-pip If its something like python3.8 then install python3-pip

Example for python3.8:

sudo apt-get install python3-pip

How to randomly select rows in SQL?

In order to shuffle the SQL result set, you need to use a database-specific function call.

Note that sorting a large result set using a RANDOM function might turn out to be very slow, so make sure you do that on small result sets.

If you have to shuffle a large result set and limit it afterward, then it's better to use something like the Oracle SAMPLE(N) or the TABLESAMPLE in SQL Server or PostgreSQL instead of a random function in the ORDER BY clause.

So, assuming we have the following database table:

Song database table

And the following rows in the song table:

| id | artist                          | title                              |
| 1  | Miyagi & ???????? ft. ??? ????? | I Got Love                         |
| 2  | HAIM                            | Don't Save Me (Cyril Hahn Remix)   |
| 3  | 2Pac ft. DMX                    | Rise Of A Champion (GalilHD Remix) |
| 4  | Ed Sheeran & Passenger          | No Diggity (Kygo Remix)            |
| 5  | JP Cooper ft. Mali-Koa          | All This Love                      |


On Oracle, you need to use the DBMS_RANDOM.VALUE function, as illustrated by the following example:

    artist||' - '||title AS song
FROM song

When running the aforementioned SQL query on Oracle, we are going to get the following result set:

| song                                              |
| JP Cooper ft. Mali-Koa - All This Love            |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |

Notice that the songs are being listed in random order, thanks to the DBMS_RANDOM.VALUE function call used by the ORDER BY clause.

SQL Server

On SQL Server, you need to use the NEWID function, as illustrated by the following example:

    CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song

When running the aforementioned SQL query on SQL Server, we are going to get the following result set:

| song                                              |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |
| JP Cooper ft. Mali-Koa - All This Love            |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |

Notice that the songs are being listed in random order, thanks to the NEWID function call used by the ORDER BY clause.


On PostgreSQL, you need to use the random function, as illustrated by the following example:

    artist||' - '||title AS song
FROM song
ORDER BY random()

When running the aforementioned SQL query on PostgreSQL, we are going to get the following result set:

| song                                              |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love            |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |

Notice that the songs are being listed in random order, thanks to the random function call used by the ORDER BY clause.


On MySQL, you need to use the RAND function, as illustrated by the following example:

  CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song

When running the aforementioned SQL query on MySQL, we are going to get the following result set:

| song                                              |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love            |

Notice that the songs are being listed in random order, thanks to the RAND function call used by the ORDER BY clause.

How do I initialize a TypeScript Object with a JSON-Object?

This is my approach (very simple):

const jsonObj: { [key: string]: any } = JSON.parse(jsonStr);

for (const key in jsonObj) {
  if (!jsonObj.hasOwnProperty(key)) {

  console.log(key); // Key
  console.log(jsonObj[key]); // Value
  // Your logic...

How do you add a Dictionary of items into another Dictionary

Swift 3:

extension Dictionary {

    mutating func merge(with dictionary: Dictionary) {
        dictionary.forEach { updateValue($1, forKey: $0) }

    func merged(with dictionary: Dictionary) -> Dictionary {
        var dict = self
        dict.merge(with: dictionary)
        return dict

let a = ["a":"b"]
let b = ["1":"2"]
let c = a.merged(with: b)

print(c) //["a": "b", "1": "2"]

Mongoose limit/offset and count query

    { '$match'    : { } },
    { '$sort'     : { '_id' : -1 } },
    { '$facet'    : {
        metadata: [ { $count: "total" } ],
        data: [ { $skip: 1 }, { $limit: 10 },{ '$project' : {"_id":0} } ] // add projection here wish you re-shape the docs
    } }
] )

Instead of using two queries to find the total count and skip the matched record.
$facet is the best and optimized way.

  1. Match the record
  2. Find total_count
  3. skip the record
  4. And also can reshape data according to our needs in the query.

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.


LaTeX output

How to VueJS router-link active style add attribute active-class="active" eg:

<ul class="nav navbar-nav">
    <router-link tag="li" active-class="active" to="/" exact><a>Home</a></router-link>
    <router-link tag="li" active-class="active" to="/about"><a>About</a></router-link>
    <router-link tag="li" active-class="active" to="/permission-list"><a>Permisison</a></router-link>

How to dump raw RTSP stream to file?

If you are reencoding in your ffmpeg command line, that may be the reason why it is CPU intensive. You need to simply copy the streams to the single container. Since I do not have your command line I cannot suggest a specific improvement here. Your acodec and vcodec should be set to copy is all I can say.

EDIT: On seeing your command line and given you have already tried it, this is for the benefit of others who come across the same question. The command:

ffmpeg -i rtsp://@ -acodec copy -vcodec copy c:/abc.mp4

will not do transcoding and dump the file for you in an mp4. Of course this is assuming the streamed contents are compatible with an mp4 (which in all probability they are).

Find and replace - Add carriage return OR Newline

You can also try \x0d\x0a in the "Replace with" box with "Use regular Expression" box checked to get carriage return + line feed using Visual Studio Find/Replace. Using \n (line feed) is the same as \x0a

How can I list all collections in the MongoDB shell?

First you need to use a database to show all collection/tables inside it.

>show dbs
users 0.56787GB
test (empty)
> // this will give you all the function which can be used with this db
>use users
>show tables //will show all the collection in the db

can't start MySql in Mac OS 10.6 Snow Leopard

Have you considered installing MacPorts 1.8.0 (release candidate), and keeping MySQL up-to-date that way? That will build MySQL for the architecture and OS that you're using, rather than installing a 10.5 version on 10.6.

How to properly use jsPDF library

first, you have to create a handler.

var specialElementHandlers = {
    '#editor': function(element, renderer){
        return true;

then write this code in click event:

doc.fromHTML($('body').get(0), 15, 15, {
    'width': 170, 
    'elementHandlers': specialElementHandlers

var pdfOutput = doc.output();
            console.log(">>>"+pdfOutput );

assuming you've already declared doc variable. And Then you have save this pdf file using File-Plugin.

Check for a substring in a string in Oracle without LIKE

I'm guessing the reason you're asking is performance? There's the instr function. But that's likely to work pretty much the same behind the scenes.

Maybe you could look into full text search.

As last resorts you'd be looking at caching or precomputed columns/an indexed view.

Jquery, Clear / Empty all contents of tbody element?




    <tbody id="tbodyid">

Works for me

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

Just in case, someone out there having same issue but changing file permission doesn't solve the issue, add this line to your file

// other config goes here . . . 
$cfg['CheckConfigurationPermissions'] = false;

And you're good to go.

In my case, I'm using windows 10 WSL with phpmyadmin installed on D: drive. There's no way to (for now) change file permission on local disk through WSL unless your installation directory is inside WSL filesystem it-self. There's updates according to this issue, but still on insider build.


Character reading from file in Python

Not sure about the (errors="ignore") option but it seems to work for files with strange Unicode characters.

with open(fName, "rb") as fData:
    lines =
    lines = [line.decode("utf-8", errors="ignore") for line in lines]

How to open warning/information/error dialog in Swing?

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ErrorDialog {

  public static void main(String argv[]) {
    String message = "\"The Comedy of Errors\"\n"
        + "is considered by many scholars to be\n"
        + "the first play Shakespeare wrote";
    JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",

Error: [$injector:unpr] Unknown provider: $routeProvider

It looks like you forgot to include the ngRoute module in your dependency for myApp.

In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.

'use strict';

angular.module('myApp', ['ngRoute']).
    config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});

Getting one value from a tuple


Single elements of a tuple a can be accessed -in an indexed array-like fashion-

via a[0], a[1], ... depending on the number of elements in the tuple.


If your tuple is a=(3,"a")

  • a[0] yields 3,
  • a[1] yields "a"

Concrete answer to question

def tup():
  return (3, "hello")

tup() returns a 2-tuple.

In order to "solve"

i = 5 + tup()  # I want to add just the three

you select the 3 by

tup()[0|    #first element

so in total

i = 5 + tup()[0]


Go with namedtuple that allows you to access tuple elements by name (and by index). Details at

>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
>>> m.mynumber
>>> m[1]
>>> m.mystring

Redirect to an external URL from controller action in Spring MVC

You can do it with two ways.


@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public void method(HttpServletResponse httpServletResponse) {
    httpServletResponse.setHeader("Location", projectUrl);


@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView method() {
    return new ModelAndView("redirect:" + projectUrl);

Center the content inside a column in Bootstrap 4

2020 : Similar Issue

If your content is a set of buttons that you want to center on a page, then wrap them in a row and use justify-content-center.

Sample code below:

<div class="row justify-content-center">

    <button>Action A</button>
    <button>Action B</button>
    <button>Action C</button> 


How can I rename a field for all documents in MongoDB?

If ever you need to do the same thing with mongoid:

Model.all.rename(:old_field, :new_field)


There is change in the syntax in monogoid 4.0.0:

Model.all.rename(old_field: :new_field)

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

I know this is an old question, but I wanted to make sure a couple of other options are noted.

Since you can't store a TimeSpan greater than 24 hours in a time sql datatype field; a couple of other options might be.

  1. Use a varchar(xx) to store the ToString of the TimeSpan. The benefit of this is the precision doesn't have to be baked into the datatype or the calculation, (seconds vs milliseconds vs days vs fortnights) All you need to to is use TimeSpan.Parse/TryParse. This is what I would do.

  2. Use a second date, datetime or datetimeoffset, that stores the result of first date + timespan. Reading from the db is a matter of TimeSpan x = SecondDate - FirstDate. Using this option will protect you for other non .NET data access libraries access the same data but not understanding TimeSpans; in case you have such an environment.

Is there a way to follow redirects with command line cURL?

As said, to follow redirects you can use the flag -L or --location:

curl -L

But, if you want limit the number of redirects, add the parameter --max-redirs

--max-redirs <num>

Set maximum number of redirection-followings allowed. If -L, --location is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.

How to overcome "datetime.datetime not JSON serializable"?

I have an application with a similar issue; my approach was to JSONize the datetime value as a 6-item list (year, month, day, hour, minutes, seconds); you could go to microseconds as a 7-item list, but I had no need to:

class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            encoded_object = list(obj.timetuple())[0:6]
            encoded_object =json.JSONEncoder.default(self, obj)
        return encoded_object

sample = {}
sample['title'] = "String"
sample['somedate'] =

print sample
print json.dumps(sample, cls=DateTimeEncoder)


{'somedate': datetime.datetime(2013, 8, 1, 16, 22, 45, 890000), 'title': 'String'}
{"somedate": [2013, 8, 1, 16, 22, 45], "title": "String"}

Do while loop in SQL Server 2008

If you are not very offended by the GOTO keyword, it can be used to simulate a DO / WHILE in T-SQL. Consider the following rather nonsensical example written in pseudocode:

 SET I=I+1

Here is the equivalent T-SQL code using goto:

START:                -- DO
  SET @I+=1;
IF @I<=10 GOTO START; -- WHILE @I<=10

Notice the one to one mapping between the GOTO enabled solution and the original DO / WHILE pseudocode. A similar implementation using a WHILE loop would look like:

WHILE (1=1)              -- DO
  SET @I+=1;
  IF NOT (@I<=10) BREAK; -- WHILE @I<=10

Now, you could of course rewrite this particular example as a simple WHILE loop, since this is not such a good candidate for a DO / WHILE construct. The emphasis was on example brevity rather than applicability, since legitimate cases requiring a DO / WHILE are rare.

REPEAT / UNTIL, anyone (does NOT work in T-SQL)?

  SET I=I+1

... and the GOTO based solution in T-SQL:

START:                    -- REPEAT
  SET @I+=1;

Through creative use of GOTO and logic inversion via the NOT keyword, there is a very close relationship between the original pseudocode and the GOTO based solution. A similar solution using a WHILE loop looks like:

WHILE (1=1)       -- REPEAT
  SET @I+=1;
  IF @I>10 BREAK; -- UNTIL @I>10

An argument can be made that for the case of the REPEAT / UNTIL, the WHILE based solution is simpler, because the if condition is not inverted. On the other hand it is also more verbose.

If it wasn't for all of the disdain around the use of GOTO, these might even be idiomatic solutions for those few times when these particular (evil) looping constructs are necessary in T-SQL code for the sake of clarity.

Use these at your own discretion, trying not to suffer the wrath of your fellow developers when they catch you using the much maligned GOTO.

How to get all the AD groups for a particular user?

This is how I list all the groups (direct and indirect) for a specific Distinguished Name:

The string 1.2.840.113556.1.4.1941 specifies LDAP_MATCHING_RULE_IN_CHAIN.

This rule is limited to filters that apply to the DN. This is a special "extended" match operator that walks the chain of ancestry in objects all the way to the root until it finds a match.

This method is 25 times faster than the UserPrincipal.GetGroups() method in my testing.

Note: The primary group (typically Domain Users) is not returned by this or GetGroups() method. To get the primary group name too, I've confirmed this method works.

Additionally, I found this list of LDAP filters extremely useful.

private IEnumerable<string> GetGroupsForDistinguishedName(DirectoryEntry domainDirectoryEntry, string distinguishedName)
    var groups = new List<string>();
    if (!string.IsNullOrEmpty(distinguishedName))
        var getGroupsFilterForDn = $"(&(objectCategory=group)(member:1.2.840.113556.1.4.1941:={distinguishedName}))";
        using (DirectorySearcher dirSearch = new DirectorySearcher(domainDirectoryEntry))
            dirSearch.Filter = getGroupsFilterForDn;

            using (var results = dirSearch.FindAll())
                foreach (SearchResult result in results)
                    if (result.Properties.Contains("name"))

    return groups;

How to generate javadoc comments in Android Studio

I'm not sure I completely understand the question, but a list of keyboard short cuts can be found here - Hope this helps!

Angularjs dynamic ng-pattern validation

Sets pattern validation error key if the ngModel $viewValue does not match a RegExp found by evaluating the Angular expression given in the attribute value. If the expression evaluates to a RegExp object, then this is used directly. If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters.

It seems that a most voted answer in this question should be updated, because when i try it, it does not apply test function and validation not working.

Example from Angular docs works good for me:

Modifying built-in validators


<form name="form" class="css-form" novalidate>
   Overwritten Email:
   <input type="email" ng-model="myEmail" overwrite-email name="overwrittenEmail" />
   <span ng-show="form.overwrittenEmail.$">This email format is invalid!</span><br>
   Model: {{myEmail}}


var app = angular.module('form-example-modify-validators', []);

app.directive('overwriteEmail', function() {
    var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i;

    return {
        require: 'ngModel',
        restrict: '',
        link: function(scope, elm, attrs, ctrl) {
            // only apply the validator if ngModel is present and Angular has added the email validator
            if (ctrl && ctrl.$ {

                // this will overwrite the default Angular email validator
                ctrl.$ = function(modelValue) {
                    return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);


What's the best practice for primary keys in tables?

A natural key, if available, is usually best. So, if datetime/char uniquely identifies the row and both parts are meaningful to the row, that's great.

If just the datetime is meaningful, and the char is just tacked on to make it unique, then you might as well just go with an identify field.

Get and set position with jQuery .offset()

I recommend another option. jQuery UI has a new position feature that allows you to position elements relative to each other. For complete documentation and demo see:

Here's one way to position your elements using the position feature:

var options = {
    "my": "top left",
    "at": "top left",
    "of": ".layer1"

How to combine multiple inline style objects?

To take this one even further, you could create a classnames-like helper function:

const styleRules = (...rules) => {
  return rules.filter(Boolean).reduce((result, rule) => {
    return { ...result, ...rule };
  }, {});

And then use it conditionally in your components:

<div style={

    (window.innerWidth >= 768) && divStyleMd,
    (window.innerWidth < 768) && divStyleSm

}>Hello World!</div>

file_get_contents() Breaks Up UTF-8 Characters

Exemple :

$string = file_get_contents(".../File.txt");
$string = mb_convert_encoding($string, 'UTF-8', "ISO-8859-1");
echo $string;

Initialization of an ArrayList in one line

With Guava you can write:

ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");

In Guava there are also other useful static constructors. You can read about them here.

Setting up maven dependency for SQL Server

Download the driver JAR from the link provided by Olaf and add it to your local Maven repository with;

mvn install:install-file -Dfile=sqljdbc4.jar -DartifactId=sqljdbc4 -Dversion=4.0 -Dpackaging=jar

Then add it to your project with;


How can I get new selection in "select" in Angular 2?

From angular 7 and up, since ngModel is deprecated, we can simply use the control to get the new selected value very easily in a reactive way.


<form [formGroup]="frmMyForm">
  <select class="form-control" formControlName="fieldCtrl">
    <option value=""></option>
    <option value="val1">label val 1</option>
    <option value="val2">label val 2</option>
    <option value="val3">label val 3</option>
this.frmMyForm.get('fieldCtrl').valueChanges.subscribe( value => {
  this.selectedValue = value;

By using this fully reactive way, we can upgrade older angular application version to newer ones more easily.

Capturing a single image from my webcam in Java or Python

On windows it is easy to interact with your webcam with pygame:

from VideoCapture import Device
cam = Device()

I haven't tried using pygame on linux (all my linux boxen are servers without X), but this link might be helpful

Convert a python UTC datetime to a local datetime using only python standard library?

Building on Alexei's comment. This should work for DST too.

import time
import datetime

def utc_to_local(dt):
    if time.localtime().tm_isdst:
        return dt - datetime.timedelta(seconds = time.altzone)
        return dt - datetime.timedelta(seconds = time.timezone)

placeholder for select tag

   <option disabled selected>select your beverage</option>
   <option >Tea</option>

What is a callback?

A callback is a function that will be called when a process is done executing a specific task.

The usage of a callback is usually in asynchronous logic.

To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegate or the new lambda semantic Func or Action.

    public delegate void WorkCompletedCallBack(string result);

    public void DoWork(WorkCompletedCallBack callback)
        callback("Hello world");

    public void Test()
        WorkCompletedCallBack callback = TestCallBack; // Notice that I am referencing a method without its parameter

    public void TestCallBack(string result)

In today C#, this could be done using lambda like:

    public void DoWork(Action<string> callback)
        callback("Hello world");

    public void Test()
        DoWork((result) => Console.WriteLine(result));

HTML <input type='file'> File Selection Event

Listen to the change event.

input.onchange = function(e) { 

cancelling a handler.postdelayed process

Hope this gist help

MainActivity as Screen Launcher with handler & runnable function, the Runnable run to login page or feed page with base preference login user with firebase.