Programs & Examples On #Plot

The graphical representation of a mathematical function or a set of data. There are different kinds of plots, such as line plots, bar plots, or scatter plots.

How to plot all the columns of a data frame in R

I don't have R on this computer, but here is a crack at it. You can use par to display multiple plots in a window, or like this to prompt for a click before displaying the next page.

plotfun <- function(col) 
  plot(data[ , col], ylab = names(data[col]), type = "l")
par(ask = TRUE)
sapply(seq(1, length(data), 1), plotfun)

Plot smooth line with PyPlot

See the scipy.interpolate documentation for some examples.

The following example demonstrates its use, for linear and cubic spline interpolation:

>>> from scipy.interpolate import interp1d

>>> x = np.linspace(0, 10, num=11, endpoint=True)
>>> y = np.cos(-x**2/9.0)
>>> f = interp1d(x, y)
>>> f2 = interp1d(x, y, kind='cubic')

>>> xnew = np.linspace(0, 10, num=41, endpoint=True)
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
>>> plt.legend(['data', 'linear', 'cubic'], loc='best')
>>> plt.show()

enter image description here

Hiding axis text in matplotlib plots

One trick could be setting the color of tick labels as white to hide it!

plt.xticks(color='w')
plt.yticks(color='w')

or to be more generalized (@Armin Okic), you can set it as "None".

Python how to plot graph sine wave

import matplotlib.pyplot as plt # For ploting
import numpy as np # to work with numerical data efficiently

fs = 100 # sample rate 
f = 2 # the frequency of the signal

x = np.arange(fs) # the points on the x axis for plotting
# compute the value (amplitude) of the sin wave at the for each sample
y = np.sin(2*np.pi*f * (x/fs)) 

#this instruction can only be used with IPython Notbook. 
% matplotlib inline
# showing the exact location of the smaples
plt.stem(x,y, 'r', )
plt.plot(x,y)

enter image description here

How to plot ROC curve in Python

Here are two ways you may try, assuming your model is an sklearn predictor:

import sklearn.metrics as metrics
# calculate the fpr and tpr for all thresholds of the classification
probs = model.predict_proba(X_test)
preds = probs[:,1]
fpr, tpr, threshold = metrics.roc_curve(y_test, preds)
roc_auc = metrics.auc(fpr, tpr)

# method I: plt
import matplotlib.pyplot as plt
plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)
plt.legend(loc = 'lower right')
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()

# method II: ggplot
from ggplot import *
df = pd.DataFrame(dict(fpr = fpr, tpr = tpr))
ggplot(df, aes(x = 'fpr', y = 'tpr')) + geom_line() + geom_abline(linetype = 'dashed')

or try

ggplot(df, aes(x = 'fpr', ymin = 0, ymax = 'tpr')) + geom_line(aes(y = 'tpr')) + geom_area(alpha = 0.2) + ggtitle("ROC Curve w/ AUC = %s" % str(roc_auc)) 

Simple line plots using seaborn

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

import seaborn as sns

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

sns.tsplot(data, time)

enter image description here

Adjust plot title (main) position

We can use title() function with negative line value to bring down the title.

See this example:

plot(1, 1)
title("Title", line = -2)

enter image description here

multiple plot in one figure in Python

The OP states that each plot element overwrites the previous one rather than being combined into a single plot. This can happen even with one of the many suggestions made by other answers. If you select several lines and run them together, say:

plt.plot(<X>, <Y>)
plt.plot(<X>, <Z>)

the plot elements will typically be rendered together, one layer on top of the other. But if you execute the code line-by-line, each plot will overwrite the previous one.

This perhaps is what happened to the OP. It just happened to me: I had set up a new key binding to execute code by a single key press (on spyder), but my key binding was executing only the current line. The solution was to select lines by whole blocks or to run the whole file.

Subscripts in plots in R

See ?expression

plot(1:10,main=expression("This is a subscript "[2]))

enter image description here

How to plot a function curve in R

You mean like this?

> eq = function(x){x*x}
> plot(eq(1:1000), type='l')

Plot of eq over range 1:1000

(Or whatever range of values is relevant to your function)

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

Changing plot scale by a factor in matplotlib

Instead of changing the ticks, why not change the units instead? Make a separate array X of x-values whose units are in nm. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel to indicate the units (which should always be done anyways).

from pylab import *

# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)

# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X

subplot(121)
scatter(X,Y)
xlim(epsilon,50*epsilon)
xlabel("meters")

subplot(122)
scatter(X2,Y)
xlim(1, 50)
xlabel("nanometers")

show()

enter image description here

Add error bars to show standard deviation on a plot in R

A solution with ggplot2 :

qplot(x,y)+geom_errorbar(aes(x=x, ymin=y-sd, ymax=y+sd), width=0.25)

enter image description here

Error in plot.new() : figure margins too large, Scatter plot

Just a side-note. Sometimes this "margin" error occurs because you want to save a high-resolution figure (eg. dpi = 300 or res = 300) in R.
In this case, what you need to do is to specify the width and height. (Btw, ggsave() doesn't require this.)

This causes the margin error:

# eg. for tiff()
par(mar=c(1,1,1,1))
tiff(filename =  "qq.tiff",
     res = 300,                                                 # the margin error.
     compression = c( "lzw") )
# qq plot for genome wide association study (just an example)
qqman::qq(df$rawp, main = "Q-Q plot of GWAS p-values", cex = .3)
dev.off()

This will fix the margin error:

# eg. for tiff()
par(mar=c(1,1,1,1))
tiff(filename =  "qq.tiff",
     res = 300,                                                 # the margin error.
     width = 5, height = 4, units = 'in',                       # fixed
     compression = c( "lzw") )
# qq plot for genome wide association study (just an example)
qqman::qq(df$rawp, main = "Q-Q plot of GWAS p-values", cex = .3)
dev.off()

Moving x-axis to the top of a plot in matplotlib

You've got to do some extra massaging if you want the ticks (not labels) to show up on the top and bottom (not just the top). The only way I could do this is with a minor change to unutbu's code:

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.xaxis.set_ticks_position('both') # THIS IS THE ONLY CHANGE

ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()

Output:

enter image description here

How do you plot bar charts in gnuplot?

I recommend Derek Bruening's bar graph generator Perl script. Available at http://www.burningcutlery.com/derek/bargraph/

Remove plot axis values

Using base graphics, the standard way to do this is to use axes=FALSE, then create your own axes using Axis (or axis). For example,

x <- 1:20
y <- runif(20)
plot(x, y, axes=FALSE, frame.plot=TRUE)
Axis(side=1, labels=FALSE)
Axis(side=2, labels=FALSE)

The lattice equivalent is

library(lattice)
xyplot(y ~ x, scales=list(alternating=0))

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Label points in geom_point

Use geom_text , with aes label. You can play with hjust, vjust to adjust text position.

ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
  geom_point() +geom_text(aes(label=Name),hjust=0, vjust=0)

enter image description here

EDIT: Label only values above a certain threshold:

  ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
  geom_point() +
  geom_text(aes(label=ifelse(PTS>24,as.character(Name),'')),hjust=0,vjust=0)

chart with conditional labels

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

Format y axis as percent

For those who are looking for the quick one-liner:

plt.gca().set_yticklabels(['{:.0f}%'.format(x*100) for x in plt.gca().get_yticks()]) 

Or if you are using Latex as the axis text formatter, you have to add one backslash '\'

plt.gca().set_yticklabels(['{:.0f}\%'.format(x*100) for x in plt.gca().get_yticks()]) 

Force the origin to start at 0

In the latest version of ggplot2, this can be more easy.

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))

enter image description here

See ?expansion() for more details.

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

Save plot to image file instead of displaying it using Matplotlib

As others have said, plt.savefig() or fig1.savefig() is indeed the way to save an image.

However I've found that in certain cases the figure is always shown. (eg. with Spyder having plt.ion(): interactive mode = On.) I work around this by forcing the closing of the figure window in my giant loop with plt.close(figure_object) (see documentation), so I don't have a million open figures during the loop:

import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png')   # save the figure to file
plt.close(fig)    # close the figure window

You should be able to re-open the figure later if needed to with fig.show() (didn't test myself).

Plotting in a non-blocking way with Matplotlib

Iggy's answer was the easiest for me to follow, but I got the following error when doing a subsequent subplot command that was not there when I was just doing show:

MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

In order to avoid this error, it helps to close (or clear) the plot after the user hits enter.

Here's the code that worked for me:

def plt_show():
    '''Text-blocking version of plt.show()
    Use this instead of plt.show()'''
    plt.draw()
    plt.pause(0.001)
    input("Press enter to continue...")
    plt.close()

matplotlib get ylim values

I put above-mentioned methods together using ax instead of plt

import numpy as np
import matplotlib.pyplot as plt

x = range(100)
y = x

fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
ax.plot(x, y);

# method 1
print(ax.get_xlim())
print(ax.get_xlim())
# method 2
print(ax.axis())

enter image description here

Plotting multiple lines, in different colors, with pandas dataframe

You could use groupby to split the DataFrame into subgroups according to the color:

for key, grp in df.groupby(['color']):

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

df = pd.read_table('data', sep='\s+')
fig, ax = plt.subplots()

for key, grp in df.groupby(['color']):
    ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key, label=key)

plt.legend(loc='best')
plt.show()

yields enter image description here

Plotting multiple time series on the same plot using ggplot()

I prefer using the ggfortify library. It is a ggplot2 wrapper that recognizes the type of object inside the autoplot function and chooses the best ggplot methods to plot. At least I don't have to remember the syntax of ggplot2.

library(ggfortify)
ts1 <- 1:100
ts2 <- 1:100*0.8
autoplot(ts( cbind(ts1, ts2)  , start = c(2010,5), frequency = 12 ),
         facets = FALSE)

Plot

How can I plot data with confidence intervals?

Some addition to the previous answers. It is nice to regulate the density of the polygon to avoid obscuring the data points.

library(MASS)
attach(Boston)
lm.fit2 = lm(medv~poly(lstat,2))
plot(lstat,medv)
new.lstat = seq(min(lstat), max(lstat), length.out=100)
preds <- predict(lm.fit2, newdata = data.frame(lstat=new.lstat), interval = 'prediction')
lines(sort(lstat), fitted(lm.fit2)[order(lstat)], col='red', lwd=3) 
polygon(c(rev(new.lstat), new.lstat), c(rev(preds[ ,3]), preds[ ,2]), density=10, col = 'blue', border = NA)
lines(new.lstat, preds[ ,3], lty = 'dashed', col = 'red')
lines(new.lstat, preds[ ,2], lty = 'dashed', col = 'red')

drawing of the prediction interval in polynomial regression

Please note that you see the prediction interval on the picture, which is several times wider than the confidence interval. You can read here the detailed explanation of those two types of interval estimates.

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.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# 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

Code for best fit straight line of a scatter plot in python

You can use numpy's polyfit. I use the following (you can safely remove the bit about coefficient of determination and error bounds, I just think it looks nice):

#!/usr/bin/python3

import numpy as np
import matplotlib.pyplot as plt
import csv

with open("example.csv", "r") as f:
    data = [row for row in csv.reader(f)]
    xd = [float(row[0]) for row in data]
    yd = [float(row[1]) for row in data]

# sort the data
reorder = sorted(range(len(xd)), key = lambda ii: xd[ii])
xd = [xd[ii] for ii in reorder]
yd = [yd[ii] for ii in reorder]

# make the scatter plot
plt.scatter(xd, yd, s=30, alpha=0.15, marker='o')

# determine best fit line
par = np.polyfit(xd, yd, 1, full=True)

slope=par[0][0]
intercept=par[0][1]
xl = [min(xd), max(xd)]
yl = [slope*xx + intercept  for xx in xl]

# coefficient of determination, plot text
variance = np.var(yd)
residuals = np.var([(slope*xx + intercept - yy)  for xx,yy in zip(xd,yd)])
Rsqr = np.round(1-residuals/variance, decimals=2)
plt.text(.9*max(xd)+.1*min(xd),.9*max(yd)+.1*min(yd),'$R^2 = %0.2f$'% Rsqr, fontsize=30)

plt.xlabel("X Description")
plt.ylabel("Y Description")

# error bounds
yerr = [abs(slope*xx + intercept - yy)  for xx,yy in zip(xd,yd)]
par = np.polyfit(xd, yerr, 2, full=True)

yerrUpper = [(xx*slope+intercept)+(par[0][0]*xx**2 + par[0][1]*xx + par[0][2]) for xx,yy in zip(xd,yd)]
yerrLower = [(xx*slope+intercept)-(par[0][0]*xx**2 + par[0][1]*xx + par[0][2]) for xx,yy in zip(xd,yd)]

plt.plot(xl, yl, '-r')
plt.plot(xd, yerrLower, '--r')
plt.plot(xd, yerrUpper, '--r')
plt.show()

3D Plotting from X, Y, Z Data, Excel or other Tools

I ended up using matplotlib :)

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
x = [1000,1000,1000,1000,1000,5000,5000,5000,5000,5000,10000,10000,10000,10000,10000]
y = [13,21,29,37,45,13,21,29,37,45,13,21,29,37,45]
z = [75.2,79.21,80.02,81.2,81.62,84.79,87.38,87.9,88.54,88.56,88.34,89.66,90.11,90.79,90.87]
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2)
plt.show()

Remove xticks in a matplotlib plot?

This snippet might help in removing the xticks only.

from matplotlib import pyplot as plt    
plt.xticks([])

This snippet might help in removing the xticks and yticks both.

from matplotlib import pyplot as plt    
plt.xticks([]),plt.yticks([])

How can I make a "color map" plot in matlab?

Note that both pcolor and "surf + view(2)" do not show the last row and the last column of your 2D data.

On the other hand, using imagesc, you have to be careful with the axes. The surf and the imagesc examples in gevang's answer only (almost -- apart from the last row and column) correspond to each other because the 2D sinc function is symmetric.

To illustrate these 2 points, I produced the figure below with the following code:

[x, y] = meshgrid(1:10,1:5);
z      = x.^3 + y.^3;

subplot(3,1,1)
imagesc(flipud(z)), axis equal tight, colorbar
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc')

subplot(3,1,2)
surf(x,y,z,'EdgeColor','None'), view(2), axis equal tight, colorbar
title('surf with view(2)')

subplot(3,1,3)
imagesc(flipud(z)), axis equal tight, colorbar
axis([0.5 9.5 1.5 5.5])
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc cropped')

colormap jet

surf vs imagesc

As you can see the 10th row and 5th column are missing in the surf plot. (You can also see this in images in the other answers.)

Note how you can use the "set(gca, 'YTick'..." (and Xtick) command to set the x and y tick labels properly if x and y are not 1:1:N.

Also note that imagesc only makes sense if your z data correspond to xs and ys are (each) equally spaced. If not you can use surf (and possibly duplicate the last column and row and one more "(end,end)" value -- although that's a kind of a dirty approach).

matplotlib savefig() plots different from show()

savefig specifies the DPI for the saved figure (The default is 100 if it's not specified in your .matplotlibrc, have a look at the dpi kwarg to savefig). It doesn't inheret it from the DPI of the original figure.

The DPI affects the relative size of the text and width of the stroke on lines, etc. If you want things to look identical, then pass fig.dpi to fig.savefig.

E.g.

import matplotlib.pyplot as plt

fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', dpi=fig.dpi)

How to plot a 2D FFT in Matlab?

Assuming that I is your input image and F is its Fourier Transform (i.e. F = fft2(I))

You can use this code:

F = fftshift(F); % Center FFT

F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1

imshow(F,[]); % Display the result

How to adjust the size of y axis labels only in R?

As the title suggests that we want to adjust the size of the labels and not the tick marks I figured that I actually might add something to the question, you need to use the mtext() if you want to specify one of the label sizes, or you can just use par(cex.lab=2) as a simple alternative. Here's a more advanced mtext() example:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data=foo,
     yaxt="n", ylab="", 
     xlab="Regular boring x", 
     pch=16,
     col="darkblue")
axis(2,cex.axis=1.2)
mtext("Awesome Y variable", side=2, line=2.2, cex=2)

enter image description here

You may need to adjust the line= option to get the optimal positioning of the text but apart from that it's really easy to use.

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'])
plt.show() # 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 >.

Matplotlib scatterplot; colour as a function of a third variable

Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,

  • Plot points corresponding to Physical variable 'A' in RED.
  • Plot points corresponding to Physical variable 'B' in BLUE.
  • Plot points corresponding to Physical variable 'C' in GREEN.

In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.

x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]

# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
    cols=[]
    for l in lst:
        if l=='A':
            cols.append('red')
        elif l=='B':
            cols.append('blue')
        else:
            cols.append('green')
    return cols
# Create the colors list using the function above
cols=pltcolor(x)

plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()

Coloring scatter plot as a function of x variable

How to save a plot as image on the disk?

For the first question, I find dev.print to be the best when working interactively. First, you set up your plot visually and when you are happy with what you see, you can ask R to save the current plot to disk

dev.print(pdf, file="filename.pdf");

You can replace pdf with other formats such as png.

This will copy the image exactly as you see it on screen. The problem with dev.copy is that the image is often different and doesn't remember the window size and aspect ratio - it forces the plot to be square by default.

For the second question, (as others have already answered), you must direct the output to disk before you execute your plotting commands

pdf('filename.pdf')
plot( yourdata )
points (some_more_data)
dev.off() # to complete the writing process and return output to your monitor

Combining paste() and expression() functions in plot labels

Use substitute instead.

labNames <- c('xLab','yLab')
plot(c(1:10),
     xlab=substitute(paste(nn, x^2), list(nn=labNames[1])),
     ylab=substitute(paste(nn, y^2), list(nn=labNames[2])))

Change background color of R plot

I use abline() with extremely wide vertical lines to fill the plot space:

abline(v = xpoints, col = "grey90", lwd = 80)

You have to create the frame, then the ablines, and then plot the points so they are visible on top. You can even use a second abline() statement to put thin white or black lines over the grey, if desired.

Example:

xpoints = 1:20
y = rnorm(20)
plot(NULL,ylim=c(-3,3),xlim=xpoints)
abline(v=xpoints,col="gray90",lwd=80)
abline(v=xpoints,col="white")
abline(h = 0, lty = 2) 
points(xpoints, y, pch = 16, cex = 1.2, col = "red")

Plotting with C#

gnuplot is an actively maintained program widely used in the scientific community. Normally plots are generated from data files which you can write out in your C# program, but it is also possible to call the gnuplot executable from C# and display the generated image in a C# picture box.

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

What does the error "arguments imply differing number of rows: x, y" mean?

Your data.frame mat is rectangular (n_rows!= n_cols).

Therefore, you cannot make a data.frame out of the column- and rownames, because each column in a data.frame must be the same length.

Maybe this suffices your needs:

require(reshape2)
mat$id <- rownames(mat) 
melt(mat)

Plot a bar using matplotlib using a dictionary

I often load the dict into a pandas DataFrame then use the plot function of the DataFrame.
Here is the one-liner:

pandas.DataFrame(D, index=['quantity']).plot(kind='bar')

resulting plot

Increase distance between text and title on the y-axis

From ggplot2 2.0.0 you can use the margin = argument of element_text() to change the distance between the axis title and the numbers. Set the values of the margin on top, right, bottom, and left side of the element.

ggplot(mpg, aes(cty, hwy)) + geom_point()+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))

margin can also be used for other element_text elements (see ?theme), such as axis.text.x, axis.text.y and title.

addition

in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top"), you'll need a different theme setting - e.g. axis.title.x.top. See https://github.com/tidyverse/ggplot2/issues/4343.

How to draw a standard normal distribution in R

I am pretty sure this is a duplicate. Anyway, have a look at the following piece of code

x <- seq(5, 15, length=1000)
y <- dnorm(x, mean=10, sd=3)
plot(x, y, type="l", lwd=1)

I'm sure you can work the rest out yourself, for the title you might want to look for something called main= and y-axis labels are also up to you.

If you want to see more of the tails of the distribution, why don't you try playing with the seq(5, 15, ) section? Finally, if you want to know more about what dnorm is doing I suggest you look here

Plot two graphs in same plot in R

You can also create your plot using ggvis:

library(ggvis)

x  <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x,1,1)
df <- data.frame(x, y1, y2)

df %>%
  ggvis(~x, ~y1, stroke := 'red') %>%
  layer_paths() %>%
  layer_paths(data = df, x = ~x, y = ~y2, stroke := 'blue')

This will create the following plot:

enter image description here

Excel plot time series frequency with continuous xaxis

I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog

Non-uniformly distributed data can be plotted in excel in

  • X Y (Scatter Plots)
  • Linear plots with Date axis
    • These don't take time into account, only days.
    • This method is quite cumbersome as it requires translating your time units to days, months, or years.. then change the axis labels... Not Recommended

Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.

1- Add the center point to your data series

+---------------+-------+------+
|    Time       | Time  | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 |  12  |
| 09:00 - 10:00 | 09:30 |  13  |
| 10:00 - 11:00 | 10:30 |  10  |
| 13:00 - 14:00 | 13:30 |   5  |
| 14:00 - 15:00 | 14:30 |  14  |
+---------------+-------+------+

2- Create a Scatter Plot

3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:

  • Minimum : Fix : 0.33333
  • Maximum : Fix : 0.625
  • Major unit : Fix : 0.041667

Line Scatter Plot


Alternative Display:

Make the points turn into columns:

To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.

1- You're going to need to add several rows where we draw the line and disjoint the data

+-------+------+
| Time  | Freq |
+-------+------+
| 08:30 |   0  |
| 08:30 |  12  |
|       |      |
| 09:30 |   0  |
| 09:30 |  13  |
|       |      |
| 10:30 |   0  |
| 10:30 |  10  |
|       |      |
| 13:30 |   0  |
| 13:30 |   5  |
|       |      |
| 14:30 |   0  |
| 14:30 |  14  |
+-------+------+

2- Plot an X Y (Scatter) Chart with Lines.

3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.

Bar-Line Scatter Plot

Finding moving average from data points in Python

There is a problem with the accepted answer. I think we need to use "valid" instead of "same" here - return numpy.convolve(interval, window, 'same') .

As an Example try out the MA of this data-set = [1,5,7,2,6,7,8,2,2,7,8,3,7,3,7,3,15,6] - the result should be [4.2,5.4,6.0,5.0,5.0,5.2,5.4,4.4,5.4,5.6,5.6,4.6,7.0,6.8], but having "same" gives us an incorrect output of [2.6,3.0,4.2,5.4,6.0,5.0,5.0,5.2,5.4,4.4,5.4,5.6,5.6, 4.6,7.0,6.8,6.2,4.8]

Rusty code to try this out -:

result=[]
dataset=[1,5,7,2,6,7,8,2,2,7,8,3,7,3,7,3,15,6]
window_size=5
for index in xrange(len(dataset)):
    if index <=len(dataset)-window_size :
        tmp=(dataset[index]+ dataset[index+1]+ dataset[index+2]+ dataset[index+3]+ dataset[index+4])/5.0
        result.append(tmp)
    else:
      pass

result==movingaverage(y, window_size) 

Try this with valid & same and see whether the math makes sense.

See also -: http://sentdex.com/sentiment-analysisbig-data-and-python-tutorials-algorithmic-trading/how-to-chart-stocks-and-forex-doing-your-own-financial-charting/calculate-simple-moving-average-sma-python/

How to combine 2 plots (ggplot) into one plot?

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +
      geom_smooth(size=1)

How to plot two histograms together in R?

So many great answers but since I've just written a function (plotMultipleHistograms() in 'basicPlotteR' package) function to do this, I thought I would add another answer.

The advantage of this function is that it automatically sets appropriate X and Y axis limits and defines a common set of bins that it uses across all the distributions.

Here's how to use it:

# Install the plotteR package
install.packages("devtools")
devtools::install_github("JosephCrispell/basicPlotteR")
library(basicPlotteR)

# Set the seed
set.seed(254534)

# Create random samples from a normal distribution
distributions <- list(rnorm(500, mean=5, sd=0.5), 
                      rnorm(500, mean=8, sd=5), 
                      rnorm(500, mean=20, sd=2))

# Plot overlapping histograms
plotMultipleHistograms(distributions, nBins=20, 
                       colours=c(rgb(1,0,0, 0.5), rgb(0,0,1, 0.5), rgb(0,1,0, 0.5)), 
                       las=1, main="Samples from normal distribution", xlab="Value")

enter image description here

The plotMultipleHistograms() function can take any number of distributions, and all the general plotting parameters should work with it (for example: las, main, etc.).

Boxplot in R showing the mean

I also think chart.Boxplot is the best option, it gives you the position of the mean but if you have a matrix with returns all you need is one line of code to get all the boxplots in one graph.

Here is a small ETF portfolio example.

library(zoo)
library(PerformanceAnalytics)
library(tseries)
library(xts)

VTI.prices = get.hist.quote(instrument = "VTI", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

VEU.prices = get.hist.quote(instrument = "VEU", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

VWO.prices = get.hist.quote(instrument = "VWO", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))


VNQ.prices = get.hist.quote(instrument = "VNQ", start= "2007-03-01", end="2013-03-01",
                       quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                       compression = "m", retclass = c("zoo"))

TLT.prices = get.hist.quote(instrument = "TLT", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

TIP.prices = get.hist.quote(instrument = "TIP", start= "2007-03-01", end="2013-03-01",
                         quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                         compression = "m", retclass = c("zoo"))

index(VTI.prices) = as.yearmon(index(VTI.prices))
index(VEU.prices) = as.yearmon(index(VEU.prices))
index(VWO.prices) = as.yearmon(index(VWO.prices))

index(VNQ.prices) = as.yearmon(index(VNQ.prices))
index(TLT.prices) = as.yearmon(index(TLT.prices))
index(TIP.prices) = as.yearmon(index(TIP.prices))

Prices.z=merge(VTI.prices, VEU.prices, VWO.prices, VNQ.prices, 
           TLT.prices, TIP.prices)

colnames(Prices.z) = c("VTI", "VEU", "VWO" , "VNQ", "TLT", "TIP")

returnscc.z = diff(log(Prices.z))

start(returnscc.z)
end(returnscc.z)
colnames(returnscc.z) 
head(returnscc.z)

Return Matrix

ret.mat = coredata(returnscc.z)
class(ret.mat)
colnames(ret.mat)
head(ret.mat)

Box Plot of Return Matrix

chart.Boxplot(returnscc.z, names=T, horizontal=TRUE, colorset="darkgreen", as.Tufte =F,
          mean.symbol = 20, median.symbol="|", main="Return Distributions Comparison",
          element.color = "darkgray", outlier.symbol = 20, 
          xlab="Continuously Compounded Returns", sort.ascending=F)

You can try changing the mean.symbol, and remove or change the median.symbol. Hope it helped. :)

Rotating x axis labels in R for barplot

Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:

par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels

#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"

end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)

barplot(mtcars$qsec, col = "grey50", 
        main = "",
        ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
        xlab = "",
        space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25, 
     srt = 60, adj = 1, xpd = TRUE,
     labels = paste(rownames(mtcars)), cex = 0.65)

enter image description here

Plot multiple lines (data series) each with unique color in R

Using @Arun dummy data :) here a lattice solution :

xyplot(val~x,type=c('l','p'),groups= variable,data=df,auto.key=T)

enter image description here

Plot a legend outside of the plotting area in base graphics?

Recently I found very easy and interesting function to print legend outside of the plot area where you want.

Make the outer margin at the right side of the plot.

par(xpd=T, mar=par()$mar+c(0,0,0,5))

Create a plot

plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")

Add legend and just use locator(1) function as like below. Then you have to just click where you want after load following script.

legend(locator(1),c("group A", "group B"), pch = c(1,2), lty = c(1,2))

Try it

How to change legend title in ggplot

Just to add to the list (the other options here didn't work for me), you can also use the function update_labels for ggplot:

p <- ggplot(df, aes(x=rating, fill=cond)) + 
           geom_density(alpha=.3) + 
           xlab("NEW RATING TITLE") + 
           ylab("NEW DENSITY TITLE")
update_labels(p, list(colour="MY NEW LEGEND TITLE")

This will also allow you to change x- and y-axis labels, with separate lines:

update_labels(p, list(x="NEW X LABEL",y="NEW Y LABEL")

Changing the "tick frequency" on x or y axis in matplotlib?

This is an old topic, but I stumble over this every now and then and made this function. It's very convenient:

import matplotlib.pyplot as pp
import numpy as np

def resadjust(ax, xres=None, yres=None):
    """
    Send in an axis and I fix the resolution as desired.
    """

    if xres:
        start, stop = ax.get_xlim()
        ticks = np.arange(start, stop + xres, xres)
        ax.set_xticks(ticks)
    if yres:
        start, stop = ax.get_ylim()
        ticks = np.arange(start, stop + yres, yres)
        ax.set_yticks(ticks)

One caveat of controlling the ticks like this is that one does no longer enjoy the interactive automagic updating of max scale after an added line. Then do

gca().set_ylim(top=new_top) # for example

and run the resadjust function again.

How to plot a subset of a data frame in R?

with(dfr[dfr$var3 < 155,], plot(var1, var2)) should do the trick.

Edit regarding multiple conditions:

with(dfr[(dfr$var3 < 155) & (dfr$var4 > 27),], plot(var1, var2))

How to increase font size in a plot in R?

You want something like the cex=1.5 argument to scale fonts 150 percent. But do see help(par) as there are also cex.lab, cex.axis, ...

Colouring plot by factor in R

The lattice library is another good option. Here I've added a legend on the right side and jittered the points because some of them overlapped.

xyplot(Sepal.Width ~ Sepal.Length, group=Species, data=iris, 
       auto.key=list(space="right"), 
       jitter.x=TRUE, jitter.y=TRUE)

example plot

How can I plot with 2 different y-axes?

As its name suggests, twoord.plot() in the plotrix package plots with two ordinate axes.

library(plotrix)
example(twoord.plot)

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

Change the spacing of tick marks on the axis of a plot?

I just discovered the Hmisc package:

Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.

library(Hmisc)    
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th

MATLAB, Filling in the area between two sets of data, lines in one figure

You can accomplish this using the function FILL to create filled polygons under the sections of your plots. You will want to plot the lines and polygons in the order you want them to be stacked on the screen, starting with the bottom-most one. Here's an example with some sample data:

x = 1:100;             %# X range
y1 = rand(1,100)+1.5;  %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5;  %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2;        %# Baseline value for filling under the curves
index = 30:70;         %# Indices of points to fill under

plot(x,y1,'b');                              %# Plot the first line
hold on;                                     %# Add to the plot
h1 = fill(x(index([1 1:end end])),...        %# Plot the first filled polygon
          [baseLine y1(index) baseLine],...
          'b','EdgeColor','none');
plot(x,y2,'g');                              %# Plot the second line
h2 = fill(x(index([1 1:end end])),...        %# Plot the second filled polygon
          [baseLine y2(index) baseLine],...
          'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r');  %# Plot the red line

And here's the resulting figure:

enter image description here

You can also change the stacking order of the objects in the figure after you've plotted them by modifying the order of handles in the 'Children' property of the axes object. For example, this code reverses the stacking order, hiding the green polygon behind the blue polygon:

kids = get(gca,'Children');        %# Get the child object handles
set(gca,'Children',flipud(kids));  %# Set them to the reverse order

Finally, if you don't know exactly what order you want to stack your polygons ahead of time (i.e. either one could be the smaller polygon, which you probably want on top), then you could adjust the 'FaceAlpha' property so that one or both polygons will appear partially transparent and show the other beneath it. For example, the following will make the green polygon partially transparent:

set(h2,'FaceAlpha',0.5);

Is there a way to detach matplotlib plots so that the computation can continue?

IMPORTANT: Just to make something clear. I assume that the commands are inside a .py script and the script is called using e.g. python script.py from the console.

A simple way that works for me is:

  1. Use the block = False inside show : plt.show(block = False)
  2. Use another show() at the end of the .py script.

Example of script.py file:

plt.imshow(*something*)                                                               
plt.colorbar()                                                                             
plt.xlabel("true ")                                                                   
plt.ylabel("predicted ")                                                              
plt.title(" the matrix")  

# Add block = False                                           
plt.show(block = False)

################################
# OTHER CALCULATIONS AND CODE HERE ! ! !
################################

# the next command is the last line of my script
plt.show()

how to draw directed graphs using networkx in python?

Fully fleshed out example with arrows for only the red edges:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edges_from(
    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
                for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]

# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), 
                       node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()

Red edges

How to specify the actual x axis values to plot as x axis ticks in R

You'll find the answer to your question in the help page for ?axis.

Here is one of the help page examples, modified with your data:

Option 1: use xaxp to define the axis labels

plot(x,y, xaxt="n")
axis(1, xaxp=c(10, 200, 19), las=2)

Option 2: Use at and seq() to define the labels:

plot(x,y, xaxt="n")
axis(1, at = seq(10, 200, by = 10), las=2)

Both these options yield the same graphic:

enter image description here


PS. Since you have a large number of labels, you'll have to use additional arguments to get the text to fit in the plot. I use las to rotate the labels.

How to remove lines in a Matplotlib plot

I'm showing that a combination of lines.pop(0) l.remove() and del l does the trick.

from matplotlib import pyplot
import numpy, weakref
a = numpy.arange(int(1e3))
fig = pyplot.Figure()
ax  = fig.add_subplot(1, 1, 1)
lines = ax.plot(a)

l = lines.pop(0)
wl = weakref.ref(l)  # create a weak reference to see if references still exist
#                      to this object
print wl  # not dead
l.remove()
print wl  # not dead
del l
print wl  # dead  (remove either of the steps above and this is still live)

I checked your large dataset and the release of the memory is confirmed on the system monitor as well.

Of course the simpler way (when not trouble-shooting) would be to pop it from the list and call remove on the line object without creating a hard reference to it:

lines.pop(0).remove()

R: Plotting a 3D surface from x, y, z

You can use the function outer() to generate it.

Have a look at the demo for the function persp(), which is a base graphics function to draw perspective plots for surfaces.

Here is their first example:

x <- seq(-10, 10, length.out = 50)  
y <- x  
rotsinc <- function(x,y) {
    sinc <- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }  
    10 * sinc( sqrt(x^2+y^2) )  
}

z <- outer(x, y, rotsinc)  
persp(x, y, z)

The same applies to surface3d():

require(rgl)  
surface3d(x, y, z)

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

How do you change the size of figures drawn with matplotlib?

Use this:

plt.figure(figsize=(width,height))

The width and height are in inches.
If not provided, defaults to rcParams["figure.figsize"] = [6.4, 4.8]. See more here.

Error in plot.window(...) : need finite 'xlim' values

This error appears when the column contains character, if you check the data type it would be of type 'chr' converting the column to 'Factor' would solve this issue.

For e.g. In case you plot 'City' against 'Sales', you have to convert column 'City' to type 'Factor'

Error in plot.new() : figure margins too large in R

enter image description here

Just zoom this area if you use RStudio.

Modify the legend of pandas bar plot

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);

enter image description here

Another approach is to do the same by plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

enter image description here

What do hjust and vjust do when making a plot using ggplot?

The value of hjust and vjust are only defined between 0 and 1:

  • 0 means left-justified
  • 1 means right-justified

Source: ggplot2, Hadley Wickham, page 196

(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)

hjust controls horizontal justification and vjust controls vertical justification.

An example should make this clear:

td <- expand.grid(
    hjust=c(0, 0.5, 1),
    vjust=c(0, 0.5, 1),
    angle=c(0, 45, 90),
    text="text"
)

ggplot(td, aes(x=hjust, y=vjust)) + 
    geom_point() +
    geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) + 
    facet_grid(~angle) +
    scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
    scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))

enter image description here


To understand what happens when you change the hjust in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)

DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() + 
    ylab("Very long label for y") +
    theme(axis.title.y=element_text(angle=0))


p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")

library(ggExtra)
align.plots(p1, p2, p3)

enter image description here


To explore what happens with vjust aligment of axis labels:

DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) + 
        xlab("X-axis labels aligned with vjust=1")


library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

How to fit a smooth curve to my data in R?

The other answers are all good approaches. However, there are a few other options in R that haven't been mentioned, including lowess and approx, which may give better fits or faster performance.

The advantages are more easily demonstrated with an alternate dataset:

sigmoid <- function(x)
{
  y<-1/(1+exp(-.15*(x-100)))
  return(y)
}

dat<-data.frame(x=rnorm(5000)*30+100)
dat$y<-as.numeric(as.logical(round(sigmoid(dat$x)+rnorm(5000)*.3,0)))

Here is the data overlaid with the sigmoid curve that generated it:

Data

This sort of data is common when looking at a binary behavior among a population. For example, this might be a plot of whether or not a customer purchased something (a binary 1/0 on the y-axis) versus the amount of time they spent on the site (x-axis).

A large number of points are used to better demonstrate the performance differences of these functions.

Smooth, spline, and smooth.spline all produce gibberish on a dataset like this with any set of parameters I have tried, perhaps due to their tendency to map to every point, which does not work for noisy data.

The loess, lowess, and approx functions all produce usable results, although just barely for approx. This is the code for each using lightly optimized parameters:

loessFit <- loess(y~x, dat, span = 0.6)
loessFit <- data.frame(x=loessFit$x,y=loessFit$fitted)
loessFit <- loessFit[order(loessFit$x),]

approxFit <- approx(dat,n = 15)

lowessFit <-data.frame(lowess(dat,f = .6,iter=1))

And the results:

plot(dat,col='gray')
curve(sigmoid,0,200,add=TRUE,col='blue',)
lines(lowessFit,col='red')
lines(loessFit,col='green')
lines(approxFit,col='purple')
legend(150,.6,
       legend=c("Sigmoid","Loess","Lowess",'Approx'),
       lty=c(1,1),
       lwd=c(2.5,2.5),col=c("blue","green","red","purple"))

Fits

As you can see, lowess produces a near perfect fit to the original generating curve. Loess is close, but experiences a strange deviation at both tails.

Although your dataset will be very different, I have found that other datasets perform similarly, with both loess and lowess capable of producing good results. The differences become more significant when you look at benchmarks:

> microbenchmark::microbenchmark(loess(y~x, dat, span = 0.6),approx(dat,n = 20),lowess(dat,f = .6,iter=1),times=20)
Unit: milliseconds
                           expr        min         lq       mean     median        uq        max neval cld
  loess(y ~ x, dat, span = 0.6) 153.034810 154.450750 156.794257 156.004357 159.23183 163.117746    20   c
            approx(dat, n = 20)   1.297685   1.346773   1.689133   1.441823   1.86018   4.281735    20 a  
 lowess(dat, f = 0.6, iter = 1)   9.637583  10.085613  11.270911  11.350722  12.33046  12.495343    20  b 

Loess is extremely slow, taking 100x as long as approx. Lowess produces better results than approx, while still running fairly quickly (15x faster than loess).

Loess also becomes increasingly bogged down as the number of points increases, becoming unusable around 50,000.

EDIT: Additional research shows that loess gives better fits for certain datasets. If you are dealing with a small dataset or performance is not a consideration, try both functions and compare the results.

Plotting time in Python with Matplotlib

I had trouble with this using matplotlib version: 2.0.2. Running the example from above I got a centered stacked set of bubbles.

graph with centered stack of bubbles

I "fixed" the problem by adding another line:

plt.plot([],[])

The entire code snippet becomes:

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


# make up some data
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot([],[])
plt.scatter(x,y)

# beautify the x-labels
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)

plt.show()
plt.close()

This produces an image with the bubbles distributed as desired.

graph with bubbles distributed over time

How to create a new figure in MATLAB?

While doing "figure(1), figure(2),..." will solve the problem in most cases, it will not solve them in all cases. Suppose you have a bunch of MATLAB figures on your desktop and how many you have open varies from time to time before you run your code. Using the answers provided, you will overwrite these figures, which you may not want. The easy workaround is to just use the command "figure" before you plot.

Example: you have five figures on your desktop from a previous script you ran and you use

figure(1);
plot(...)

figure(2);
plot(...)

You just plotted over the figures on your desktop. However the code

figure;
plot(...)

figure;
plot(...)

just created figures 6 and 7 with your desired plots and left your previous plots 1-5 alone.

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    '''
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    '''
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

How to add title to subplots in Matplotlib?

ax.set_title() should set the titles for separate subplots:

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")
    ax.plot(data)

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")
    ax.plot(data)

    plt.show()

Can you check if this code works for you? Maybe something overwrites them later?

How to change the window title of a MATLAB plotting figure?

First you must create an empty figure with the following command.

figure('name','Title of the window here');

By doing this, the newly created figure becomes you active figure. Immediately after calling a plot() command, it will print your plotting onto this figure. So your window will have a title.

This is the code you must use:

figure('name','Title of the window here');

hold on

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [0; 0.198669; 0.389418; 0.564642; 0.717356; 0.841471; 0.932039; 0.98545; 0.999574; 0.973848; 0.909297; 0.808496; 0.675463; 0.515501; 0.334988; 0.14112; -0.0583741; -0.255541; -0.44252; -0.611858; -0.756802; -0.871576; -0.951602; -0.993691; -0.996165; -0.958924; -0.883455; -0.772764; -0.631267; -0.464602; -0.279415; -0.0830894; 0.116549; 0.311541; 0.494113; 0.656987; 0.793668; 0.898708; 0.96792; 0.998543; 0.989358; 0.940731; 0.854599; 0.734397; 0.584917; 0.412118; 0.22289; 0.0247754; -0.174327; -0.366479; -0.544021; -0.699875; -0.827826; -0.922775; -0.980936; -0.99999; -0.979178; -0.919329; -0.822829; -0.693525; -0.536573; -0.358229; -0.165604; 0.033623; 0.23151; 0.420167; 0.592074; 0.740376; 0.859162; 0.943696; 0.990607; 0.998027; 0.965658; 0.894791; 0.788252; 0.650288; 0.486399; 0.303118; 0.107754; -0.0919069; -0.287903; -0.472422; -0.638107; -0.778352; -0.887567; -0.961397; -0.9969; -0.992659; -0.948844; -0.867202; -0.750987; -0.604833; -0.434566; -0.246974; -0.0495356];
plot(x, y, '--b');

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [-1; -0.980133; -0.921324; -0.825918; -0.697718; -0.541836; -0.364485; -0.172736; 0.0257666; 0.223109; 0.411423; 0.583203; 0.731599; 0.850695; 0.935744; 0.983355; 0.991629; 0.960238; 0.890432; 0.784994; 0.648128; 0.48529; 0.302972; 0.108443; -0.0905427; -0.286052; -0.470289; -0.635911; -0.776314; -0.885901; -0.960303; -0.996554; -0.993208; -0.950399; -0.869833; -0.754723; -0.609658; -0.44042; -0.253757; -0.057111; 0.141679; 0.334688; 0.514221; 0.673121; 0.805052; 0.904756; 0.968256; 0.993023; 0.978068; 0.923987; 0.832937; 0.708548; 0.555778; 0.380717; 0.190346; -0.00774649; -0.205663; -0.395514; -0.56973; -0.721365; -0.844375; -0.933855; -0.986238; -0.999436; -0.972923; -0.907755; -0.806531; -0.673287; -0.513333; -0.333047; -0.139617; 0.0592467; 0.255615; 0.44166; 0.609964; 0.753818; 0.867487; 0.946439; 0.987526; 0.989111; 0.95113; 0.875097; 0.764044; 0.622398; 0.455806; 0.27091; 0.0750802; -0.123876; -0.318026; -0.499631; -0.66145; -0.797032; -0.900972; -0.969126; -0.998776];
plot(x, y, '-r');

hold off

title('My plot title');
xlabel('My x-axis title');
ylabel('My y-axis title');

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

In addition to the answers above, you can check the type of object using type(plt.subplots()) which returns a tuple, on the other hand, type(plt.subplot()) returns matplotlib.axes._subplots.AxesSubplot which you can't unpack.

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

Plotting a list of (x, y) coordinates in python matplotlib

As per this example:

import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y)
plt.show()

will produce:

enter image description here

To unpack your data from pairs into lists use zip:

x, y = zip(*li)

So, the one-liner:

plt.scatter(*zip(*li))

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I'm not sure of a way to do this in 3D, but in 2D you can use the compass command.

How to reset par(mfrow) in R

You can reset the plot by doing this:

dev.off()

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

Plotting multiple curves same graph and same scale

(The typical method would be to use plot just once to set up the limits, possibly to include the range of all series combined, and then to use points and lines to add the separate series.) To use plot multiple times with par(new=TRUE) you need to make sure that your first plot has a proper ylim to accept the all series (and in another situation, you may need to also use the same strategy for xlim):

# first plot
plot(x, y1, ylim=range(c(y1,y2)))

# second plot  EDIT: needs to have same ylim
par(new = TRUE)
plot(x, y2, ylim=range(c(y1,y2)), axes = FALSE, xlab = "", ylab = "")

enter image description here

This next code will do the task more compactly, by default you get numbers as points but the second one gives you typical R-type-"points":

  matplot(x, cbind(y1,y2))
  matplot(x, cbind(y1,y2), pch=1)

Plotting 4 curves in a single plot, with 3 y-axes

One possibility you can try is to create 3 axes stacked one on top of the other with the 'Color' properties of the top two set to 'none' so that all the plots are visible. You would have to adjust the axes width, position, and x-axis limits so that the 3 y axes are side-by-side instead of on top of one another. You would also want to remove the x-axis tick marks and labels from 2 of the axes since they will lie on top of one another.

Here's a general implementation that computes the proper positions for the axes and offsets for the x-axis limits to keep the plots lined up properly:

%# Some sample data:
x = 0:20;
N = numel(x);
y1 = rand(1,N);
y2 = 5.*rand(1,N)+5;
y3 = 50.*rand(1,N)-50;

%# Some initial computations:
axesPosition = [110 40 200 200];  %# Axes position, in pixels
yWidth = 30;                      %# y axes spacing, in pixels
xLimit = [min(x) max(x)];         %# Range of x values
xOffset = -yWidth*diff(xLimit)/axesPosition(3);

%# Create the figure and axes:
figure('Units','pixels','Position',[200 200 330 260]);
h1 = axes('Units','pixels','Position',axesPosition,...
          'Color','w','XColor','k','YColor','r',...
          'XLim',xLimit,'YLim',[0 1],'NextPlot','add');
h2 = axes('Units','pixels','Position',axesPosition+yWidth.*[-1 0 1 0],...
          'Color','none','XColor','k','YColor','m',...
          'XLim',xLimit+[xOffset 0],'YLim',[0 10],...
          'XTick',[],'XTickLabel',[],'NextPlot','add');
h3 = axes('Units','pixels','Position',axesPosition+yWidth.*[-2 0 2 0],...
          'Color','none','XColor','k','YColor','b',...
          'XLim',xLimit+[2*xOffset 0],'YLim',[-50 50],...
          'XTick',[],'XTickLabel',[],'NextPlot','add');
xlabel(h1,'time');
ylabel(h3,'values');

%# Plot the data:
plot(h1,x,y1,'r');
plot(h2,x,y2,'m');
plot(h3,x,y3,'b');

and here's the resulting figure:

enter image description here

Putting text in top left corner of matplotlib plot

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

enter image description here

Add missing dates to pandas dataframe

One issue is that reindex will fail if there are duplicate values. Say we're working with timestamped data, which we want to index by date:

df = pd.DataFrame({
    'timestamps': pd.to_datetime(
        ['2016-11-15 1:00','2016-11-16 2:00','2016-11-16 3:00','2016-11-18 4:00']),
    'values':['a','b','c','d']})
df.index = pd.DatetimeIndex(df['timestamps']).floor('D')
df

yields

            timestamps             values
2016-11-15  "2016-11-15 01:00:00"  a
2016-11-16  "2016-11-16 02:00:00"  b
2016-11-16  "2016-11-16 03:00:00"  c
2016-11-18  "2016-11-18 04:00:00"  d

Due to the duplicate 2016-11-16 date, an attempt to reindex:

all_days = pd.date_range(df.index.min(), df.index.max(), freq='D')
df.reindex(all_days)

fails with:

...
ValueError: cannot reindex from a duplicate axis

(by this it means the index has duplicates, not that it is itself a dup)

Instead, we can use .loc to look up entries for all dates in range:

df.loc[all_days]

yields

            timestamps             values
2016-11-15  "2016-11-15 01:00:00"  a
2016-11-16  "2016-11-16 02:00:00"  b
2016-11-16  "2016-11-16 03:00:00"  c
2016-11-17  NaN                    NaN
2016-11-18  "2016-11-18 04:00:00"  d

fillna can be used on the column series to fill blanks if needed.

Plot 3D data in R

I use the lattice package for almost everything I plot in R and it has a corresponing plot to persp called wireframe. Let data be the way Sven defined it.

wireframe(z ~ x * y, data=data)

wireframe plot

Or how about this (modification of fig 6.3 in Deepanyan Sarkar's book):

p <- wireframe(z ~ x * y, data=data)
npanel <- c(4, 2)
rotx <- c(-50, -80)
rotz <- seq(30, 300, length = npanel[1]+1)
update(p[rep(1, prod(npanel))], layout = npanel,
    panel = function(..., screen) {
        panel.wireframe(..., screen = list(z = rotz[current.column()],
                                           x = rotx[current.row()]))
    })

Multiple wireframe plots using panel and update

Update: Plotting surfaces with OpenGL

Since this post continues to draw attention I want to add the OpenGL way to make 3-d plots too (as suggested by @tucson below). First we need to reformat the dataset from xyz-tripplets to axis vectors x and y and a matrix z.

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(rgl)
persp3d(x, y, z, col="skyblue")

rgl::persp3d

This image can be freely rotated and scaled using the mouse, or modified with additional commands, and when you are happy with it you save it using rgl.snapshot.

rgl.snapshot("myplot.png")

Matplotlib different size subplots

Another way is to use the subplots function and pass the width ratio with gridspec_kw:

import numpy as np
import matplotlib.pyplot as plt 

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)

f.tight_layout()
f.savefig('grid_figure.pdf')

How do I tell matplotlib that I am done with a plot?

There is a clear figure command, and it should do it for you:

plt.clf()

If you have multiple subplots in the same figure

plt.cla()

clears the current axes.

When to use cla(), clf() or close() for clearing a plot in matplotlib?

plt.cla() means clear current axis

plt.clf() means clear current figure

also, there's plt.gca() (get current axis) and plt.gcf() (get current figure)

Read more here: Matplotlib, Pyplot, Pylab etc: What's the difference between these and when to use each?

Creating a Plot Window of a Particular Size

This will depend on the device you're using. If you're using a pdf device, you can do this:

pdf( "mygraph.pdf", width = 11, height = 8 )
plot( x, y )

You can then divide up the space in the pdf using the mfrow parameter like this:

par( mfrow = c(2,2) )

That makes a pdf with four panels available for plotting. Unfortunately, some of the devices take different units than others. For example, I think that X11 uses pixels, while I'm certain that pdf uses inches. If you'd just like to create several devices and plot different things to them, you can use dev.new(), dev.list(), and dev.next().

Other devices that might be useful include:

There's a list of all of the devices here.

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

You can add a custom legend documentation

first = [1, 2, 4, 5, 4]
second = [3, 4, 2, 2, 3]
plt.plot(first, 'g--', second, 'r--')
plt.legend(['First List', 'Second List'], loc='upper left')
plt.show()

enter image description here

How to download excel (.xls) file from API in postman?

You can Just save the response(pdf,doc etc..) by option on the right side of the response in postman check this image postman save response

For more Details check this

https://learning.getpostman.com/docs/postman/sending_api_requests/responses/

Accessing a local website from another computer inside the local network in IIS 7

Add two bindings to your website, one for local access and another for LAN access like so:

Open IIS and select your local website (that you want to access from your local network) from the left panel:

Connections > server (user-pc) > sites > local site

Open Bindings on the right panel under Actions tab add these bindings:

  1. Local:

    Type: http
    Ip Address: All Unassigned
    Port: 80
    Host name: samplesite.local
    
  2. LAN:

    Type: http
    Ip Address: <Network address of the hosting machine ex. 192.168.0.10>
    Port: 80
    Host name: <Leave it blank>
    

Voila, you should be able to access the website from any machine on your local network by using the host's LAN IP address (192.168.0.10 in the above example) as the site url.

NOTE:

if you want to access the website from LAN using a host name (like samplesite.local) instead of an ip address, add the host name to the hosts file on the local network machine (The hosts file can be found in "C:\Windows\System32\drivers\etc\hosts" in windows, or "/etc/hosts" in ubuntu):

192.168.0.10 samplesite.local

SQL select max(date) and corresponding value

There's no easy way to do this, but something like this will work:

SELECT ET.TrainingID, 
  ET.CompletedDate, 
  ET.Notes
FROM 
HR_EmployeeTrainings ET
inner join
(
  select TrainingID, Max(CompletedDate) as CompletedDate
  FROM HR_EmployeeTrainings
  WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
  GROUP BY AvantiRecID, TrainingID  
) ET2 
  on ET.TrainingID = ET2.TrainingID
  and ET.CompletedDate = ET2.CompletedDate

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

First you must test the query list size; here a example:

long count;
if (query.list().size() > 0)
    count=(long) criteria.list().get(0);   
else
    count=0;            
return count;

How to use systemctl in Ubuntu 14.04

Ubuntu 14 and lower does not have "systemctl" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot

Configure Docker to start on boot:

Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.

1) systemd (Ubuntu 16 and above):

$ sudo systemctl enable docker

To disable this behavior, use disable instead.

$ sudo systemctl disable docker

2) upstart (Ubuntu 14 and below):

Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:

$ echo manual | sudo tee /etc/init/docker.override
chkconfig

$ sudo chkconfig docker on

Done.

How can I get a Dialog style activity window to fill the screen?

For Dialog This may helpful for someone. I want a dialog to take full width of screen. searched a lot but nothing found useful. Finally this worked for me:

mDialog.setContentView(R.layout.my_custom_dialog);
mDialog.getWindow().setBackgroundDrawable(null);

after adding this, my dialog appears in full width of screen.

Eclipse: How do you change the highlight color of the currently selected method/expression?

For those working in Titanium Studio, the item is a little different: It's under the "Titanium Studio" Themes tab.

The color to change is the "Selection" one in the top right.

enter image description here

Clone an image in cv2 python

You can simply use Python standard library. Make a shallow copy of the original image as follows:

import copy

original_img = cv2.imread("foo.jpg")
clone_img = copy.copy(original_img)

When does socket.recv(recv_size) return?

It'll have the same behavior as the underlying recv libc call see the man page for an official description of behavior (or read a more general description of the sockets api).

Creating hard and soft links using PowerShell

I wrote a PowerShell module that has native wrappers for MKLINK. https://gist.github.com/2891103

Includes functions for:

  • New-Symlink
  • New-HardLink
  • New-Junction

Captures the MKLINK output and throws proper PowerShell errors when necessary.

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

Had the same error with PHP 7 on XAMPP and OSX.

The above mentioned answer in https://stackoverflow.com/ is good, but it did not completely solve the problem for me. I had to provide the complete certificate chain to make file_get_contents() work again. That's how I did it:

Get root / intermediate certificate

First of all I had to figure out what's the root and the intermediate certificate.

The most convenient way is maybe an online cert-tool like the ssl-shopper

There I found three certificates, one server-certificate and two chain-certificates (one is the root, the other one apparantly the intermediate).

All I need to do is just search the internet for both of them. In my case, this is the root:

thawte DV SSL SHA256 CA

And it leads to his url thawte.com. So I just put this cert into a textfile and did the same for the intermediate. Done.

Get the host certificate

Next thing I had to to is to download my server cert. On Linux or OS X it can be done with openssl:

openssl s_client -showcerts -connect whatsyoururl.de:443 </dev/null 2>/dev/null|openssl x509 -outform PEM > /tmp/whatsyoururl.de.cert

Now bring them all together

Now just merge all of them into one file. (Maybe it's good to just put them into one folder, I just merged them into one file). You can do it like this:

cat /tmp/thawteRoot.crt > /tmp/chain.crt
cat /tmp/thawteIntermediate.crt >> /tmp/chain.crt
cat /tmp/tmp/whatsyoururl.de.cert >> /tmp/chain.crt

tell PHP where to find the chain

There is this handy function openssl_get_cert_locations() that'll tell you, where PHP is looking for cert files. And there is this parameter, that will tell file_get_contents() where to look for cert files. Maybe both ways will work. I preferred the parameter way. (Compared to the solution mentioned above).

So this is now my PHP-Code

$arrContextOptions=array(
    "ssl"=>array(
        "cafile" => "/Applications/XAMPP/xamppfiles/share/openssl/certs/chain.pem",
        "verify_peer"=> true,
        "verify_peer_name"=> true,
    ),
);

$response = file_get_contents($myHttpsURL, 0, stream_context_create($arrContextOptions));

That's all. file_get_contents() is working again. Without CURL and hopefully without security flaws.

Send value of submit button when form gets posted

You can maintain your html as it is but use this php code

<?php
    $name = $_POST['name'];
    $purchase1 = $_POST['Tea'];
    $purchase2 =$_POST['Coffee'];
?>

Pandas conditional creation of a series/dataframe column

If you only have two choices to select from:

df['color'] = np.where(df['Set']=='Z', 'green', 'red')

For example,

import pandas as pd
import numpy as np

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print(df)

yields

  Set Type  color
0   Z    A  green
1   Z    B  green
2   X    B    red
3   Y    C    red

If you have more than two conditions then use np.select. For example, if you want color to be

  • yellow when (df['Set'] == 'Z') & (df['Type'] == 'A')
  • otherwise blue when (df['Set'] == 'Z') & (df['Type'] == 'B')
  • otherwise purple when (df['Type'] == 'B')
  • otherwise black,

then use

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
conditions = [
    (df['Set'] == 'Z') & (df['Type'] == 'A'),
    (df['Set'] == 'Z') & (df['Type'] == 'B'),
    (df['Type'] == 'B')]
choices = ['yellow', 'blue', 'purple']
df['color'] = np.select(conditions, choices, default='black')
print(df)

which yields

  Set Type   color
0   Z    A  yellow
1   Z    B    blue
2   X    B  purple
3   Y    C   black

Ignoring a class property in Entity Framework 4.1 Code First

You can use the NotMapped attribute data annotation to instruct Code-First to exclude a particular property

public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.


Edit : SEP 2017

Asp.NET Core(2.0)

Data annotation

If you are using asp.net core (2.0 at the time of this writing), The [NotMapped] attribute can be used on the property level.

public class Customer
{
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    [NotMapped]
    public int FullName { set; get; }
}

Fluent API

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Customer> Customers { get; set; }
}

What's wrong with nullable columns in composite primary keys?

Fundamentally speaking nothing is wrong with a NULL in a multi-column primary key. But having one has implications the designer likely did not intend, which is why many systems throw an error when you try this.

Consider the case of module/package versions stored as a series of fields:

CREATE TABLE module
  (name        varchar(20) PRIMARY KEY,
   description text DEFAULT '' NOT NULL);

CREATE TABLE version
  (module      varchar(20) REFERENCES module,
   major       integer NOT NULL,
   minor       integer DEFAULT 0 NOT NULL,
   patch       integer DEFAULT 0 NOT NULL,
   release     integer DEFAULT 1 NOT NULL,
   ext         varchar(20),
   notes       text DEFAULT '' NOT NULL,
   PRIMARY KEY (module, major, minor, patch, release, ext));

The first 5 elements of the primary key are regularly defined parts of a release version, but some packages have a customized extension that is usually not an integer (like "rc-foo" or "vanilla" or "beta" or whatever else someone for whom four fields is insufficient might dream up). If a package does not have an extension, then it is NULL in the above model, and no harm would be done by leaving things that way.

But what is a NULL? It is supposed to represent a lack of information, an unknown. That said, perhaps this makes more sense:

CREATE TABLE version
  (module      varchar(20) REFERENCES module,
   major       integer NOT NULL,
   minor       integer DEFAULT 0 NOT NULL,
   patch       integer DEFAULT 0 NOT NULL,
   release     integer DEFAULT 1 NOT NULL,
   ext         varchar(20) DEFAULT '' NOT NULL,
   notes       text DEFAULT '' NOT NULL,
   PRIMARY KEY (module, major, minor, patch, release, ext));

In this version the "ext" part of the tuple is NOT NULL but defaults to an empty string -- which is semantically (and practically) different from a NULL. A NULL is an unknown, whereas an empty string is a deliberate record of "something not being present". In other words, "empty" and "null" are different things. Its the difference between "I don't have a value here" and "I don't know what the value here is."

When you register a package that lacks a version extension you know it lacks an extension, so an empty string is actually the correct value. A NULL would only be correct if you didn't know whether it had an extension or not, or you knew that it did but didn't know what it was. This situation is easier to deal with in systems where string values are the norm, because there is no way to represent an "empty integer" other than inserting 0 or 1, which will wind up being rolled up in any comparisons made later (which has its own implications)*.

Incidentally, both ways are valid in Postgres (since we're discussing "enterprise" RDMBSs), but comparison results can vary quite a bit when you throw a NULL into the mix -- because NULL == "don't know" so all results of a comparison involving a NULL wind up being NULL since you can't know something that is unknown. DANGER! Think carefully about that: this means that NULL comparison results propagate through a series of comparisons. This can be a source of subtle bugs when sorting, comparing, etc.

Postgres assumes you're an adult and can make this decision for yourself. Oracle and DB2 assume you didn't realize you were doing something silly and throw an error. This is usually the right thing, but not always -- you might actually not know and have a NULL in some cases and therefore leaving a row with an unknown element against which meaningful comparisons are impossible is correct behavior.

In any case you should strive to eliminate the number of NULL fields you permit across the entire schema and doubly so when it comes to fields that are part of a primary key. In the vast majority of cases the presence of NULL columns is an indication of un-normalized (as opposed to deliberately de-normalized) schema design and should be thought very hard about before being accepted.

[* NOTE: It is possible to create a custom type that is the union of integers and a "bottom" type that would semantically mean "empty" as opposed to "unknown". Unfortunately this introduces a bit of complexity in comparison operations and usually being truly type correct isn't worth the effort in practice as you shouldn't be permitted many NULL values at all in the first place. That said, it would be wonderful if RDBMSs would include a default BOTTOM type in addition to NULL to prevent the habit of casually conflating the semantics of "no value" with "unknown value".]

How do I find duplicate values in a table in Oracle?

Simplest I can think of:

select job_number, count(*)
from jobs
group by job_number
having count(*) > 1;

WPF TemplateBinding vs RelativeSource TemplatedParent

TemplateBinding is not quite the same thing. MSDN docs are often written by people that have to quiz monosyllabic SDEs about software features, so the nuances are not quite right.

TemplateBindings are evaluated at compile time against the type specified in the control template. This allows for much faster instantiation of compiled templates. Just fumble the name in a templatebinding and you'll see that the compiler will flag it.

The binding markup is resolved at runtime. While slower to execute, the binding will resolve property names that are not visible on the type declared by the template. By slower, I'll point out that its kind of relative since the binding operation takes very little of the application's cpu. If you were blasting control templates around at high speed you might notice it.

As a matter of practice use the TemplateBinding when you can but don't fear the Binding.

SQL Server: Maximum character length of object names

You can also use this script to figure out more info:

EXEC sp_server_info

The result will be something like that:

attribute_id | attribute_name        | attribute_value
-------------|-----------------------|-----------------------------------
           1 | DBMS_NAME             | Microsoft SQL Server
           2 | DBMS_VER              | Microsoft SQL Server 2012 - 11.0.6020.0
          10 | OWNER_TERM            | owner
          11 | TABLE_TERM            | table
          12 | MAX_OWNER_NAME_LENGTH | 128
          13 | TABLE_LENGTH          | 128
          14 | MAX_QUAL_LENGTH       | 128
          15 | COLUMN_LENGTH         | 128
          16 | IDENTIFIER_CASE       | MIXED
           ?  ?                       ?
           ?  ?                       ?
           ?  ?                       ?

PHP server on local machine?

If you want an all-purpose local development stack for any operating system where you can choose from different PHP, MySQL and Web server versions and are also not afraid of using Docker, you could go for the devilbox.

The devilbox is a modern and highly customisable dockerized PHP stack supporting full LAMP and MEAN and running on all major platforms. The main goal is to easily switch and combine any version required for local development. It supports an unlimited number of projects for which vhosts and DNS records are created automatically. Email catch-all and popular development tools will be at your service as well. Configuration is not necessary, as everything is pre-setup with mass virtual hosting.

Getting it up and running is pretty straight-forward:

# Get the devilbox
$ git clone https://github.com/cytopia/devilbox
$ cd devilbox

# Create docker-compose environment file
$ cp env-example .env

# Edit your configuration
$ vim .env

# Start all containers
$ docker-compose up

devilbox

Links:

Using atan2 to find angle between two vectors

 atan2(vector1.y - vector2.y, vector1.x - vector2.x)

is the angle between the difference vector (connecting vector2 and vector1) and the x-axis, which is problably not what you meant.

The (directed) angle from vector1 to vector2 can be computed as

angle = atan2(vector2.y, vector2.x) - atan2(vector1.y, vector1.x);

and you may want to normalize it to the range [0, 2 p):

if (angle < 0) { angle += 2 * M_PI; }

or to the range (-p, p]:

if (angle > M_PI)        { angle -= 2 * M_PI; }
else if (angle <= -M_PI) { angle += 2 * M_PI; }

Python `if x is not None` or `if not x is None`?

Personally, I use

if not (x is None):

which is understood immediately without ambiguity by every programmer, even those not expert in the Python syntax.

What command means "do nothing" in a conditional in Bash?

The no-op command in shell is : (colon).

if [ "$a" -ge 10 ]
then
    :
elif [ "$a" -le 5 ]
then
    echo "1"
else
    echo "2"
fi

From the bash manual:

: (a colon)
Do nothing beyond expanding arguments and performing redirections. The return status is zero.

reducing number of plot ticks

The solution @raphael gave is straightforward and quite helpful.

Still, the displayed tick labels will not be values sampled from the original distribution but from the indexes of the array returned by np.linspace(ymin, ymax, N).

To display N values evenly spaced from your original tick labels, use the set_yticklabels() method. Here is a snippet for the y axis, with integer labels:

import numpy as np
import matplotlib.pyplot as plt

ax = plt.gca()

ymin, ymax = ax.get_ylim()
custom_ticks = np.linspace(ymin, ymax, N, dtype=int)
ax.set_yticks(custom_ticks)
ax.set_yticklabels(custom_ticks)

What are intent-filters in Android?

First change the xml, mark your second activity as DEFAULT

<activity android:name=".AddNewActivity" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

Now you can initiate this activity using StartActivity method.

Check if boolean is true?

Both are correct.

You probably have some coding standard in your company - just see to follow it through. If you don't have - you should :)

Duplicating a MySQL table, indices, and data

Go to phpMyAdmin and select your original table then select "Operations" tab in the "Copy table to (database.table)" area. Select the database where you want to copy and add a name for your new table.

copy table - phyMyAdmin Screenshot

Importing large sql file to MySql via command line

You can import .sql file using the standard input like this:

mysql -u <user> -p<password> <dbname> < file.sql

Note: There shouldn't space between <-p> and <password>

Reference: http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html

Note for suggested edits: This answer was slightly changed by suggested edits to use inline password parameter. I can recommend it for scripts but you should be aware that when you write password directly in the parameter (-p<password>) it may be cached by a shell history revealing your password to anyone who can read the history file. Whereas -p asks you to input password by standard input.

What does "Error: object '<myvariable>' not found" mean?

I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.

Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!

Hope to help

What is the right way to POST multipart/form-data using curl?

On Windows 10, curl 7.28.1 within powershell, I found the following to work for me:

$filePath = "c:\temp\dir with spaces\myfile.wav"
$curlPath = ("myfilename=@" + $filePath)
curl -v -F $curlPath URL

Get a Windows Forms control by name in C#

You can do the following:

private ToolStripMenuItem getToolStripMenuItemByName(string nameParam)
   {
      foreach (Control ctn in this.Controls)
         {
            if (ctn is ToolStripMenuItem)
               {
                   if (ctn.Name = nameParam)
                      {
                         return ctn;
                      }
                }
         }
         return null;
    }

How to include Javascript file in Asp.Net page

I assume that you are using MasterPage so within your master page you should have

<head runat="server">
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>

And within any of your pages based on that MasterPage add this

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script src="js/yourscript.js" type="text/javascript"></script>
</asp:Content>

Access is denied when attaching a database

I had the same issue when attaching a database. It wasn't a SQL issue it was an account issue. Go to the panel control/User Account Control Settings/Set to "never notify". Finally,restart the computer and it worked for me.

Where is the user's Subversion config file stored on the major operating systems?

@Baxter's is mostly correct but it is missing one important Windows-specific detail.

Subversion's runtime configuration area is stored in the %APPDATA%\Subversion\ directory. The files are config and servers.

However, in addition to text-based configuration files, Subversion clients can use Windows Registry to store the client settings. It makes it possible to modify the settings with PowerShell in a convenient manner, and also distribute these settings to user workstations in Active Directory environment via AD Group Policy. See SVNBook | Configuration and the Windows Registry (you can find examples and a sample *.reg file there).

enter image description here

Printing the correct number of decimal points with cout

Just a minor point; put the following in the header

using namespace std;

then

std::cout << std::fixed << std::setprecision(2) << d;

becomes simplified to

cout << fixed << setprecision(2) << d;

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.

In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.

It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.

Pie chart with jQuery

Tons of great suggestions here, just going to throw ZingChart onto the stack for good measure. We recently released a jQuery wrapper for the library that makes it even easier to build and customize charts. The CDN links are in the demo below.

I'm on the ZingChart team and we're here to answer any questions any of you might have!

_x000D_
_x000D_
$('#pie-chart').zingchart({_x000D_
  "data": {_x000D_
    "type": "pie",_x000D_
    "legend": {},_x000D_
    "series": [{_x000D_
      "values": [5]_x000D_
    }, {_x000D_
      "values": [10]_x000D_
    }, {_x000D_
      "values": [15]_x000D_
    }]_x000D_
  }_x000D_
});
_x000D_
<script src="http://cdn.zingchart.com/zingchart.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://cdn.zingchart.com/zingchart.jquery.min.js"></script>_x000D_
_x000D_
<div id="pie-chart"></div>
_x000D_
_x000D_
_x000D_

How to achieve function overloading in C?

In the sense you mean — no, you cannot.

You can declare a va_arg function like

void my_func(char* format, ...);

, but you'll need to pass some kind of information about number of variables and their types in the first argument — like printf() does.

Catching FULL exception message

I keep coming back to these questions trying to figure out where exactly the data I'm interested in is buried in what is truly a monolithic ErrorRecord structure. Almost all answers give piecemeal instructions on how to pull certain bits of data.

But I've found it immensely helpful to dump the entire object with ConvertTo-Json so that I can visually see LITERALLY EVERYTHING in a comprehensible layout.

    try {
        Invoke-WebRequest...
    }
    catch {
        Write-Host ($_ | ConvertTo-Json)
    }

Use ConvertTo-Json's -Depth parameter to expand deeper values, but use extreme caution going past the default depth of 2 :P

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json

SQL SERVER, SELECT statement with auto generate row id

Is this perhaps what you are looking for?

select NEWID() * from TABLE

sending mail from Batch file

We use blat to do this all the time in our environment. I use it as well to connect to Gmail with Stunnel. Here's the params to send a file

blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body" -attach c:\temp\file.txt

Or you can put that file in as the body

blat c:\temp\file.txt -to [email protected] -server smtp.example.com -f [email protected] -subject "subject"

'react-scripts' is not recognized as an internal or external command

This is rather old question but this might be of some help for future reference. Delete node_modules folder and run npm install again. Worked for me.

How to copy a char array in C?

c functions below only ... c++ you have to do char array then use a string copy then user the string tokenizor functions... c++ made it a-lot harder to do anythng

#include <iostream>
#include <fstream>
#include <cstring>
#define TRUE 1
#define FALSE 0
typedef int Bool;
using namespace std;
Bool PalTrueFalse(char str[]);
int main(void)
{
char string[1000], ch;
int i = 0;
cout<<"Enter a message: ";

while((ch = getchar()) != '\n') //grab users input string untill 
{                               //Enter is pressed
    if (!isspace(ch) && !ispunct(ch)) //Cstring functions checking for
    {                                //spaces and punctuations of all kinds
        string[i] = tolower(ch); 
        i++;
    }
}
string[i] = '\0';  //hitting null deliminator once users input
cout<<"Your string: "<<string<<endl; 
if(PalTrueFalse(string)) //the string[i] user input is passed after
                        //being cleaned into the null function.
    cout<<"is a "<<"Palindrome\n"<<endl;
else
   cout<<"Not a palindrome\n"<<endl;
return 0;
}

Bool PalTrueFalse(char str[])
{
int left = 0;
int right = strlen(str)-1;
while (left<right)
{
   if(str[left] != str[right]) //comparing most outer values of string
       return FALSE;          //to inner values.
   left++;
   right--;
}
return TRUE;
}

How to take character input in java

use :

char ch=**scanner.nextChar**()

Package php5 have no installation candidate (Ubuntu 16.04)

I recently had this issue as well and solved it using the following command:

sudo apt install php7.2-cli

php is now installed. I'm using Ubuntu 18.04.

Change Spinner dropdown icon

I have had a lot of difficulty with this as I have a custom spinner, if I setBackground then the Drawable would stretch. My solution to this was to add a drawable to the right of the Spinner TextView. Heres a code snippet from my Custom Spinner. The trick is to Override getView and customize the Textview as you wish.

public class NoTextSpinnerArrayAdapter extends ArrayAdapter<String> {

    private String text = "0";

    public NoTextSpinnerArrayAdapter(Context context, int textViewResourceId, List<String> objects) {
        super(context, textViewResourceId, objects);
    }

    public void updateText(String text){
        this.text = text;
        notifyDataSetChanged();
    }

    public String getText(){
        return text;
    }

    @NonNull
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView textView = view.findViewById(android.R.id.text1);
        textView.setCompoundDrawablePadding(16);
        textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_menu_white_24dp, 0);

        textView.setGravity(Gravity.END);
        textView.setText(text);
        return view;
    }
}

You also need to set the Spinner background to transparent:

<lifeunlocked.valueinvestingcheatsheet.views.SelectAgainSpinner
            android:id="@+id/saved_tickers_spinner"
            android:background="@android:color/transparent"
            android:layout_width="60dp"
            android:layout_height="match_parent"
            tools:layout_editor_absoluteX="248dp"
            tools:layout_editor_absoluteY="16dp" />

and my custom spinner if you want it....

public class SelectAgainSpinner extends android.support.v7.widget.AppCompatSpinner {
    public SelectAgainSpinner(Context context) {
        super(context);
    }

    public SelectAgainSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SelectAgainSpinner(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setPopupBackgroundDrawable(Drawable background) {
        super.setPopupBackgroundDrawable(background);
    }

    @Override
    public void setSelection(int position, boolean animate) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position, animate);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }

    @Override
    public void setSelection(int position) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }
}

Escaping ampersand character in SQL string

This works as well:

select * from mde_product where cfn = 'A3D"&"R01'

you define & as literal by enclosing is with double qoutes "&" in the string.

How do I pull from a Git repository through an HTTP proxy?

This isn't a problem with your proxy. It's a problem with github (or git). It fails for me on git-1.6.0.1 on linux as well. Bug is already reported (by you no less).

Make sure to delete your pasties, they're already on google. Edit: Must've been dreaming, i guess you can't delete them. Use Gist instead?

Set cookies for cross origin requests

In order for the client to be able to read cookies from cross-origin requests, you need to have:

  1. All responses from the server need to have the following in their header:

    Access-Control-Allow-Credentials: true

  2. The client needs to send all requests with withCredentials: true option

In my implementation with Angular 7 and Spring Boot, I achieved that with the following:


Server-side:

@CrossOrigin(origins = "http://my-cross-origin-url.com", allowCredentials = "true")
@Controller
@RequestMapping(path = "/something")
public class SomethingController {
  ...
}

The origins = "http://my-cross-origin-url.com" part will add Access-Control-Allow-Origin: http://my-cross-origin-url.com to every server's response header

The allowCredentials = "true" part will add Access-Control-Allow-Credentials: true to every server's response header, which is what we need in order for the client to read the cookies


Client-side:

import { HttpInterceptor, HttpXsrfTokenExtractor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {

    constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // send request with credential options in order to be able to read cross-origin cookies
        req = req.clone({ withCredentials: true });

        // return XSRF-TOKEN in each request's header (anti-CSRF security)
        const headerName = 'X-XSRF-TOKEN';
        let token = this.tokenExtractor.getToken() as string;
        if (token !== null && !req.headers.has(headerName)) {
            req = req.clone({ headers: req.headers.set(headerName, token) });
        }
        return next.handle(req);
    }
}

With this class you actually inject additional stuff to all your request.

The first part req = req.clone({ withCredentials: true });, is what you need in order to send each request with withCredentials: true option. This practically means that an OPTION request will be send first, so that you get your cookies and the authorization token among them, before sending the actual POST/PUT/DELETE requests, which need this token attached to them (in the header), in order for the server to verify and execute the request.

The second part is the one that specifically handles an anti-CSRF token for all requests. Reads it from the cookie when needed and writes it in the header of every request.

The desired result is something like this:

response request

Compare two objects with .equals() and == operator

Here the output will be false , false beacuse in first sopln statement you are trying to compare a string type varible of Myclass type to the other MyClass type and it will allow because of both are Object type and you have used "==" oprerator which will check the reference variable value holding the actual memory not the actual contnets inside the memory . In the second sopln also it is the same as you are again calling a.equals(object2) where a is a varible inside object1 . Do let me know your findings on this .

GoogleTest: How to skip a test?

I prefer to do it in code:

// Run a specific test only
//testing::GTEST_FLAG(filter) = "MyLibrary.TestReading"; // I'm testing a new feature, run something quickly

// Exclude a specific test
testing::GTEST_FLAG(filter) = "-MyLibrary.TestWriting"; // The writing test is broken, so skip it

I can either comment out both lines to run all tests, uncomment out the first line to test a single feature that I'm investigating/working on, or uncomment the second line if a test is broken but I want to test everything else.
You can also test/exclude a suite of features by using wildcards and writing a list, "MyLibrary.TestNetwork*" or "-MyLibrary.TestFileSystem*".

Change Oracle port from port 8080

Oracle (database) can use many ports. when you install the software it scans for free ports and decides which port to use then.

The database listener defaults to 1520 but will use 1521 or 1522 if 1520 is not available. This can be adjusted in the listener.ora files.

The Enterprise Manager, web-based database administration tool defaults to port 80 but will use 8080 if 80 is not available.

See here for details on how to change the port number for enterprise manager: http://download-uk.oracle.com/docs/cd/B14099_19/integrate.1012/b19370/manage_oem.htm#i1012853

Common CSS Media Queries Break Points

I've been using:

@media only screen and (min-width: 768px) {
    /* tablets and desktop */
}

@media only screen and (max-width: 767px) {
    /* phones */
}

@media only screen and (max-width: 767px) and (orientation: portrait) {
    /* portrait phones */
}

It keeps things relatively simple and allows you to do something a bit different for phones in portrait mode (a lot of the time I find myself having to change various elements for them).

Git push rejected "non-fast-forward"

try this command

$ git push -f -u origin <name of branch>

i.e $ git push -f -u origin master

Why are hexadecimal numbers prefixed with 0x?

Note: I don't know the correct answer, but the below is just my personal speculation!

As has been mentioned a 0 before a number means it's octal:

04524 // octal, leading 0

Imagine needing to come up with a system to denote hexadecimal numbers, and note we're working in a C style environment. How about ending with h like assembly? Unfortunately you can't - it would allow you to make tokens which are valid identifiers (eg. you could name a variable the same thing) which would make for some nasty ambiguities.

8000h // hex
FF00h // oops - valid identifier!  Hex or a variable or type named FF00h?

You can't lead with a character for the same reason:

xFF00 // also valid identifier

Using a hash was probably thrown out because it conflicts with the preprocessor:

#define ...
#FF00 // invalid preprocessor token?

In the end, for whatever reason, they decided to put an x after a leading 0 to denote hexadecimal. It is unambiguous since it still starts with a number character so can't be a valid identifier, and is probably based off the octal convention of a leading 0.

0xFF00 // definitely not an identifier!

Android Facebook style slide

I've just implemented similar view for my own project. You can check it here

Here is screen of sample application based on library I wrote: ActionsContentView Example

It is easy to use this custom view as element of XML layout. Here is example:

    <shared.ui.actionscontentview.ActionsContentView
      android:id="@+id/content"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:actions_layout="@layout/actions"
      app:content_layout="@layout/content" />

I you will have any questions about usage of ActionsContentView library I can write a small article at projects Wiki.

Some advantages of this library:

  • ability to slide view by touch
  • it is easy to adjust size of actions bar in XML
  • support of all Android SDK version starting from 2.0 and up

There is one limitation:

  • all horizontal scrolling views will not work at bounds of this view

Best regards, Steven

Quickest way to find missing number in an array of numbers

Well, use a bloom filter.

int findmissing(int arr[], int n)
{
    long bloom=0;
    int i;
    for(i=0; i<;n; i++)bloom+=1>>arr[i];
    for(i=1; i<=n, (bloom<<i & 1); i++);
    return i;
}

react-native - Fit Image in containing View, not the whole screen size

Anyone over here who wants his image to fit in full screen without any crop (in both portrait and landscape mode), use this:

image: {
    flex: 1,
    width: '100%',
    height: '100%',
    resizeMode: 'contain',
},

How should I multiple insert multiple records?

If I were you I would not use either of them.

The disadvantage of the first one is that the parameter names might collide if there are same values in the list.

The disadvantage of the second one is that you are creating command and parameters for each entity.

The best way is to have the command text and parameters constructed once (use Parameters.Add to add the parameters) change their values in the loop and execute the command. That way the statement will be prepared only once. You should also open the connection before you start the loop and close it after it.

How can I get the DateTime for the start of the week?

Ugly but it at least gives the right dates back

With start of week set by system:

    public static DateTime FirstDateInWeek(this DateTime dt)
    {
        while (dt.DayOfWeek != System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
            dt = dt.AddDays(-1);
        return dt;
    }

Without:

    public static DateTime FirstDateInWeek(this DateTime dt, DayOfWeek weekStartDay)
    {
        while (dt.DayOfWeek != weekStartDay)
            dt = dt.AddDays(-1);
        return dt;
    }

CSS property to pad text inside of div

The CSS property you are looking for is padding. The problem with padding is that it adds to the width of the original element, so if you have a div with a width of 300px, and add 10px of padding to it, the width will now be 320px (10px on the left and 10px on the right).

To prevent this you can add box-sizing: border-box; to the div, this makes it maintain the designated width, even if you add padding. So your CSS would look like this:

div {
    box-sizing: border-box;
    padding: 10px;
}

you can read more about box-sizing and it's overall browser support here:

http://www.paulirish.com/2012/box-sizing-border-box-ftw/

Responsively change div size keeping aspect ratio

You can do this using pure CSS; no JavaScript needed. This utilizes the (somewhat counterintuitive) fact that padding-top percentages are relative to the containing block's width. Here's an example:

_x000D_
_x000D_
.wrapper {_x000D_
  width: 50%;_x000D_
  /* whatever width you want */_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
}_x000D_
.wrapper:after {_x000D_
  padding-top: 56.25%;_x000D_
  /* 16:9 ratio */_x000D_
  display: block;_x000D_
  content: '';_x000D_
}_x000D_
.main {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  /* fill parent */_x000D_
  background-color: deepskyblue;_x000D_
  /* let's see it! */_x000D_
  color: white;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="main">_x000D_
    This is your div with the specified aspect ratio._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Laravel 5 call a model function in a blade view

Instead of passing functions or querying it on the controller, I think what you need is relationships on models since these are related tables on your database.

If based on your structure, input_details and products are related you should put relationship definition on your models like this:

public class InputDetail(){
 protected $table = "input_details";
 ....//other code

 public function product(){
   return $this->hasOne('App\Product');
 }
}

then in your view you'll just have to say:

<p>{{ $input_details->product->name }}</p>

More simpler that way. It is also the best practice that controllers should only do business logic for the current resource. For more info on how to do this just go to the docs: https://laravel.com/docs/5.0/eloquent#relationships

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Polymorphism vs Overriding vs Overloading

Polymorphism is the ability for an object to appear in multiple forms. This involves using inheritance and virtual functions to build a family of objects which can be interchanged. The base class contains the prototypes of the virtual functions, possibly unimplemented or with default implementations as the application dictates, and the various derived classes each implements them differently to affect different behaviors.

Create controller for partial view in ASP.NET MVC

Html.Action is a poorly designed technology. Because in your page Controller you can't receive the results of computation in your Partial Controller. Data flow is only Page Controller => Partial Controller.

To be closer to WebForm UserControl (*.ascx) you need to:

  1. Create a page Model and a Partial Model

  2. Place your Partial Model as a property in your page Model

  3. In page's View use Html.EditorFor(m => m.MyPartialModel)
  4. Create an appropriate Partial View
  5. Create a class very similar to that Child Action Controller described here in answers many times. But it will be just a class (inherited from Object rather than from Controller). Let's name it as MyControllerPartial. MyControllerPartial will know only about Partial Model.
  6. Use your MyControllerPartial in your page controller. Pass model.MyPartialModel to MyControllerPartial
  7. Take care about proper prefix in your MyControllerPartial. Fox example: ModelState.AddError("MyPartialModel." + "SomeFieldName", "Error")
  8. In MyControllerPartial you can make validation and implement other logics related to this Partial Model

In this situation you can use it like:

public class MyController : Controller
{
    ....
    public MyController()
    {
    MyChildController = new MyControllerPartial(this.ViewData);
    }

    [HttpPost]
    public ActionResult Index(MyPageViewModel model)
    {
    ...
    int childResult = MyChildController.ProcessSomething(model.MyPartialModel);
    ...
    }
}

P.S. In step 3 you can use Html.Partial("PartialViewName", Model.MyPartialModel, <clone_ViewData_with_prefix_MyPartialModel>). For more details see ASP.NET MVC partial views: input name prefixes

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

What about this for a catch all...

if (string.IsNullOrEmpty(x.Trim())
{
}

This will trim all the spaces if they are there avoiding the performance penalty of IsWhiteSpace, which will enable the string to meet the "empty" condition if its not null.

I also think this is clearer and its generally good practise to trim strings anyway especially if you are putting them into a database or something.

How to write inside a DIV box with javascript

I would suggest Jquery:

$("#log").html("Type what you want to be shown to the user");   

System has not been booted with systemd as init system (PID 1). Can't operate

If you are using Docker, you may try an image that has Ubuntu with System D already active with this command:

docker run -d --name redis --privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro jrei/systemd-ubuntu:18.04

Then you just need to run:

docker exec -it redis /bin/bash

and there you can just install Redis, start it, restart it or whatever you need.

How to use conditional breakpoint in Eclipse?

A way that might be more convenient: where you want a breakpoint, write a no-op if statement and set a breakpoint in its contents.

if(tablist[i].equalsIgnoreCase("LEADDELEGATES")) {
-->    int noop = 0; //don't do anything
}

(the breakpoint is represented by the arrow)

This way, the breakpoint only triggers if your condition is true. This could potentially be easier without that many pop-ups.

rotating axis labels in R

Not sure if this is what you mean, but try setting las=1. Here's an example:

require(grDevices)
tN <- table(Ni <- stats::rpois(100, lambda=5))
r <- barplot(tN, col=rainbow(20), las=1)

output

That represents the style of axis labels. (0=parallel, 1=all horizontal, 2=all perpendicular to axis, 3=all vertical)

Twitter bootstrap modal-backdrop doesn't disappear

I suffered a similar issue: in my modal window, I have two buttons, "Cancel" and "OK". Originally, both buttons would close the modal window by invoking $('#myModal').modal('hide') (with "OK" previously executing some code) and the scenario would be the following:

  1. Open the modal window
  2. Do some operations, then click on "OK" do validate them and close the modal
  3. Open the modal again and dismiss by clicking on "Cancel"
  4. Re-open the modal, click again on "Cancel" ==> the backdrop is no longer accessible!

well, my fellow next desk saved my day: instead of invoking $('#myModal').modal('hide'), give your buttons the attribute data-dismiss="modal" and add a "click" event to your "Submit" button. In my problem, the HTML (well, TWIG) code for the button is:

<button id="modal-btn-ok" class="btn" data-dismiss="modal">OK</button>
<button id="modal-btn-cancel" class="btn" data-dismiss="modal">Cancel</button>

and in my JavaScript code, I have:

$("#modal-btn-ok").one("click", null, null, function(){
    // My stuff to be done
});

while no "click" event is attributed to the "Cancel" button. The modal now closes properly and lets me play again with the "normal" page. It actually seems that the data-dismiss="modal" should be the only way to indicate that a button (or whatever DOM element) should close a Bootstrap modal. The .modal('hide') method seems to behave in a not quite controllable way.

Hope this helps!

Create an array of integers property in Objective-C

I'm just speculating:

I think that the variable defined in the ivars allocates the space right in the object. This prevents you from creating accessors because you can't give an array by value to a function but only through a pointer. Therefore you have to use a pointer in the ivars:

int *doubleDigits;

And then allocate the space for it in the init-method:

@synthesize doubleDigits;

- (id)init {
    if (self = [super init]) {
        doubleDigits = malloc(sizeof(int) * 10);
        /*
         * This works, but is dangerous (forbidden) because bufferDoubleDigits
         * gets deleted at the end of -(id)init because it's on the stack:
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * [self setDoubleDigits:bufferDoubleDigits];
         *
         * If you want to be on the safe side use memcpy() (needs #include <string.h>)
         * doubleDigits = malloc(sizeof(int) * 10);
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * memcpy(doubleDigits, bufferDoubleDigits, sizeof(int) * 10);
         */
    }
    return self;
}

- (void)dealloc {
    free(doubleDigits);
    [super dealloc];
}

In this case the interface looks like this:

@interface MyClass : NSObject {
    int *doubleDigits;
}
@property int *doubleDigits;

Edit:

I'm really unsure wether it's allowed to do this, are those values really on the stack or are they stored somewhere else? They are probably stored on the stack and therefore not safe to use in this context. (See the question on initializer lists)

int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
[self setDoubleDigits:bufferDoubleDigits];

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

Hexadecimal To Decimal in Shell Script

To convert from hex to decimal, there are many ways to do it in the shell or with an external program:

With :

$ echo $((16#FF))
255

with :

$ echo "ibase=16; FF" | bc
255

with :

$ perl -le 'print hex("FF");'
255

with :

$ printf "%d\n" 0xFF
255

with :

$ python -c 'print(int("FF", 16))'
255

with :

$ ruby -e 'p "FF".to_i(16)'
255

with :

$ nodejs <<< "console.log(parseInt('FF', 16))"
255

with :

$ rhino<<EOF
print(parseInt('FF', 16))
EOF
...
255

with :

$ groovy -e 'println Integer.parseInt("FF",16)'
255

Where does the .gitignore file belong?

If you want to do it globally, you can use the default path git will search for. Just place it inside a file named "ignore" in the path ~/.config/git

(so full path for your file is: ~/.config/git/ignore)

Count the cells with same color in google spreadsheet

here is a working version :

function countbackgrounds() {
 var book = SpreadsheetApp.getActiveSpreadsheet();
 var range_input = book.getRange("B3:B4");
 var range_output = book.getRange("B6");
 var cell_colors = range_input.getBackgroundColors();
 var color = "#58FA58";
 var count = 0;

 for( var i in cell_colors ){
 Logger.log(cell_colors[i][0])
  if( cell_colors[i][0] == color ){ ++count }
  }
range_output.setValue(count);
 }  

Getting content/message from HttpResponseMessage

You can use the GetStringAsync method:

var uri = new Uri("http://yoururlhere");
var response = await client.GetStringAsync(uri);

What is the difference between a deep copy and a shallow copy?

'ShallowCopy' points to the same location in memory as 'Source' does. 'DeepCopy' points to a different location in memory, but the contents are the same.

bash, extract string before a colon

Try this in pure bash:

FRED="/some/random/file.csv:some string"
a=${FRED%:*}
echo $a

Here is some documentation that helps.

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

For me i had already created a folder with name excel in wwroot D:\working directory\OnlineExam\wwwroot\excel And i was trying to copy a file with name excel which was already existing as a folder name. the path which was required was D:\working directory\OnlineExam\wwwroot\excel\finance.csv so according i changed the code as below

string copyPath = Path.Combine(_webHostEnvironment.WebRootPath, "excel\\finance");
                    questionExcelUpload.Upload.CopyTo(new FileStream(copyPath, FileMode.Create));

Basically check if a folder or a file with same name as your path exist already.

HttpServletRequest - Get query string parameters, no form data

The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.

The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":

GET /persons?age=42

The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":

PUT /persons?age=42

hair=grey

So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.

line breaks in a textarea

The simple way:

  1. Use this to insert into mysql:

    $msg = $_GET['msgtextarea']; //or POST and my msg field format: text
    $msg = htmlspecialchars($msg, ENT_QUOTES);

  2. And use this for output:

    echo nl2br($br['msg']);

Convert DateTime to String PHP

You can use the format method of the DateTime class:

$date = new DateTime('2000-01-01');
$result = $date->format('Y-m-d H:i:s');

If format fails for some reason, it will return FALSE. In some applications, it might make sense to handle the failing case:

if ($result) {
  echo $result;
} else { // format failed
  echo "Unknown Time";
}

Can a Windows batch file determine its own file name?

Bear in mind that 0 is a special case of parameter numbers inside a batch file, where 0 means this file as given on the command line.

So if the file is myfile.bat, you could call it in several ways as follows, each of which would give you a different output from the %0 or %~0 usage:

myfile

myfile.bat

mydir\myfile.bat

c:\mydir\myfile.bat

"c:\mydir\myfile.bat"

All of the above are legal calls if you call it from the correct relative place to the directory in which it exists. %~0 strips the quotes from the last example, whereas %0 does not.

Because these all give different results, %0 and %~0 are very unlikely to be what you actually want to use.

Here's a batch file to illustrate:

@echo Full path and filename: %~f0
@echo Drive: %~d0
@echo Path: %~p0
@echo Drive and path: %~dp0
@echo Filename without extension: %~n0
@echo Filename with    extension: %~nx0
@echo Extension: %~x0
@echo Filename as given on command line: %0
@echo Filename as given on command line minus quotes: %~0
@REM Build from parts
@SETLOCAL
@SET drv=%~d0
@SET pth=%~p0
@SET fpath=%~dp0
@SET fname=%~n0
@SET ext=%~x0
@echo Simply Constructed name: %fpath%%fname%%ext%
@echo Fully  Constructed name: %drv%%pth%%fname%%ext%
@ENDLOCAL
pause

Killing a process using Java

If you start the process from with in your Java application (ex. by calling Runtime.exec() or ProcessBuilder.start()) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.

But be aware that if the process that you invoke creates new sub-processes, those may not be terminated (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092).

On the other hand, if you want to kill external processes (which you did not spawn from your Java app), then one thing you can do is to call O/S utilities which allow you to do that. For example, you can try a Runtime.exec() on kill command under Unix / Linux and check for return values to ensure that the application was killed or not (0 means success, -1 means error). But that of course will make your application platform dependent.

ActiveRecord: size vs count

You should read that, it's still valid.

You'll adapt the function you use depending on your needs.

Basically:

  • if you already load all entries, say User.all, then you should use length to avoid another db query

  • if you haven't anything loaded, use count to make a count query on your db

  • if you don't want to bother with these considerations, use size which will adapt

Android: Clear Activity Stack

Using Kotlin:

You can set the flag directly using setter method. In Kotlin or is the replacement for the Java bitwise or |.

intent.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK

If you plan to use this regularly, create an Intent extension function

fun Intent.clearStack() {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

You can then directly call this function before starting the intent

intent.clearStack()

Cast int to varchar

I don't have MySQL, but there are RDBMS (Postgres, among others) in which you can use the hack

SELECT id || '' FROM some_table;

The concatenate does an implicit conversion.

The Import android.support.v7 cannot be resolved

Recent sdk-manager's download does not contain android-support-v7-appcompat.jar But the following dir contains aar file C:\Users\madan\android-sdks\extras\android\m2repository\com\ android\support\appcompat-v7\24.2.1\appcompat-v7-24.2.1.aar This file can be imported by right-click project, import, select general, select archieve and finally select aar file. Even this does not solve the problem. Later remove 'import android.R' and add 'import android.support.v7.appcompat.*;' Follow this tutorial for other details: http://www.srccodes.com/p/article/22/android-hello-world-example-using-eclipse-ide-and-android-development-tools-adt-plugin

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *. Also, the map method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply is used for.

So, if you must use the above approach, I would write it like this

df["A1"], df["A2"] = zip(*df["a"].apply(calculate))

There's actually no reason to use zip here. You can simply do this:

df["A1"], df["A2"] = calculate(df['a'])

This second method is also much faster on larger DataFrames

df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})

DataFrame created with 300,000 rows

%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

60x faster than zip


In general, avoid using apply

Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above

%%timeit
A1, A2 = [], []
for val in df['a']:
    A1.append(val**2)
    A2.append(val**3)

df['A1'] = A1
df['A2'] = A2

298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:

%load_ext cython

%%cython
cpdef power(vals):
    A1, A2 = [], []
    cdef double val
    for val in vals:
        A1.append(val**2)
        A2.append(val**3)

    return A1, A2

%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Directly assigning without apply

You can get even greater speed improvements if you use the direct vectorized operations.

%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.


The simplest speed test with apply

The above example should clearly show how slow apply can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply

s = pd.Series(np.random.rand(10000000))

%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Without apply is 50x faster

%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

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

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

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

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

How to create folder with PHP code?

You can create it easily:

$structure = './depth1/depth2/depth3/';
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}

Getting a "This application is modifying the autolayout engine from a background thread" error?

I had the same issue when trying to update error message in UILabel in the same ViewController (it takes a little while to update data when trying to do that with normal coding). I used DispatchQueue in Swift 3 Xcode 8 and it works.

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

Keep only first n characters in a string?

You can use .substring, which returns a potion of a string:

"abcdefghijklmnopq".substring(0, 8) === "abcdefgh"; // portion from index 0 to 8

Is it better practice to use String.format over string Concatenation in Java?

About performance:

public static void main(String[] args) throws Exception {      
  long start = System.currentTimeMillis();
  for(int i = 0; i < 1000000; i++){
    String s = "Hi " + i + "; Hi to you " + i*2;
  }
  long end = System.currentTimeMillis();
  System.out.println("Concatenation = " + ((end - start)) + " millisecond") ;

  start = System.currentTimeMillis();
  for(int i = 0; i < 1000000; i++){
    String s = String.format("Hi %s; Hi to you %s",i, + i*2);
  }
  end = System.currentTimeMillis();
  System.out.println("Format = " + ((end - start)) + " millisecond");
}

The timing results are as follows:

  • Concatenation = 265 millisecond
  • Format = 4141 millisecond

Therefore, concatenation is much faster than String.format.

CronJob not running

For me, the solution was that the file cron was trying to run was in an encrypted directory, more specifcically a user diretory on /home/. Although the crontab was configured as root, because the script being run exisited in an encrypted user directory in /home/ cron could only read this directory when the user was actually logged in. To see if the directory is encrypted check if this directory exists:

/home/.ecryptfs/<yourusername>

if so then you have an encrypted home directory.

The fix for me was to move the script in to a non=encrypted directory and everythig worked fine.

Convert array of strings into a string in Java

Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:

String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);

Produces:

a-b-1

Using async/await with a forEach loop

A simple drop-in solution for replacing a forEach() await loop that is not working is replacing forEach with map and adding Promise.all( to the beginning.

For example:

await y.forEach(async (x) => {

to

await Promise.all(y.map(async (x) => {

An extra ) is needed at the end.

Can you break from a Groovy "each" closure?

Replace each loop with any closure.

def list = [1, 2, 3, 4, 5]
list.any { element ->
    if (element == 2)
        return // continue

    println element

    if (element == 3)
        return true // break
}

Output

1
3

How to display text in pygame?

Here is my answer:


    def draw_text(text, font_name, size, color, x, y, align="nw"):
        font = pg.font.Font(font_name, size)
        text_surface = font.render(text, True, color)
        text_rect = text_surface.get_rect()
        if align == "nw":
            text_rect.topleft = (x, y)
        if align == "ne":
            text_rect.topright = (x, y)
        if align == "sw":
            text_rect.bottomleft = (x, y)
        if align == "se":
            text_rect.bottomright = (x, y)
        if align == "n":
            text_rect.midtop = (x, y)
        if align == "s":
            text_rect.midbottom = (x, y)
        if align == "e":
            text_rect.midright = (x, y)
        if align == "w":
            text_rect.midleft = (x, y)
        if align == "center":
            text_rect.center = (x, y)
        screen.blit(text_surface, text_rect)

Of course, you'll need to import pygame, a font and a screen, but this is just a def to add on to the rest of the code, and then call "draw_text".

Bulk package updates using Conda

You want conda update --all.

conda search --outdated will show outdated packages, and conda update --all will update them (note that the latter will not update you from Python 2 to Python 3, but the former will show Python as being outdated if you do use Python 2).

SQL Server query to find all permissions/access for all users in a database

Great thanks for awesome audit scripts.

I highly recommend for audit user use awesome Kenneth Fisher (b | t) stored procedures:

Hibernate Annotations - Which is better, field or property access?

There are arguments for both, but most of them stem from certain user requirements "what if you need to add logic for", or "xxxx breaks encapsulation". However, nobody has really commented on the theory, and given a properly reasoned argument.

What is Hibernate/JPA actually doing when it persists an object - well, it is persisting the STATE of the object. That means storing it in a way that it can be easily reproduced.

What is encapsulation? Encapsulations means encapsulating the data (or state) with an interface that the application/client can use to access the data safely - keeping it consistent and valid.

Think of this like MS Word. MS Word maintains a model of the document in memory - the documents STATE. It presents an interface that the user can use to modify the document - a set of buttons, tools, keyboard commands etc. However, when you choose to persist (Save) that document, it saves the internal state, not the set of keypresses and mouse clicks used to generate it.

Saving the internal state of the object DOES NOT break encapsulation - otherwise you don't really understand what encapsulation means, and why it exists. It is just like object serialisation really.

For this reason, IN MOST CASES, it is appropriate to persist the FIELDS and not the ACCESSORS. This means that an object can be accurately recreated from the database exactly the way it was stored. It should not need any validation, because this was done on the original when it was created, and before it was stored in the database (unless, God forbid, you are storing invalid data in the DB!!!!). Likewise, there should be no need to calculate values, as they were already calculated before the object was stored. The object should look just the way it did before it was saved. In fact, by adding additional stuff into the getters/setters you are actually increasing the risk that you will recreate something that is not an exact copy of the original.

Of course, this functionality was added for a reason. There may be some valid use cases for persisting the accessors, however, they will typically be rare. An example may be that you want to avoid persisting a calculated value, though you may want to ask the question why you don't calculate it on demand in the value's getter, or lazily initialise it in the getter. Personally I cannot think of any good use case, and none of the answers here really give a "Software Engineering" answer.

How to remove unused C/C++ symbols with GCC and ld?

Programming habits could help too; e.g. add static to functions that are not accessed outside a specific file; use shorter names for symbols (can help a bit, likely not too much); use const char x[] where possible; ... this paper, though it talks about dynamic shared objects, can contain suggestions that, if followed, can help to make your final binary output size smaller (if your target is ELF).

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

To change the navigation icon you can use:

Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.my_icon);

To change the overflow icon you can use the method:

toolbar.setOverflowIcon(ContextCompat.getDrawable(this, R.drawable.ic_my_menu);

If you would like to change the color of the icons you can use:

with a Material Components Theme (with a MaterialToolbar for example):

<com.google.android.material.appbar.MaterialToolbar
    android:theme="@style/MyThemeOverlay_Toolbar"
    ...>

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- color used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/myColor</item>
  </style>

With an AppCompat Theme:

<android.support.v7.widget.Toolbar
  app:theme="@style/ThemeToolbar" />


<style name="ThemeToolbar" parent="Theme.AppCompat.Light">

   <!-- navigation icon color -->
   <item name="colorControlNormal">@color/my_color</item>

    <!-- color of the menu overflow icon -->
    <item name="android:textColorSecondary">@color/my_color</item>
</style>

You can also change the overflow icon overriding in the app theme the actionOverflowButtonStyle attribute:

With a Material Components Theme:

<style name="AppTheme.Base" parent="Theme.MaterialComponents.DayNight">
    <item name="actionOverflowButtonStyle">@style/OverFlow</item>
</style>

<style name="OverFlow" parent="Widget.AppCompat.ActionButton.Overflow">
    <item name="srcCompat">@drawable/my_overflow_menu</item>
</style>

With an AppCompat theme:

<style name="AppTheme.Base" parent="Theme.AppCompat.Light">
    <item name="actionOverflowButtonStyle">@style/OverFlow</item>
</style>

<style name="OverFlow" parent="Widget.AppCompat.ActionButton.Overflow">
    <item name="srcCompat">@drawable/my_overflow_menu</item>
</style>

Check if a variable is null in plsql

Always remember to be careful with nulls in pl/sql conditional clauses as null is never greater, smaller, equal or unequal to anything. Best way to avoid them is to use nvl.

For example

declare
  i integer;
begin
  if i <> 1 then
    i:=1;
    foobar();
  end if;
end;
/

Never goes inside the if clause.

These would work.

if 1<>nvl(i,1) then
if i<> 1 or i is null then

How do I add a newline using printf?

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget

How to redirect output of an already running process

Dupx

Dupx is a simple *nix utility to redirect standard output/input/error of an already running process.

Motivation

I've often found myself in a situation where a process I started on a remote system via SSH takes much longer than I had anticipated. I need to break the SSH connection, but if I do so, the process will die if it tries to write something on stdout/error of a broken pipe. I wish I could suspend the process with ^Z and then do a

bg %1 >/tmp/stdout 2>/tmp/stderr 

Unfortunately this will not work (in shells I know).

http://www.isi.edu/~yuri/dupx/

Gets byte array from a ByteBuffer in java

final ByteBuffer buffer;
if (buffer.hasArray()) {
    final byte[] array = buffer.array();
    final int arrayOffset = buffer.arrayOffset();
    return Arrays.copyOfRange(array, arrayOffset + buffer.position(),
                              arrayOffset + buffer.limit());
}
// do something else

How to get the day of week and the month of the year?

Use the standard javascript Date class. No need for arrays. No need for extra libraries.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

_x000D_
_x000D_
var options = {  weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };_x000D_
var prnDt = 'Printed on ' + new Date().toLocaleTimeString('en-us', options);_x000D_
_x000D_
console.log(prnDt);
_x000D_
_x000D_
_x000D_

PHP DOMDocument loadHTML not encoding UTF-8 correctly

The problem is that when you add a parameter to DOMDocument::saveHTML() function, you lose the encoding. In a few cases, you'll need to avoid the use of the parameter and use old string function to find what your are looking for.

I think the previous answer works for you, but since this workaround didn't work for me, I'm adding that answer to help people who may be in my case.

Visual Studio Community 2015 expiration date

In my case, even after sign up to Visual Studio account, I cant sign in and the license still expired.

Solution from across the internet: Download iso version of the installer. Then run installer, select repair. That would solve the problem for most case.

In my case, I got an iso version of ms Visual Studio 2013. Installed it and I can successfully sign in and its forever free.

How can I remove a key from a Python dictionary?

I prefer the immutable version

foo = {
    1:1,
    2:2,
    3:3
}
removeKeys = [1,2]
def woKeys(dct, keyIter):
    return {
        k:v
        for k,v in dct.items() if k not in keyIter
    }

>>> print(woKeys(foo, removeKeys))
{3: 3}
>>> print(foo)
{1: 1, 2: 2, 3: 3}

jQuery: Count number of list elements?

_x000D_
_x000D_
$("button").click(function(){_x000D_
    alert($("li").length);_x000D_
 });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>_x000D_
  <meta charset="utf-8">_x000D_
  <title>Count the number of specific elements</title>_x000D_
</head>_x000D_
<body>_x000D_
<ul>_x000D_
  <li>List - 1</li>_x000D_
  <li>List - 2</li>_x000D_
  <li>List - 3</li>_x000D_
</ul>_x000D_
  <button>Display the number of li elements</button>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Google Maps how to Show city or an Area outline

use this code:

<iframe width="600" height="450" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?q=place_id:ChIJ5Rw5v9dCXz4R3SUtcL5ZLMk&key=..." allowfullscreen></iframe>

How to "z-index" to make a menu always on top of the content

Ok, Im assuming you want to put the .left inside the container so I suggest you edit your html. The key is the position:absolute and right:0

#right { 
    background-color: red;
    height: 300px;
    width: 300px;
    z-index: 999999;
    margin-top: 0px;
    position: absolute;
    right:0;
}

here is the full code: http://jsfiddle.net/T9FJL/

How do I programmatically click a link with javascript?

Many of the above methods have been deprecated. It is now recommended to use the constructor found here

function clickAnchorTag() {
    var event = document.createEvent('MouseEvent');
    event = new CustomEvent('click');
    var a = document.getElementById('nameOfID');
    a.dispatchEvent(event);
}

This will cause the anchor tag to be clicked, but it wont show if pop-up blockers are active so the user will need to allow pop-ups.

No signing certificate "iOS Distribution" found

I had the same issue and I have gone through all these solutions given, but none of them worked for me. But then I realised my stupid mistake. I forgot to change Code signing identity to iOS Distribution from iOS Developer, under build settings tab. Please make sure you have selected 'iOS Distribution' there.

How to wait until an element exists?

You can do

$('#yourelement').ready(function() {

});

Please note that this will only work if the element is present in the DOM when being requested from the server. If the element is being dynamically added via JavaScript, it will not work and you may need to look at the other answers.

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

Best way to specify whitespace in a String.Split operation

you can use

var FirstString = YourString.Split().First();

to split string .

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

Target server must allowed cross-origin request. In order to allow it through express, simply handle http options request :

app.options('/url...', function(req, res, next){
   res.header('Access-Control-Allow-Origin', "*");
   res.header('Access-Control-Allow-Methods', 'POST');
   res.header("Access-Control-Allow-Headers", "accept, content-type");
   res.header("Access-Control-Max-Age", "1728000");
   return res.sendStatus(200);
});

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

Proper way to handle multiple forms on one page in Django

You have a few options:

  1. Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.

  2. Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons django form?

bower proxy configuration

add in .bowerrc

{SET HTTP_PROXY= http://HOST:PORT,SET HTTPS_PROXY=http://HOST:PORT}

In NPM, you must to execute in console this:

npm --proxy http://Host:Port install

Lua - Current time in milliseconds

I use LuaSocket to get more precision.

require "socket"
print("Milliseconds: " .. socket.gettime()*1000)

This adds a dependency of course, but works fine for personal use (in benchmarking scripts for example).

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The error message explains it pretty well:

ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()

What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

(1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

(2) True, because at least one element is True;

(3) False, because not all elements are True;

and that's not even considering the complexity of the N-d case.

So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True,  True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False

and you might want to consider np.allclose if you're comparing arrays of floats:

>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I update my Hibernate JPA to 2.1 and It works.

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

Download image from the site in .NET/C#

        private static void DownloadRemoteImageFile(string uri, string fileName)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if ((response.StatusCode == HttpStatusCode.OK ||
                response.StatusCode == HttpStatusCode.Moved ||
                response.StatusCode == HttpStatusCode.Redirect) &&
                response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase)) 
            {
                using (Stream inputStream = response.GetResponseStream())
                using (Stream outputStream = File.OpenWrite(fileName))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    do
                    {
                        bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                        outputStream.Write(buffer, 0, bytesRead);
                    } while (bytesRead != 0);
                }
            }
        }

How can I use different certificates on specific connections?

I read through LOTS of places online to solve this thing. This is the code I wrote to make it work:

ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());

app.certificateString is a String that contains the Certificate, for example:

static public String certificateString=
        "-----BEGIN CERTIFICATE-----\n" +
        "MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
        "BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
        ... a bunch of characters...
        "5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
        "-----END CERTIFICATE-----";

I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.

How can I create a carriage return in my C# string

Along with Environment.NewLine and the literal \r\n or just \n you may also use a verbatim string in C#. These begin with @ and can have embedded newlines. The only thing to keep in mind is that " needs to be escaped as "". An example:

string s = @"This is a string
that contains embedded new lines,
that will appear when this string is used."

Get the current year in JavaScript

Such is how I have it embedded and outputted to my HTML web page:

<div class="container">
    <p class="text-center">Copyright &copy; 
        <script>
            var CurrentYear = new Date().getFullYear()
            document.write(CurrentYear)
        </script>
    </p>
</div>

Output to HTML page is as follows:

Copyright © 2018

Is arr.__len__() the preferred way to get the length of an array in Python?

len(list_name) function takes list as a parameter and it calls list's __len__() function.

Is there a way I can capture my iPhone screen as a video?

I used ScreenFlow to record the Simulator, and zoomed it and added static images as necessary. I then embedded the movie in an iPhone frame on my website. Turned out okay. See the Tweeps page for the result.

Bootstrap $('#myModal').modal('show') is not working

After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.

Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using

setTimeout(() => {  $('#modalID').modal('show'); }, 500);

Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it

Disable and later enable all table indexes in Oracle

Combining the two answers:

First create sql to make all index unusable:

alter session set skip_unusable_indexes = true;
select 'alter index ' || u.index_name || ' unusable;' from user_indexes u;

Do import...

select 'alter index ' || u.index_name || ' rebuild online;' from user_indexes u;

jQuery AutoComplete Trigger Change Event

They are binding to keydown in the autocomplete source, so triggering the keydown will case it to update.

$("#CompanyList").trigger('keydown');

They aren't binding to the 'change' event because that only triggers at the DOM level when the form field loses focus. The autocomplete needs to respond faster than 'lost focus' so it has to bind to a key event.

Doing this:

companyList.autocomplete('option','change').call(companyList);

Will cause a bug if the user retypes the exact option that was there before.

How can I render HTML from another file in a React component?

You could do it if template is a react component.

Template.js

var React = require('react');

var Template = React.createClass({
    render: function(){
        return (<div>Mi HTML</div>);
    }
});

module.exports = Template;

MainComponent.js

var React = require('react');
var ReactDOM = require('react-dom');
var injectTapEventPlugin = require("react-tap-event-plugin");
var Template = require('./Template');

//Needed for React Developer Tools
window.React = React;

//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

var MainComponent = React.createClass({
    render: function() {
        return(
            <Template/>
        );
    }
});

// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(
  <MainComponent />,
  document.getElementById('app')
 );

And if you are using Material-UI, for compatibility use Material-UI Components, no normal inputs.

UTF-8 all the way through

In PHP, you'll need to either use the multibyte functions, or turn on mbstring.func_overload. That way things like strlen will work if you have characters that take more than one byte.

You'll also need to identify the character set of your responses. You can either use AddDefaultCharset, as above, or write PHP code that returns the header. (Or you can add a META tag to your HTML documents.)

EnterKey to press button in VBA Userform

Be sure to avoid "magic numbers" whenever possible, either by defining your own constants, or by using the built-in vbXXX constants.

In this instance we could use vbKeyReturn to indicate the enter key's keycode (replacing YourInputControl and SubToBeCalled).

   Private Sub YourInputControl_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = vbKeyReturn Then
             SubToBeCalled
        End If
   End Sub

This prevents a whole category of compatibility issues and simple typos, especially because VBA capitalizes identifiers for us.

Cheers!

Create an array with same element repeated multiple times

You can do it like this:

function fillArray(value, len) {
  if (len == 0) return [];
  var a = [value];
  while (a.length * 2 <= len) a = a.concat(a);
  if (a.length < len) a = a.concat(a.slice(0, len - a.length));
  return a;
}

It doubles the array in each iteration, so it can create a really large array with few iterations.


Note: You can also improve your function a lot by using push instead of concat, as concat will create a new array each iteration. Like this (shown just as an example of how you can work with arrays):

function fillArray(value, len) {
  var arr = [];
  for (var i = 0; i < len; i++) {
    arr.push(value);
  }
  return arr;
}

Programmatically switching between tabs within Swift

Just to update, following iOS 13, we now have SceneDelegates. So one might choose to put the desired tab selection in SceneDelegate.swift as follows:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, 
               willConnectTo session: UISceneSession, 
               options connectionOptions: UIScene.ConnectionOptions) {

        guard let _ = (scene as? UIWindowScene) else { return }

        if let tabBarController = self.window!.rootViewController as? UITabBarController {
            tabBarController.selectedIndex = 1
        }

    }

POST string to ASP.NET Web Api application - returns null

I use this code to post HttpRequests.

/// <summary>
        /// Post this message.
        /// </summary>
        /// <param name="url">URL of the document.</param>
        /// <param name="bytes">The bytes.</param>
        public T Post<T>(string url, byte[] bytes)
    {
        T item;
        var request = WritePost(url, bytes);

        using (var response = request.GetResponse() as HttpWebResponse)
        {
            item = DeserializeResponse<T>(response);
            response.Close();
        }

        return item;
    }

    /// <summary>
    /// Writes the post.
    /// </summary>
    /// <param name="url">The URL.</param>
    /// <param name="bytes">The bytes.</param>
    /// <returns></returns>
    private static HttpWebRequest WritePost(string url, byte[] bytes)
    {
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
        Stream stream = null;
        try
        {
            request.Headers.Clear();
            request.PreAuthenticate = true;
            request.Connection = null;
            request.Expect = null;
            request.KeepAlive = false;
            request.ContentLength = bytes.Length;
            request.Timeout = -1;
            request.Method = "POST";
            stream = request.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
        }
        catch (Exception e)
        {
            GetErrorResponse(url, e);
        }
        finally
        {
            if (stream != null)
            {
                stream.Flush();
                stream.Close();
            }
        }
        return request;
    }

In regards to your code, try it without the content.Type (request.ContentType = "application/x-www-form-urlencoded";)

update

I believe the problem lies with how you are trying to retrieve the value. When you do a POST and send bytes via the Stream, they will not be passed into the action as a parameter. You'll need to retrieve the bytes via the stream on the server.

On the server, try getting the bytes from stream. The following code is what I use.

     /// <summary> Gets the body. </summary>
     /// <returns> The body. </returns>
     protected byte[] GetBytes()
     {
       byte[] bytes;
        using (var binaryReader = new BinaryReader(Request.InputStream))
        {
            bytes = binaryReader.ReadBytes(Request.ContentLength);
        }

         return bytes;
     }

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

I had the same issue and found out that my code was using the injection before it was initialized.

services.AddControllers(); // Will cause a problem if you use your IBloggerRepository in there since it's defined after this line.
services.AddScoped<IBloggerRepository, BloggerRepository>();

I know it has nothing to do with the question, but since I was sent to this page, I figure out it my be useful to someone else.

What is the default encoding of the JVM?

To get default java settings just use :

java -XshowSettings 

Python: create dictionary using dict() with integer keys?

There are also these 'ways':

>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}

How to create a HTTP server in Android?

Another server you can try http://tjws.sf.net, actually it already provides Android enabled version.

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

Append a dictionary to a dictionary

The answer I want to give is "use collections.ChainMap", but I just discovered that it was only added in Python 3.3: https://docs.python.org/3.3/library/collections.html#chainmap-objects

You can try to crib the class from the 3.3 source though: http://hg.python.org/cpython/file/3.3/Lib/collections/init.py#l763

Here is a less feature-full Python 2.x compatible version (same author): http://code.activestate.com/recipes/305268-chained-map-lookups/

Instead of expanding/overwriting one dictionary with another using dict.merge, or creating an additional copy merging both, you create a lookup chain that searches both in order. Because it doesn't duplicate the mappings it wraps ChainMap uses very little memory, and sees later modifications to any sub-mapping. Because order matters you can also use the chain to layer defaults (i.e. user prefs > config > env).

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

I fixed the same problem on Google Chrome with the following:

  1. Choose Customize and control Google Chrome (the button in the top right corner).

  2. Choose Settings.

  3. Go to Extensions.

  4. Unmark all the extensions there. (They should show as Enable instead of Enabled.)

Scroll to the top of the page using JavaScript?

A lot of users recommend selecting both the html and body tags for cross-browser compatibility, like so:

$('html, body').animate({ scrollTop: 0 }, callback);

This can trip you up though if you're counting on your callback running only once. It will in fact run twice because you've selected two elements.

If that is a problem for you, you can do something like this:

function scrollToTop(callback) {
    if ($('html').scrollTop()) {
        $('html').animate({ scrollTop: 0 }, callback);
        return;
    }

    $('body').animate({ scrollTop: 0 }, callback);
}

The reason this works is in Chrome $('html').scrollTop() returns 0, but not in other browsers such as Firefox.

If you don't want to wait for the animation to complete in the case that the scrollbar is already at the top, try this:

function scrollToTop(callback) {
    if ($('html').scrollTop()) {
        $('html').animate({ scrollTop: 0 }, callback);
        return;
    }

    if ($('body').scrollTop()) {
        $('body').animate({ scrollTop: 0 }, callback);
        return;
    }

    callback();
}

Why use 'git rm' to remove a file instead of 'rm'?

git rm will remove the file from the index and working directory ( only index if you used --cached ) so that the deletion is staged for next commit.

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

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

Try this one

/**
 * Get the value of a querystring
 * @param  {String} field The field to get the value of
 * @param  {String} url   The URL to get the value from (optional)
 * @return {String}       The field value
 */
var getQueryString = function ( field, url ) {
    var href = url ? url : window.location.href;
    var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
    var string = reg.exec(href);
    return string ? string[1] : null;
};

Let’s say your URL is http://example.com&this=chicken&that=sandwich. You want to get the value of this, that, and another.

var thisOne = getQueryString('this'); // returns 'chicken'
var thatOne = getQueryString('that'); // returns 'sandwich'
var anotherOne = getQueryString('another'); // returns null

If you want to use a URL other than the one in the window, you can pass one in as a second argument.

var yetAnotherOne = getQueryString('example', 'http://another-example.com&example=something'); // returns 'something'

Reference

Is null reference possible?

The answer depends on your view point:


If you judge by the C++ standard, you cannot get a null reference because you get undefined behavior first. After that first incidence of undefined behavior, the standard allows anything to happen. So, if you write *(int*)0, you already have undefined behavior as you are, from a language standard point of view, dereferencing a null pointer. The rest of the program is irrelevant, once this expression is executed, you are out of the game.


However, in practice, null references can easily be created from null pointers, and you won't notice until you actually try to access the value behind the null reference. Your example may be a bit too simple, as any good optimizing compiler will see the undefined behavior, and simply optimize away anything that depends on it (the null reference won't even be created, it will be optimized away).

Yet, that optimizing away depends on the compiler to prove the undefined behavior, which may not be possible to do. Consider this simple function inside a file converter.cpp:

int& toReference(int* pointer) {
    return *pointer;
}

When the compiler sees this function, it does not know whether the pointer is a null pointer or not. So it just generates code that turns any pointer into the corresponding reference. (Btw: This is a noop since pointers and references are the exact same beast in assembler.) Now, if you have another file user.cpp with the code

#include "converter.h"

void foo() {
    int& nullRef = toReference(nullptr);
    cout << nullRef;    //crash happens here
}

the compiler does not know that toReference() will dereference the passed pointer, and assume that it returns a valid reference, which will happen to be a null reference in practice. The call succeeds, but when you try to use the reference, the program crashes. Hopefully. The standard allows for anything to happen, including the appearance of pink elephants.

You may ask why this is relevant, after all, the undefined behavior was already triggered inside toReference(). The answer is debugging: Null references may propagate and proliferate just as null pointers do. If you are not aware that null references can exist, and learn to avoid creating them, you may spend quite some time trying to figure out why your member function seems to crash when it's just trying to read a plain old int member (answer: the instance in the call of the member was a null reference, so this is a null pointer, and your member is computed to be located as address 8).


So how about checking for null references? You gave the line

if( & nullReference == 0 ) // null reference

in your question. Well, that won't work: According to the standard, you have undefined behavior if you dereference a null pointer, and you cannot create a null reference without dereferencing a null pointer, so null references exist only inside the realm of undefined behavior. Since your compiler may assume that you are not triggering undefined behavior, it can assume that there is no such thing as a null reference (even though it will readily emit code that generates null references!). As such, it sees the if() condition, concludes that it cannot be true, and just throw away the entire if() statement. With the introduction of link time optimizations, it has become plain impossible to check for null references in a robust way.


TL;DR:

Null references are somewhat of a ghastly existence:

Their existence seems impossible (= by the standard),
but they exist (= by the generated machine code),
but you cannot see them if they exist (= your attempts will be optimized away),
but they may kill you unaware anyway (= your program crashes at weird points, or worse).
Your only hope is that they don't exist (= write your program to not create them).

I do hope that will not come to haunt you!

How to import a CSS file in a React Component

You can also use the required module.

require('./componentName.css');
const React = require('react');

Postgresql -bash: psql: command not found

If you are using the Postgres Mac app (by Heroku) and Bundler, you can add the pg_config directly inside the app, to your bundle.

bundle config build.pg --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config

...then run bundle again.

Note: check the version first using the following.

ls /Applications/Postgres.app/Contents/Versions/

What's the difference between "Layers" and "Tiers"?

Layers are logical separation of related-functionality[code] within an application, Communication between layers is explicit and loosely coupled. [Presentation logic,Application logic,Data Access logic]

Tiers are Physical separation of layers [which get hosted on Individual servers] in an individual computer(process).

enter image description here

As shown in diagram:

1-Tier & 3-Layers « App Logic  with out DB access store data in a files.
2-Tier & 3-Layers « App Logic & DataStorage-box.
2-Tier & 2-Layers « Browser View[php] & DataStorage[procedures]
2-Tier & 1-Layers « Browser View[php] & DataStorage, query sending is common.
3-Tier & n-Layer  « Browser View[php], App Logic[jsp], DataStorage

n-Tier advantages:
Better Security
Scalability : As your organisation grows You can scale up your DB-Tier with DB-Clustering with out touching other tiers.
Maintainability : Web designer can change the View-code, with out touching the other layers on the other tiers.
Easily Upgrade or Enhance [Ex: You can add Additional Application Code, Upgrade Storage Area, or even add Multiple presentation Layers for Separate devises like mobile, tablet, pc]

Maven Run Project

The above mentioned answers are correct but I am simplifying it for noobs like me.Go to your project's pom file. Add a new property exec.mainClass and give its value as the class which contains your main method. For me it was DriverClass in mainpkg. Change it as per your project. enter image description here

Having done this navigate to the folder that contains your project's pom.xml and run this on the command prompt mvn exec:java. This should call the main method.

INSERT INTO...SELECT for all MySQL columns

don't you need double () for the values bit? if not try this (although there must be a better way

insert into this_table_archive (id, field_1, field_2, field_3) 
values
((select id from this_table where entry_date < '2001-01-01'), 
((select field_1 from this_table where entry_date < '2001-01-01'), 
((select field_2 from this_table where entry_date < '2001-01-01'), 
((select field_3 from this_table where entry_date < '2001-01-01'));

Android Error - Open Failed ENOENT

Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt"); to open a stream to this file.

What is the easiest way to initialize a std::vector with hardcoded elements?

Just thought I'd toss in my $0.02. I tend to declare this:

template< typename T, size_t N >
std::vector<T> makeVector( const T (&data)[N] )
{
    return std::vector<T>(data, data+N);
}

in a utility header somewhere and then all that's required is:

const double values[] = { 2.0, 1.0, 42.0, -7 };
std::vector<double> array = makeVector(values);

But I can't wait for C++0x. I'm stuck because my code must also compile in Visual Studio. Boo.

Bash: Strip trailing linebreak from output

If you want to print output of anything in Bash without end of line, you echo it with the -n switch.

If you have it in a variable already, then echo it with the trailing newline cropped:

$ testvar=$(wc -l < log.txt)
$ echo -n $testvar

Or you can do it in one line, instead:

$ echo -n $(wc -l < log.txt)

stdlib and colored output in C

You can assign one color to every functionality to make it more useful.

#define Color_Red "\33[0:31m\\]" // Color Start
#define Color_end "\33[0m\\]" // To flush out prev settings
#define LOG_RED(X) printf("%s %s %s",Color_Red,X,Color_end)

foo()
{
LOG_RED("This is in Red Color");
}

Like wise you can select different color codes and make this more generic.

Case Statement Equivalent in R

case_when(), which was added to dplyr in May 2016, solves this problem in a manner similar to memisc::cases().

For example:

library(dplyr)
mtcars %>% 
  mutate(category = case_when(
    .$cyl == 4 & .$disp < median(.$disp) ~ "4 cylinders, small displacement",
    .$cyl == 8 & .$disp > median(.$disp) ~ "8 cylinders, large displacement",
    TRUE ~ "other"
  )
)

As of dplyr 0.7.0,

mtcars %>% 
  mutate(category = case_when(
    cyl == 4 & disp < median(disp) ~ "4 cylinders, small displacement",
    cyl == 8 & disp > median(disp) ~ "8 cylinders, large displacement",
    TRUE ~ "other"
  )
)

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

My Solution was to 'Uri.parse' the File Path as String, instead of using Uri.fromFile().

String storage = Environment.getExternalStorageDirectory().toString() + "/test.txt";
File file = new File(storage);
Uri uri;
if (Build.VERSION.SDK_INT < 24) {
    uri = Uri.fromFile(file);
} else {
    uri = Uri.parse(file.getPath()); // My work-around for new SDKs, worked for me in Android 10 using Solid Explorer Text Editor as the external editor.
}
Intent viewFile = new Intent(Intent.ACTION_VIEW);
viewFile.setDataAndType(uri, "text/plain");
startActivity(viewFile);

Seems that fromFile() uses A file pointer, which I suppose could be insecure when memory addresses are exposed to all apps. But A file path String never hurt anybody, so it works without throwing FileUriExposedException.

Tested on API levels 9 to 29! Successfully opens the text file for editing in another app. Does not require FileProvider, nor the Android Support Library at all.

How to initialize private static members in C++?

If you want to initialize some compound type (f.e. string) you can do something like that:

class SomeClass {
  static std::list<string> _list;

  public:
    static const std::list<string>& getList() {
      struct Initializer {
         Initializer() {
           // Here you may want to put mutex
           _list.push_back("FIRST");
           _list.push_back("SECOND");
           ....
         }
      }
      static Initializer ListInitializationGuard;
      return _list;
    }
};

As the ListInitializationGuard is a static variable inside SomeClass::getList() method it will be constructed only once, which means that constructor is called once. This will initialize _list variable to value you need. Any subsequent call to getList will simply return already initialized _list object.

Of course you have to access _list object always by calling getList() method.

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

For Sublime Text 3:

defaults write com.apple.LaunchServices LSHandlers -array-add '{LSHandlerContentType=public.plain-text;LSHandlerRoleAll=com.sublimetext.3;}'

See Set TextMate as the default text editor on Mac OS X for details.

Remove .php extension with .htaccess

Here's a method if you want to do it for just one specific file:

RewriteRule ^about$ about.php [L]

Ref: http://css-tricks.com/snippets/htaccess/remove-file-extention-from-urls/

pip installing in global site-packages instead of virtualenv

It's also worth checking that you didn't modify somehow the path to your virtualenv.

In that case the first line in bin/pip (and the rest of the executables) would have an incorrect path.

You can either edit these files and fix the path or remove and install again the virtualenv.

history.replaceState() example?

Indeed this is a bug, although intentional for 2 years now. The problem lies with some unclear specs and the complexity when document.title and back/forward are involved.

See bug reference on Webkit and Mozilla. Also Opera on the introduction of History API said it wasn't using the title parameter and probably still doesn't.

Currently the 2nd argument of pushState and replaceState — the title of the history entry — isn't used in Opera's implementation, but may be one day.

Potential solution

The only way I see is to alter the title element and use pushState instead:

document.getElementsByTagName('title')[0].innerHTML = 'bar';
window.history.pushState( {} , 'bar', '/bar' );

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

I found this question after searching for the first line of this error:

dyld: Library not loaded: /opt/local/lib/libcrypto.1.0.0.dylib
  Referenced from: /opt/local/lib/libgssapi_krb5.2.2.dylib
  Reason: image not found
Abort trap: 6

That I saw not from using vapor, but instead, as the result of using ssh and scp and git after upgrading some packages.

I think it's unwise to downgrade most packages as @Smokie and others suggested doing with openssl (especially for security-related packages).

So I generalized the answer posted by @MichalCichon on solving the problem with install_name_tool and that seems to have taken care of my issue (at least for now with ssh and scp; I think I'll be able to use a variant of this solution if the problem comes up again with another executable).

Because it was the non-existent /opt/local/lib/libcrypto.1.0.0.dylib library that was missing, and because I had a /opt/local/lib/libcrypto.1.1.dylib after upgrading, and because ssh and scp were referencing /opt/local/lib/libgssapi_krb5.2.2.dylib in an attempt to find /opt/local/lib/libcrypto.1.0.0.dylib, I just used install_name_tool like this:

$ sudo install_name_tool -change /opt/local/lib/libcrypto.1.0.0.dylib\
/opt/local/lib/libcrypto.1.1.dylib\
/opt/local/lib/libgssapi_krb5.2.2.dylib

Then tried running ssh again. It failed again, but this time with a different error:

dyld: Library not loaded: /opt/local/lib/libcrypto.1.0.0.dylib
  Referenced from: /opt/local/lib/libkrb5.3.3.dylib
  Reason: image not found
Abort trap: 6

So then I did:

$ sudo install_name_tool -change /opt/local/lib/libcrypto.1.0.0.dylib\
/opt/local/lib/libcrypto.1.1.dylib\
/opt/local/lib/libkrb5.3.3.dylib

and tried ssh again. Again it failed, but with yet another different error:

dyld: Library not loaded: /opt/local/lib/libcrypto.1.0.0.dylib
  Referenced from: /opt/local/lib/libk5crypto.3.1.dylib
  Reason: image not found
Abort trap: 6

So then I did:

$ sudo install_name_tool -change /opt/local/lib/libcrypto.1.0.0.dylib\
/opt/local/lib/libcrypto.1.1.dylib\
/opt/local/lib/libk5crypto.3.1.dylib

and tried ssh again. Again it failed, but with yet another different error:

dyld: Library not loaded: /opt/local/lib/libcrypto.1.0.0.dylib
  Referenced from: /opt/local/lib/libkrb5support.1.1.dylib
  Reason: image not found
Abort trap: 6

So then I did:

$ sudo install_name_tool -change /opt/local/lib/libcrypto.1.0.0.dylib\
/opt/local/lib/libcrypto.1.1.dylib\
/opt/local/lib/libkrb5support.1.1.dylib

and tried ssh again. Finally, ssh and scp and git resumed working as expected.

Thank you @MichalCichon for a great answer that I was able to generalize beyond vapor to allow myself to continue using ssh without downgrading my openssl!

Why is __init__() always called after __new__()?

__new__ is static class method, while __init__ is instance method. __new__ has to create the instance first, so __init__ can initialize it. Note that __init__ takes self as parameter. Until you create instance there is no self.

Now, I gather, that you're trying to implement singleton pattern in Python. There are a few ways to do that.

Also, as of Python 2.6, you can use class decorators.

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
  ...

Call function with setInterval in jQuery?

setInterval(function() {
    updatechat();
}, 2000);

function updatechat() {
    alert('hello world');
}

Where are the Properties.Settings.Default stored?

it is saved in your Documents and Settings\%user%\Local Settings\Application Data......etc search for a file called user.config there

the location may change however.

How to protect Excel workbook using VBA?

  1. in your sample code you must remove the brackets, because it's not a functional assignment; also for documentary reasons I would suggest you use the := notation (see code sample below)

    1. Application.Thisworkbook refers to the book containing the VBA code, not necessarily the book containing the data, so be cautious.

Express the sheet you're working on as a sheet object and pass it, together with a logical variable to the following sub:

Sub SetProtectionMode(MySheet As Worksheet, ProtectionMode As Boolean)

    If ProtectionMode Then
        MySheet.Protect DrawingObjects:=True, Contents:=True, _
                        AllowSorting:=True, AllowFiltering:=True
    Else
        MySheet.Unprotect
    End If
End Sub

Within the .Protect method you can define what you want to allow/disallow. This code block will switch protection on/off - without password in this example, you can add it as a parameter or hardcoded within the Sub. Anyway somewhere the PW will be hardcoded. If you don't want this, just call the Protection Dialog window and let the user decide what to do:

Application.Dialogs(xlDialogProtectDocument).Show

Hope that helps

Good luck - MikeD

Only numbers. Input number in React

2019 Answer Late, but hope it helps somebody

This will make sure you won't get null on an empty textfield

  • Textfield value is always 0
  • When backspacing, you will end with 0
  • When value is 0 and you start typing, 0 will be replaced with the actual number
// This will make sure that value never is null when textfield is empty

const minimum = 0;   

export default (props) => {
    const [count, changeCount] = useState(minimum);

    function validate(count) {
        return parseInt(count) | minimum
    }

    function handleChangeCount(count) {
        changeCount(validate(count))
    }

    return (
        <Form>
            <FormGroup>
                <TextInput
                    type="text"
                    value={validate(count)}
                    onChange={handleChangeCount}
                />
            </FormGroup>
            <ActionGroup>
                <Button type="submit">submit form</Button>
            </ActionGroup>
        </Form>
    );
};

kill -3 to get java thread dump

In Jboss you can perform the following

nohup $JBOSS_HOME/bin/run.sh -c  yourinstancename $JBOSS_OPTS >> console-$(date +%Y%m%d).out  2>&1 < /dev/null &
kill -3 <java_pid>

This will redirect your output/threadump to the file console specified in the above command.

Contain form within a bootstrap popover?

like this Working demo http://jsfiddle.net/7e2XU/21/show/# * Update: http://jsfiddle.net/kz5kjmbt/

 <div class="container">
    <div class="row" style="padding-top: 240px;"> <a href="#" class="btn btn-large btn-primary" rel="popover" data-content='
<form id="mainForm" name="mainForm" method="post" action="">
    <p>
        <label>Name :</label>
        <input type="text" id="txtName" name="txtName" />
    </p>
    <p>
        <label>Address 1 :</label>
        <input type="text" id="txtAddress" name="txtAddress" />
    </p>
    <p>
        <label>City :</label>
        <input type="text" id="txtCity" name="txtCity" />
    </p>
    <p>
        <input type="submit" name="Submit" value="Submit" />
    </p>
</form>
 data-placement="top" data-original-title="Fill in form">Open form</a>

    </div>
</div>

JavaScript code:

    $('a[rel=popover]').popover({
      html: 'true',
      placement: 'right'
    })

ScreenShot

working updated fiddle screenshot

Using C# to check if string contains a string in string array

You can try this solution as well.

string[] nonSupportedExt = { ".3gp", ".avi", ".opus", ".wma", ".wav", ".m4a", ".ac3", ".aac", ".aiff" };
        
bool valid = Array.Exists(nonSupportedExt,E => E == ".Aac".ToLower());

functional way to iterate over range (ES6/7)

One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:

Array(8).fill().map((_, i) => i * i);

Python script to do something at the same time every day

APScheduler might be what you are after.

from datetime import date
from apscheduler.scheduler import Scheduler

# Start the scheduler
sched = Scheduler()
sched.start()

# Define the function that is to be executed
def my_job(text):
    print text

# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)

# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])

# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])

https://apscheduler.readthedocs.io/en/latest/

You can just get it to schedule another run by building that into the function you are scheduling.

React - Display loading screen while DOM is rendering?

This will happen before ReactDOM.render() takes control of the root <div>. I.e. your App will not have been mounted up to that point.

So you can add your loader in your index.html file inside the root <div>. And that will be visible on the screen until React takes over.

You can use whatever loader element works best for you (svg with animation for example).

You don't need to remove it on any lifecycle method. React will replace any children of its root <div> with your rendered <App/>, as we can see in the GIF below.

Example on CodeSandbox

enter image description here

index.html

<head>
  <style>
    .svgLoader {
      animation: spin 0.5s linear infinite;
      margin: auto;
    }
    .divLoader {
      width: 100vw;
      height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  </style>
</head>

<body>
  <div id="root">
    <div class="divLoader">
      <svg class="svgLoader" viewBox="0 0 1024 1024" width="10em" height="10em">
        <path fill="lightblue"
          d="PATH FOR THE LOADER ICON"
        />
      </svg>
    </div>
  </div>
</body>

index.js

Using debugger to inspect the page before ReactDOM.render() runs.

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

debugger; // TO INSPECT THE PAGE BEFORE 1ST RENDER

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

How store a range from excel into a Range variable?

What is currentWorksheet? It works if you use the built-in ActiveSheet.

dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

The smallest difference between 2 Angles

Arithmetical (as opposed to algorithmic) solution:

angle = Pi - abs(abs(a1 - a2) - Pi);

What are best practices that you use when writing Objective-C and Cocoa?

Declared Properties

You should typically use the Objective-C 2.0 Declared Properties feature for all your properties. If they are not public, add them in a class extension. Using declared properties makes the memory management semantics immediately clear, and makes it easier for you to check your dealloc method -- if you group your property declarations together you can quickly scan them and compare with the implementation of your dealloc method.

You should think hard before not marking properties as 'nonatomic'. As The Objective C Programming Language Guide notes, properties are atomic by default, and incur considerable overhead. Moreover, simply making all your properties atomic does not make your application thread-safe. Also note, of course, that if you don't specify 'nonatomic' and implement your own accessor methods (rather than synthesising them), you must implement them in an atomic fashion.

Setting a width and height on an A tag

You need to make your anchor display: block or display: inline-block; and then it will accept the width and height values.

How do I capture the output of a script if it is being ran by the task scheduler?

To supplement @user2744787's answer, here is a screenshot to show how to use cmd with arguments in a Scheduled Task:

Scheduled Task cmd output to logfile

Program/script: cmd

Add arguments: /c run_with_default_port.bat > IMQuantWebServices.log

Convert String to Float in Swift

I found another way to take a input value of a UITextField and cast it to a float:

    var tempString:String?
    var myFloat:Float?

    @IBAction func ButtonWasClicked(_ sender: Any) {
       tempString = myUITextField.text
       myFloat = Float(tempString!)!
    }

'dependencies.dependency.version' is missing error, but version is managed in parent

What just worked for was to delete the settings.xml in the .m2 folder: this file was telling the project to look for a versión of spring mvc and web that didn't exist.

How to format a phone number with jQuery

I found this question while googling for a way to auto-format phone numbers via a jQuery plugin. The accepted answer was not ideal for my needs and a lot has happened in the 6 years since it was originally posted. I eventually found the solution and am documenting it here for posterity.

Problem

I would like my phone number html input field to auto-format (mask) the value as the user types.

Solution

Check out Cleave.js. It is a very powerful/flexible and easy way to solve this problem, and many other data masking issues.

Formatting a phone number is as easy as:

var cleave = new Cleave('.input-element', {
    phone: true,
    phoneRegionCode: 'US'
});

How to verify element present or visible in selenium 2 (Selenium WebDriver)

You could try something like:

    WebElement rxBtn = driver.findElement(By.className("icon-rx"));
    WebElement otcBtn = driver.findElement(By.className("icon-otc"));
    WebElement herbBtn = driver.findElement(By.className("icon-herb"));

    Assert.assertEquals(true, rxBtn.isDisplayed());
    Assert.assertEquals(true, otcBtn.isDisplayed());
    Assert.assertEquals(true, herbBtn.isDisplayed());

This is just an example. Basically you declare and define the WebElement variables you wish to use and then Assert whether or not they are displayed. This is using TestNG Assertions.