Programs & Examples On #Matlab

MATLAB is a high-level language and interactive programming environment for numerical computation and visualization developed by MathWorks. Questions should be tagged with either [tag:matlab] or [tag:octave], but not both, unless the question explicitly involves both packages. When using this tag, please mention the MATLAB release you're working with (e.g. R2017a).

How to plot a 2D FFT in Matlab?

Here is an example from my HOW TO Matlab page:

close all; clear all;

img   = imread('lena.tif','tif');
imagesc(img)
img   = fftshift(img(:,:,2));
F     = fft2(img);

figure;

imagesc(100*log(1+abs(fftshift(F)))); colormap(gray); 
title('magnitude spectrum');

figure;
imagesc(angle(F));  colormap(gray);
title('phase spectrum');

This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.

ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say

img = imread('ngc6543a.jpg');

and it will work. I used an older version of Matlab to make the above example and just copied it here.

On the scaling factor

When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c value in the equation

s = c log(1+r) 

There is no known way to pre detrmine this scale that I know. Just need to try different values to get on you like. I used 100 in the above example.

enter image description here

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);

Optional args in MATLAB functions

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?

How to display (print) vector in Matlab?

Here's another approach that takes advantage of Matlab's strjoin function. With strjoin it's easy to customize the delimiter between values.

x = [1, 2, 3];
fprintf('Answer: (%s)\n', strjoin(cellstr(num2str(x(:))),', '));

This results in: Answer: (1, 2, 3)

Array of Matrices in MATLAB

If all of the matrices are going to be the same size (i.e. 500x800), then you can just make a 3D array:

nUnknown;  % The number of unknown arrays
myArray = zeros(500,800,nUnknown);

To access one array, you would use the following syntax:

subMatrix = myArray(:,:,3);  % Gets the third matrix

You can add more matrices to myArray in a couple of ways:

myArray = cat(3,myArray,zeros(500,800));
% OR
myArray(:,:,nUnknown+1) = zeros(500,800);

If each matrix is not going to be the same size, you would need to use cell arrays like Hosam suggested.

EDIT: I missed the part about running out of memory. I'm guessing your nUnknown is fairly large. You may have to switch the data type of the matrices (single or even a uintXX type if you are using integers). You can do this in the call to zeros:

myArray = zeros(500,800,nUnknown,'single');

Loop through files in a folder in matlab

At first, you must specify your path, the path that your *.csv files are in there

path = 'f:\project\dataset'

You can change it based on your system.

then,

use dir function :

files = dir (strcat(path,'\*.csv'))

L = length (files);

for i=1:L
   image{i}=csvread(strcat(path,'\',file(i).name));   
   % process the image in here
end

pwd also can be used.

How to apply a low-pass or high-pass filter to an array in Matlab?

Look at the filter function.

If you just need a 1-pole low-pass filter, it's

xfilt = filter(a, [1 a-1], x);

where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.

Here's the corresponding high-pass filter:

xfilt = filter([1-a a-1],[1 a-1], x);

If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.

how to stop a running script in Matlab

if you are running your matlab on linux, you can terminate the matlab by command in linux consule. first you should find the PID number of matlab by this code:

top

then you can use this code to kill matlab: kill

example: kill 58056

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

How to create an executable .exe file from a .m file

Try:

mcc -m yourfile

Also see help mcc

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

I have try with the SCFRench and with the Ru Hasha on octave.

And finally it works: but I have done some modification

function message = makefuns
    assignin('base','fun1', @fun1);   % Ru Hasha
    assignin('base', 'fun2', @fun2);  % Ru Hasha
    message.fun1=@fun1;               % SCFrench
    message.fun2=@fun2;               % SCFrench
end

function y=fun1(x)
    y=x;
end

function z=fun2
    z=1;
end

Can be called in other 'm' file:

printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());

update:

I added an answer because neither the +72 nor the +20 worked in octave for me. The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).

How to get the number of columns in a matrix?

Use the size() function.

>> size(A,2)

Ans =

   3

The second argument specifies the dimension of which number of elements are required which will be '2' if you want the number of columns.

Official documentation.

MATLAB error: Undefined function or method X for input arguments of type 'double'

As others have pointed out, this is very probably a problem with the path of the function file not being in Matlab's 'path'.

One easy way to verify this is to open your function in the Editor and press the F5 key. This would make the Editor try to run the file, and in case the file is not in path, it will prompt you with a message box. Choose Add to Path in that, and you must be fine to go.

One side note: at the end of the above process, Matlab command window will give an error saying arguments missing: obviously, we didn't provide any arguments when we tried to run from the editor. But from now on you can use the function from the command line giving the correct arguments.

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

When iterating over cell arrays of strings, the loop variable (let's call it f) becomes a single-element cell array. Having to write f{1} everywhere gets tedious, and modifying the loop variable provides a clean workaround.

% This example transposes each field of a struct.
s.a = 1:3;
s.b = zeros(2,3);
s % a: [1 2 3]; b: [2x3 double]
for f = fieldnames(s)'
    s.(f{1}) = s.(f{1})';
end
s % a: [3x1 double]; b: [3x2 double]

% Redefining f simplifies the indexing.
for f = fieldnames(s)'
    f = f{1};
    s.(f) = s.(f)';
end
s % back to a: [1 2 3]; b: [2x3 double]

Understanding Matlab FFT example

It sounds like you need to some background reading on what an FFT is (e.g. http://en.wikipedia.org/wiki/FFT). But to answer your questions:

Why does the x-axis (frequency) end at 500?

Because the input vector is length 1000. In general, the FFT of a length-N input waveform will result in a length-N output vector. If the input waveform is real, then the output will be symmetrical, so the first 501 points are sufficient.

Edit: (I didn't notice that the example padded the time-domain vector.)

The frequency goes to 500 Hz because the time-domain waveform is declared to have a sample-rate of 1 kHz. The Nyquist sampling theorem dictates that a signal with sample-rate fs can support a (real) signal with a maximum bandwidth of fs/2.

How do I know the frequencies are between 0 and 500?

See above.

Shouldn't the FFT tell me, in which limits the frequencies are?

No.

Does the FFT only return the amplitude value without the frequency?

The FFT simply assigns an amplitude (and phase) to every frequency bin.

how to open .mat file without using MATLAB?

I didn't use it myself but heard of a simple tool (not a text editor) for this so it is definitely possible without setting up a programming environment (by installing octave or python).

A quick search hints that it was possible with total commander. (A lightweight tool with an easy point and click interface)

I would not be surprised if this still works, but I can't guarantee it.

Matlab: Running an m-file from command-line

Here is what I would use instead, to gracefully handle errors from the script:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "try, run('C:\<a long path here>\mfile.m'), catch, exit, end, exit"

If you want more verbosity:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "try, run('C:\<a long path here>\mfile.m'), catch me, fprintf('%s / %s\n',me.identifier,me.message), end, exit"

I found the original reference here. Since original link is now gone, here is the link to an alternate newreader still alive today:

How to create a new figure in MATLAB?

figure;
plot(something);

or

figure(2);
plot(something);
...
figure(3);
plot(something else);
...

etc.

How can I find the maximum value and its index in array in MATLAB?

You can use max() to get the max value. The max function can also return the index of the maximum value in the vector. To get this, assign the result of the call to max to a two element vector instead of just a single variable.

e.g. z is your array,

>> [x, y] = max(z)

x =

7

y =

4

Here, 7 is the largest number at the 4th position(index).

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

I did it this way,

2D

% vectors I want to plot as rows (XSTART, YSTART) (XDIR, YDIR)
rays = [
  1 2   1 0 ;
  3 3   0 1 ;
  0 1   2 0 ;
  2 0   0 2 ;
] ;

% quiver plot
quiver( rays( :,1 ), rays( :,2 ), rays( :,3 ), rays( :,4 ) );

3D

% vectors I want to plot as rows (XSTART, YSTART, ZSTART) (XDIR, YDIR, ZDIR)
rays = [
  1 2 0  1 0 0;
  3 3 2  0 1 -1 ;
  0 1 -1  2 0 8;
  2 0 0  0 2 1;
] ;

% quiver plot
quiver3( rays( :,1 ), rays( :,2 ), rays( :,3 ), rays( :,4 ), rays( :,5 ), rays( :,6 ) );

Based on the quiver and quiver3 documentation

How to save a figure in MATLAB from the command line?

I don't think you can save it without it appearing, but just for saving in multiple formats use the print command. See the answer posted here: Save an imagesc output in Matlab

How to represent e^(-t^2) in MATLAB?

All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.

for matrix:

t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));

gives the results:

x =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

y =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

z=

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

And using a scalar:

p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);

gives the results:

x =

1.2341e-004

y =

1.2341e-004

z =

1.2341e-004

Read .mat files in Python

There is also the MATLAB Engine for Python by MathWorks itself. If you have MATLAB, this might be worth considering (I haven't tried it myself but it has a lot more functionality than just reading MATLAB files). However, I don't know if it is allowed to distribute it to other users (it is probably not a problem if those persons have MATLAB. Otherwise, maybe NumPy is the right way to go?).

Also, if you want to do all the basics yourself, MathWorks provides (if the link changes, try to google for matfile_format.pdf or its title MAT-FILE Format) a detailed documentation on the structure of the file format. It's not as complicated as I personally thought, but obviously, this is not the easiest way to go. It also depends on how many features of the .mat-files you want to support.

I've written a "small" (about 700 lines) Python script which can read some basic .mat-files. I'm neither a Python expert nor a beginner and it took me about two days to write it (using the MathWorks documentation linked above). I've learned a lot of new stuff and it was quite fun (most of the time). As I've written the Python script at work, I'm afraid I cannot publish it... But I can give some advice here:

  • First read the documentation.
  • Use a hex editor (such as HxD) and look into a reference .mat-file you want to parse.
  • Try to figure out the meaning of each byte by saving the bytes to a .txt file and annotate each line.
  • Use classes to save each data element (such as miCOMPRESSED, miMATRIX, mxDOUBLE, or miINT32)
  • The .mat-files' structure is optimal for saving the data elements in a tree data structure; each node has one class and subnodes

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

First Mover Advantage. Matlab has been around since the late 1970s. Python came along more recently, and the libraries that make it suitable for Matlab type tasks came along even more recently. People are used to Matlab, so they use it.

How to install toolbox for MATLAB

first, you need to find the toolbox that you need. There are many people developing 3rd party toolboxes for Matlab, so there isn't just one single place where you can find "the image processing toolbox". That said, a good place to start looking is the Matlab Central which is a Mathworks-run site for exchanging all kinds of Matlab-related material.

Once you find a toolbox you want, it will be in some compressed format, and its developers might have a "readme" file that details on how to install it. If it isn't the case, a generic way to attempt installation is to place the toolbox in any directory on your drive, and then add it to Matlab path, e.g., going to File -> Set Path... -> Add Folder or Add with Subfolders (I'm writing for memory but this is definitely close).

Otherwise, you can extract all .m files in your working directory, if you don't want to use downloaded toolbox in more than one project.

How to delete zero components in a vector in Matlab?

I often ended up doing things like this. Therefore I tried to write a simple function that 'snips' out the unwanted elements in an easy way. This turns matlab logic a bit upside down, but looks good:

b = snip(a,'0')

you can find the function file at: http://www.mathworks.co.uk/matlabcentral/fileexchange/41941-snip-m-snip-elements-out-of-vectorsmatrices

It also works with all other 'x', nan or whatever elements.

How to iterate over a column vector in Matlab?

In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.

Thus you can write

for elm = list
%# do something with the element
end

Note that Matlab iterates through the columns of list, so if list is a nx1 vector, you may want to transpose it.

How to normalize a vector in MATLAB efficiently? Any related built-in function?

I don't know any MATLAB and I've never used it, but it seems to me you are dividing. Why? Something like this will be much faster:

d = 1/norm(V)
V1 = V * d

How to show x and y axes in a MATLAB graph?

@Martijn your order of function calls is slightly off. Try this instead:

x=-3:0.1:3;
y = x.^3;
plot(x,y), hold on
plot([-3 3], [0 0], 'k:')
hold off

How to get the type of a variable in MATLAB?

Use the class function

>> b = 2
b =
     2
>> a = 'Hi'
a =
Hi
>> class(b)
ans =
double
>> class(a)
ans =
char

What can MATLAB do that R cannot do?

In my experience moving from MATLAB to Python is an easier transition - Python with numpy/scipy is closer to MATLAB in terms of style and features than R. There are also open source direct MATLAB clones Octave and Scilab.

There is certainly much that MATLAB can do that R can't - in my area MATLAB is used a lot for real time data aquisition - most hardware companies include MATLAB interfaces. While this may be possible with R I imagine it would be a lot more involved. Also Simulink provides a whole area of functionality which I think is missing from R. I'm sure there is more but I'm not so familiar with R.

Automatically plot different colored lines

If all vectors have equal size, create a matrix and plot it. Each column is plotted with a different color automatically Then you can use legend to indicate columns:

data = randn(100, 5);

figure;
plot(data);

legend(cellstr(num2str((1:size(data,2))')))

Or, if you have a cell with kernels names, use

legend(names)

SQL server stored procedure return a table

Here's an example of a SP that both returns a table and a return value. I don't know if you need the return the "Return Value" and I have no idea about MATLAB and what it requires.

CREATE PROCEDURE test
AS 
BEGIN

    SELECT * FROM sys.databases

    RETURN 27
END

--Use this to test
DECLARE @returnval int

EXEC @returnval = test 

SELECT @returnval

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

PLOTYY allows two different y-axes. Or you might look into LayerPlot from the File Exchange. I guess I should ask if you've considered using HOLD or just rescaling the data and using regular old plot?

OLD, not what the OP was looking for: SUBPLOT allows you to break a figure window into multiple axes. Then if you want to have only one x-axis showing, or some other customization, you can manipulate each axis independently.

What's the difference between & and && in MATLAB?

As already mentioned by others, & is a logical AND operator and && is a short-circuit AND operator. They differ in how the operands are evaluated as well as whether or not they operate on arrays or scalars:

  • & (AND operator) and | (OR operator) can operate on arrays in an element-wise fashion.
  • && and || are short-circuit versions for which the second operand is evaluated only when the result is not fully determined by the first operand. These can only operate on scalars, not arrays.

How do I set default values for functions parameters in Matlab?

I've found that the parseArgs function can be very helpful.

Gaussian filter in MATLAB

You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).

You specify sigma and hsize in fspecial.

Code:

%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)

What are the ways to sum matrix elements in MATLAB?

The best practice is definitely to avoid loops or recursions in Matlab.

Between sum(A(:)) and sum(sum(A)). In my experience, arrays in Matlab seems to be stored in a continuous block in memory as stacked column vectors. So the shape of A does not quite matter in sum(). (One can test reshape() and check if reshaping is fast in Matlab. If it is, then we have a reason to believe that the shape of an array is not directly related to the way the data is stored and manipulated.)

As such, there is no reason sum(sum(A)) should be faster. It would be slower if Matlab actually creates a row vector recording the sum of each column of A first and then sum over the columns. But I think sum(sum(A)) is very wide-spread amongst users. It is likely that they hard-code sum(sum(A)) to be a single loop, the same to sum(A(:)).

Below I offer some testing results. In each test, A=rand(size) and size is specified in the displayed texts.

First is using tic toc.

Size 100x100
sum(A(:))
Elapsed time is 0.000025 seconds.
sum(sum(A))
Elapsed time is 0.000018 seconds.

Size 10000x1
sum(A(:))
Elapsed time is 0.000014 seconds.
sum(A)
Elapsed time is 0.000013 seconds.

Size 1000x1000
sum(A(:))
Elapsed time is 0.001641 seconds.
sum(A)
Elapsed time is 0.001561 seconds.

Size 1000000
sum(A(:))
Elapsed time is 0.002439 seconds.
sum(A)
Elapsed time is 0.001697 seconds.

Size 10000x10000
sum(A(:))
Elapsed time is 0.148504 seconds.
sum(A)
Elapsed time is 0.155160 seconds.

Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.

Error in test27 (line 70)
A=rand(100000000,1);

Below is using cputime

Size 100x100
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 10000x1
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 1000x1000
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 1000000
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.

Error in test27_2 (line 70)
A=rand(100000000,1);

In my experience, both timers are only meaningful up to .1s. So if you have similar experience with Matlab timers, none of the tests can discern sum(A(:)) and sum(sum(A)).

I tried the largest size allowed on my computer a few more times.

Size 10000x10000
sum(A(:))
Elapsed time is 0.151256 seconds.
sum(A)
Elapsed time is 0.143937 seconds.

Size 10000x10000
sum(A(:))
Elapsed time is 0.149802 seconds.
sum(A)
Elapsed time is 0.145227 seconds.

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.2808
The cputime for sum(sum(A)) in seconds is 
0.312

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

They seem equivalent. Either one is good. But sum(sum(A)) requires that you know the dimension of your array is 2.

How to normalize a signal to zero mean and unit variance?

if your signal is in the matrix X, you make it zero-mean by removing the average:

X=X-mean(X(:));

and unit variance by dividing by the standard deviation:

X=X/std(X(:));

What is the Python equivalent of Matlab's tic and toc functions?

This can also be done using a wrapper. Very general way of keeping time.

The wrapper in this example code wraps any function and prints the amount of time needed to execute the function:

def timethis(f):
    import time

    def wrapped(*args, **kwargs):
        start = time.time()
        r = f(*args, **kwargs)
        print "Executing {0} took {1} seconds".format(f.func_name,  time.time()-start)
        return r
    return wrapped

@timethis
def thistakestime():
    for x in range(10000000):
        pass

thistakestime()

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

I also suggest using contourf(Z). For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.

So in my case, I prefer to use jucestain's answer. The default shading faceted of pcolor() is more suitable. However, pcolor() does not use the last row and column of the plotted matrix. For this, I used the padarray() function:

pcolor(padarray(Z,[1 1],0,'post'))

Sorry if that is not really related to the original post

How to get all files under a specific directory in MATLAB?

This answer does not directly answer the question but may be a good solution outside of the box.

I upvoted gnovice's solution, but want to offer another solution: Use the system dependent command of your operating system:

tic
asdfList = getAllFiles('../TIMIT_FULL/train');
toc
% Elapsed time is 19.066170 seconds.

tic
[status,cmdout] = system('find ../TIMIT_FULL/train/ -iname "*.wav"');
C = strsplit(strtrim(cmdout));
toc
% Elapsed time is 0.603163 seconds.

Positive:

  • Very fast (in my case for a database of 18000 files on linux).
  • You can use well tested solutions.
  • You do not need to learn or reinvent a new syntax to select i.e. *.wav files.

Negative:

  • You are not system independent.
  • You rely on a single string which may be hard to parse.

How do I iterate through each element in an n-dimensional matrix in MATLAB?

these solutions are more faster (about 11%) than using numel;)

for idx = reshape(array,1,[]),
     element = element + idx;
end

or

for idx = array(:)',
    element = element + idx;
end

UPD. tnx @rayryeng for detected error in last answer


Disclaimer

The timing information that this post has referenced is incorrect and inaccurate due to a fundamental typo that was made (see comments stream below as well as the edit history - specifically look at the first version of this answer). Caveat Emptor.

How can I count the number of elements of a given value in a matrix?

Use nnz instead of sum. No need for the double call to collapse matrices to vectors and it is likely faster than sum.

nnz(your_matrix == 5)

Doc

Differences between Octave and MATLAB?

There is not much which I would like to add to Rody Oldenhuis answer. I usually follow the strategy that all functions which I write should run in Matlab.

Some specific functions I test on both systems, for the following use cases:

a) octave does not need a license server - e.g. if your institution does not support local licenses. I used it once in a situation where the system I used a script on had no connection to the internet and was going to run for a very long time (in a corner in the lab) and used by many different users. Remark: that is not about the license cost, but about the technical issues related.

b) Octave supports other platforms, for example, the Rasberry Pi (http://wiki.octave.org/Rasperry_Pi) - which may come in handy.

How to normalize a histogram in MATLAB?

Since 2014b, Matlab has these normalization routines embedded natively in the histogram function (see the help file for the 6 routines this function offers). Here is an example using the PDF normalization (the sum of all the bins is 1).

data = 2*randn(5000,1) + 5;             % generate normal random (m=5, std=2)
h = histogram(data,'Normalization','pdf')   % PDF normalization

The corresponding PDF is

Nbins = h.NumBins;
edges = h.BinEdges; 
x = zeros(1,Nbins);
for counter=1:Nbins
    midPointShift = abs(edges(counter)-edges(counter+1))/2;
    x(counter) = edges(counter)+midPointShift;
end

mu = mean(data);
sigma = std(data);

f = exp(-(x-mu).^2./(2*sigma^2))./(sigma*sqrt(2*pi));

The two together gives

hold on;
plot(x,f,'LineWidth',1.5)

enter image description here

An improvement that might very well be due to the success of the actual question and accepted answer!


EDIT - The use of hist and histc is not recommended now, and histogram should be used instead. Beware that none of the 6 ways of creating bins with this new function will produce the bins hist and histc produce. There is a Matlab script to update former code to fit the way histogram is called (bin edges instead of bin centers - link). By doing so, one can compare the pdf normalization methods of @abcd (trapz and sum) and Matlab (pdf).

The 3 pdf normalization method give nearly identical results (within the range of eps).

TEST:

A = randn(10000,1);
centers = -6:0.5:6;
d = diff(centers)/2;
edges = [centers(1)-d(1), centers(1:end-1)+d, centers(end)+d(end)];
edges(2:end) = edges(2:end)+eps(edges(2:end));

figure;
subplot(2,2,1);
hist(A,centers);
title('HIST not normalized');

subplot(2,2,2);
h = histogram(A,edges);
title('HISTOGRAM not normalized');

subplot(2,2,3)
[counts, centers] = hist(A,centers); %get the count with hist
bar(centers,counts/trapz(centers,counts))
title('HIST with PDF normalization');


subplot(2,2,4)
h = histogram(A,edges,'Normalization','pdf')
title('HISTOGRAM with PDF normalization');

dx = diff(centers(1:2))
normalization_difference_trapz = abs(counts/trapz(centers,counts) - h.Values);
normalization_difference_sum = abs(counts/sum(counts*dx) - h.Values);

max(normalization_difference_trapz)
max(normalization_difference_sum)

enter image description here

The maximum difference between the new PDF normalization and the former one is 5.5511e-17.

How to save a plot into a PDF file without a large margin around

Save to EPS and then convert to PDF:

saveas(gcf, 'nombre.eps', 'eps2c')
system('epstopdf nombre.eps') %Needs TeX Live (maybe it works with MiKTeX).

You will need some software that converts EPS to PDF.

size of NumPy array

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape

How do I initialise all entries of a matrix with a specific value?

As mentioned in other answers you can use:

>> tic; x=5*ones(10,1); toc
Elapsed time is 0.000415 seconds.

An even faster method is:

>> tic;  x=5; x=x(ones(10,1)); toc
Elapsed time is 0.000257 seconds.

How do I put variable values into a text string in MATLAB?

You can use fprintf/sprintf with familiar C syntax. Maybe something like:

fprintf('x = %d, y = %d \n x+y=%d \n x*y=%d \n x/y=%f\n', x,y,d,e,f)

reading your comment, this is how you use your functions from the main program:

x = 2;
y = 2;
[d e f] = answer(x,y);
fprintf('%d + %d = %d\n', x,y,d)
fprintf('%d * %d = %d\n', x,y,e)
fprintf('%d / %d = %f\n', x,y,f)

Also for the answer() function, you can assign the output values to a vector instead of three distinct variables:

function result=answer(x,y)
result(1)=addxy(x,y);
result(2)=mxy(x,y);
result(3)=dxy(x,y);

and call it simply as:

out = answer(x,y);

Import CSV file with mixed data types

In R2013b or later you can use a table:

>> table = readtable('myfile.txt','Delimiter',';','ReadVariableNames',false)
>> table = 

    Var1    Var2     Var3     Var4     Var5        Var6          Var7         Var8      Var9    Var10
    ____    _____    _____    _____    _____    __________    __________    ________    ____    _____

      4     'abc'    'def'    'ghj'    'klm'    ''            ''            ''          NaN     NaN  
    NaN     ''       ''       ''       ''       'Test'        'text'        '0xFF'      NaN     NaN  
    NaN     ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'    '0x0F0F'    NaN     NaN  

Here is more info.

Correlation between two vectors?

For correlations you can just use the corr function (statistics toolbox)

corr(A_1(:), A_2(:))

Note that you can also just use

corr(A_1, A_2)

But the linear indexing guarantees that your vectors don't need to be transposed.

Python equivalent to 'hold on' in Matlab

You can use the following:

plt.hold(True)

Function for 'does matrix contain value X?'

For floating point data, you can use the new ismembertol function, which computes set membership with a specified tolerance. This is similar to the ismemberf function found in the File Exchange except that it is now built-in to MATLAB. Example:

>> pi_estimate = 3.14159;
>> abs(pi_estimate - pi)
ans =
   5.3590e-08
>> tol = 1e-7;
>> ismembertol(pi,pi_estimate,tol)
ans =
     1

Create an array of strings

You can create a character array that does this via a loop:

>> for i=1:10
Names(i,:)='Sample Text';
end
>> Names

Names =

Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text

However, this would be better implemented using REPMAT:

>> Names = repmat('Sample Text', 10, 1)

Names =

Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text

Setting graph figure size

Write it as a one-liner:

figure('position', [0, 0, 200, 500])  % create new figure with specified size  

enter image description here

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

Iterating through struct fieldnames in MATLAB

You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

for i = 1:numel(fields)
  teststruct.(fields{i})
end

Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed

Mean filter for smoothing images in Matlab

h = fspecial('average', n);
filter2(h, img);

See doc fspecial: h = fspecial('average', n) returns an averaging filter. n is a 1-by-2 vector specifying the number of rows and columns in h.

Call Python function from MATLAB

Try this MEX file for ACTUALLY calling Python from MATLAB not the other way around as others suggest. It provides fairly decent integration : http://algoholic.eu/matpy/

You can do something like this easily:

[X,Y]=meshgrid(-10:0.1:10,-10:0.1:10);
Z=sin(X)+cos(Y);
py_export('X','Y','Z')
stmt = sprintf(['import matplotlib\n' ...
'matplotlib.use(''Qt4Agg'')\n' ...
'import matplotlib.pyplot as plt\n' ...
'from mpl_toolkits.mplot3d import axes3d\n' ...
'f=plt.figure()\n' ...
'ax=f.gca(projection=''3d'')\n' ...
'cset=ax.plot_surface(X,Y,Z)\n' ...
'ax.clabel(cset,fontsize=9,inline=1)\n' ...
'plt.show()']);
py('eval', stmt);

MATLAB - multiple return values from a function?

Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed

What does operator "dot" (.) mean?

The dot itself is not an operator, .^ is.

The .^ is a pointwise¹ (i.e. element-wise) power, as .* is the pointwise product.

.^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. The sizes of A and B must be the same or be compatible.

C.f.

¹) Hence the dot.

How do I import/include MATLAB functions?

You should be able to put them in your ~/matlab on unix.

I'm not sure which directory matlab looks in for windows, but you should be able to figure it out by executing userpath from the matlab command line.

Octave/Matlab: Adding new elements to a vector

x(end+1) = newElem is a bit more robust.

x = [x newElem] will only work if x is a row-vector, if it is a column vector x = [x; newElem] should be used. x(end+1) = newElem, however, works for both row- and column-vectors.

In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)

How can I apply a function to every row/column of a matrix in MATLAB?

Stumbled upon this question/answer while seeking how to compute the row sums of a matrix.

I would just like to add that Matlab's SUM function actually has support for summing for a given dimension, i.e a standard matrix with two dimensions.

So to calculate the column sums do:

colsum = sum(M) % or sum(M, 1)

and for the row sums, simply do

rowsum = sum(M, 2)

My bet is that this is faster than both programming a for loop and converting to cells :)

All this can be found in the matlab help for SUM.

Reading a text file in MATLAB line by line

Just read it in to MATLAB in one block

fid = fopen('file.csv');
data=textscan(fid,'%s %f %f','delimiter',',');
fclose(fid);

You can then process it using logical addressing

ind50 = data{2}>=50 ;

ind50 is then an index of the rows where column 2 is greater than 50. So

data{1}(ind50)

will list all the strings for the rows of interest. Then just use fprintf to write out your data to the new file

How to concat string + i?

Try the following:

for i = 1:4
    result = strcat('f',int2str(i));
end

If you use this for naming several files that your code generates, you are able to concatenate more parts to the name. For example, with the extension at the end and address at the beginning:

filename = strcat('c:\...\name',int2str(i),'.png'); 

Create a 3D matrix

Create a 3D matrix

A = zeros(20, 10, 3);   %# Creates a 20x10x3 matrix

Add a 3rd dimension to a matrix

B = zeros(4,4);  
C = zeros(size(B,1), size(B,2), 4);  %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B;                        %# Copy the content of B into C's first set of values

zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0 for a 3D matrix. To confirm the size of your matrices you can run: size(A) which gives 20 10 3.

There is no explicit bound on the number of dimensions a matrix may have.

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

It can also be done this way:

figure(xx);
set(gcf, 'name', 'Name goes here')

gcf gets the current figure handle.

Changing Fonts Size in Matlab Plots

Jonas's answer does not change the font size of the axes. Sergeyf's answer does not work when there are multiple subplots.

Here is a modification of their answers that works for me when I have multiple subplots:

set(findall(gcf,'type','axes'),'fontsize',30)
set(findall(gcf,'type','text'),'fontSize',30) 

How to search for a string in cell array in MATLAB?

did you try

indices = Find(strs, 'KU')

see link

alternatively,

indices = strfind(strs, 'KU');

should also work if I'm not mistaken.

how to use a like with a join in sql?

Using conditional criteria in a join is definitely different than the Where clause. The cardinality between the tables can create differences between Joins and Where clauses.

For example, using a Like condition in an Outer Join will keep all records in the first table listed in the join. Using the same condition in the Where clause will implicitly change the join to an Inner join. The record has to generally be present in both tables to accomplish the conditional comparison in the Where clause.

I generally use the style given in one of the prior answers.

tbl_A as ta
    LEFT OUTER JOIN tbl_B AS tb
            ON ta.[Desc] LIKE '%' + tb.[Desc] + '%'

This way I can control the join type.

How do I set the timeout for a JAX-WS webservice client?

In case your appserver is WebLogic (for me it was 10.3.6) then properties responsible for timeouts are:

com.sun.xml.ws.connect.timeout 
com.sun.xml.ws.request.timeout

How to use export with Python on Linux

Another way to do this, if you're in a hurry and don't mind the hacky-aftertaste, is to execute the output of the python script in your bash environment and print out the commands to execute setting the environment in python. Not ideal but it can get the job done in a pinch. It's not very portable across shells, so YMMV.

$(python -c 'print "export MY_DATA=my_export"')

(you can also enclose the statement in backticks in some shells ``)

Git Cherry-Pick and Conflicts

Do, I need to resolve all the conflicts before proceeding to next cherry -pick

Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.

Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.

That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.

Further, is it suggested to do cherry-pick or branch merge in this case?

Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.

Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.

How to declare a global variable in a .js file

Have you tried it?

If you do:

var HI = 'Hello World';

In global.js. And then do:

alert(HI);

In js1.js it will alert it fine. You just have to include global.js prior to the rest in the HTML document.

The only catch is that you have to declare it in the window's scope (not inside any functions).

You could just nix the var part and create them that way, but it's not good practice.

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

What is Shelving in TFS?

Shelving is like your changes have been stored in the source control without affecting the existing changes. Means if you check in a file in source control it will modify the existing file but shelving is like storing your changes in source control but without modifying the actual changes.

Convert timestamp in milliseconds to string formatted time in Java

Try this:

Date date = new Date(logEvent.timeSTamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateFormatted = formatter.format(date);

See SimpleDateFormat for a description of other format strings that the class accepts.

See runnable example using input of 1200 ms.

Practical uses for the "internal" keyword in C#

One use of the internal keyword is to limit access to concrete implementations from the user of your assembly.

If you have a factory or some other central location for constructing objects the user of your assembly need only deal with the public interface or abstract base class.

Also, internal constructors allow you to control where and when an otherwise public class is instantiated.

WPF ListView - detect when selected item is clicked

You can handle the ListView's PreviewMouseLeftButtonUp event. The reason not to handle the PreviewMouseLeftButtonDown event is that, by the time when you handle the event, the ListView's SelectedItem may still be null.

XAML:

<ListView ... PreviewMouseLeftButtonUp="listView_Click"> ...

Code behind:

private void listView_Click(object sender, RoutedEventArgs e)
{
    var item = (sender as ListView).SelectedItem;
    if (item != null)
    {
        ...
    }
}

Can't find file executable in your configured search path for gnc gcc compiler

I'm guessing you've installed Code::Blocks but not installed or set up GCC yet. I'm assuming you're on Windows, based on your comments about Visual Studio; if you're on a different platform, the steps for setting up GCC should be similar but not identical.

First you'll need to download GCC. There are lots and lots of different builds; personally, I use the 64-bit build of TDM-GCC. The setup for this might be a bit more complex than you'd care for, so you can go for the 32-bit version or just grab a preconfigured Code::Blocks/TDM-GCC setup here.

Once your setup is done, go ahead and launch Code::Blocks. You don't need to create a project or write any code yet; we're just here to set stuff up or double-check your setup, depending on how you opted to install GCC.

Go into the Settings menu, then select Global compiler settings in the sidebar, and select the Toolchain executables tab. Make sure the Compiler's installation directory textbox matches the folder you installed GCC into. For me, this is C:\TDM-GCC-64. Your path will vary, and this is completely fine; just make sure the path in the textbox is the same as the path you installed to. Pay careful attention to the warning note Code::Blocks shows: this folder must have a bin subfolder which will contain all the relevant GCC executables. If you look into the folder the textbox shows and there isn't a bin subfolder there, you probably have the wrong installation folder specified.

Now, in that same Toolchain executables screen, go through the individual Program Files boxes one by one and verify that the filenames shown in each are correct. You'll want some variation of the following:

  • C compiler: gcc.exe (mine shows x86_64-w64-mingw32-gcc.exe)
  • C++ compiler: g++.exe (mine shows x86_64-w64-mingw32-g++.exe)
  • Linker for dynamic libs: g++.exe (mine shows x86_64-w64-mingw32-g++.exe)
  • Linker for static libs: gcc-ar.exe (mine shows x86_64-w64-mingw32-gcc-ar.exe)
  • Debugger: GDB/CDB debugger: Default
  • Resource compiler: windres.exe (mine shows windres.exe)
  • Make program: make.exe (mine shows mingw32-make.exe)

Again, note that all of these files are in the bin subfolder of the folder shown in the Compiler installation folder box - if you can't find these files, you probably have the wrong folder specified. It's okay if the filenames aren't a perfect match, though; different GCC builds might have differently prefixed filenames, as you can see from my setup.

Once you're done with all that, go ahead and click OK. You can restart Code::Blocks if you'd like, just to confirm the changes will stick even if there's a crash (I've had occasional glitches where Code::Blocks will crash and forget any settings changed since the last launch).

Now, you should be all set. Go ahead and try your little section of code again. You'll want int main(void) to be int main(), but everything else looks good. Try building and running it and see what happens. It should run successfully.

Visual Studio: LINK : fatal error LNK1181: cannot open input file

In Linker, general, additional library directories, add the directory to the .dll or .libs you have included in Linker, Input. It does not work if you put this in VC++ Directories, Library Directories.

How to change navbar/container width? Bootstrap 3

Proper way to do it is to change the width on the online customizer here:

http://getbootstrap.com/customize/

download the recompiled source, overwrite the existing bootstrap dist dir, and reload (mind the browser cache!!!)

All your changes will be retained in the .json configuration file

To apply again the all the changes just upload the json file and you are ready to go

do { ... } while (0) — what is it good for?

It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:

#define FOO(n)   foo(n);bar(n)

and you do:

void foobar(int n) {
  if (n)
     FOO(n);
}

then this expands to:

void foobar(int n) {
  if (n)
     foo(n);bar(n);
}

Notice that the second call bar(n) is not part of the if statement anymore.

Wrap both into do { } while(0), and you can also use the macro in an if statement.

React "after render" code?

I am not going to pretend I know why this particular function works, however window.getComputedStyle works 100% of the time for me whenever I need to access DOM elements with a Ref in a useEffect — I can only presume it will work with componentDidMount as well.

I put it at the top of the code in a useEffect and it appears as if it forces the effect to wait for the elements to be painted before it continues with the next line of code, but without any noticeable delay such as using a setTimeout or an async sleep function. Without this, the Ref element returns as undefined when I try to access it.

const ref = useRef(null);

useEffect(()=>{
    window.getComputedStyle(ref.current);
    // Next lines of code to get element and do something after getComputedStyle().
});

return(<div ref={ref}></div>);

batch to copy files with xcopy

You must specify your file in the copy:

xcopy C:\source\myfile.txt C:\target

Or if you want to copy all txt files for example

xcopy C:\source\*.txt C:\target

Check if argparse optional argument is set or not

Very simple, after defining args variable by 'args = parser.parse_args()' it contains all data of args subset variables too. To check if a variable is set or no assuming the 'action="store_true" is used...

if args.argument_name:
   # do something
else:
   # do something else

Check file uploaded is in csv format

Mime type option is not best option for validating CSV file. I used this code this worked well in all browser

$type = explode(".",$_FILES['file']['name']);
if(strtolower(end($type)) == 'csv'){

}
else
{

}

How do I install a NuGet package .nupkg file locally?

Recently I want to install squirrel.windows, I tried Install-Package squirrel.windows -Version 2.0.1 from https://www.nuget.org/packages/squirrel.windows/, but it failed with some errors. So I downloaded squirrel.windows.2.0.1.nupkg and save it in D:\Downloads\, then I can install it success via Install-Package squirrel.windows -verbose -Source D:\Downloads\ -Scope CurrentUser -SkipDependencies in powershell.

Swift - Remove " character from string

As Martin R says, your string "Optional("5")" looks like you did something wrong.

dasblinkenlight answers you so it is fine, but for future readers, I will try to add alternative code as:

if let realString = yourOriginalString {
    text2 = realString
} else {
    text2 = ""
}

text2 in your example looks like String and it is maybe already set to "" but it looks like you have an yourOriginalString of type Optional(String) somewhere that it wasn't cast or use correctly.

I hope this can help some reader.

Two statements next to curly brace in an equation

To answer also to the comment by @MLT, there is an alternative to the standard cases environment, not too sophisticated really, with both lines numbered. This code:

\documentclass{article}
\usepackage{amsmath}
\usepackage{cases}

\begin{document}

\begin{numcases}{f(x)=}
  1, & if $x<0$\\
  0, & otherwise
\end{numcases}

\end{document}

produces

screenshot of output pdf

Notice that here, math must be delimited by \(...\) or $...$, at least on the right of & in each line (reference).

Remove duplicate values from JS array

Go for this one:

var uniqueArray = duplicateArray.filter(function(elem, pos) {
    return duplicateArray.indexOf(elem) == pos;
}); 

Now uniqueArray contains no duplicates.

Difference between webdriver.Dispose(), .Close() and .Quit()

close() is a webdriver command which closes the browser window which is currently in focus. Despite the familiar name for this method, WebDriver does not implement the AutoCloseable interface.

During the automation process, if there are more than one browser window opened, then the close() command will close only the current browser window which is having focus at that time. The remaining browser windows will not be closed. The following code can be used to close the current browser window:

quit() is a webdriver command which calls the driver.dispose method, which in turn closes all the browser windows and terminates the WebDriver session. If we do not use quit() at the end of program, the WebDriver session will not be closed properly and the files will not be cleared off memory. This may result in memory leak errors.

If the Automation process opens only a single browser window, the close() and quit() commands work in the same way. Both will differ in their functionality when there are more than one browser window opened during Automation.

For Above Ref : click here

Dispose Command Dispose() should call Quit(), and it appears it does. However, it also has the same problem in that any subsequent actions are blocked until PhantomJS is manually closed.

Ref Link

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

Angular 2 : No NgModule metadata found

The issue is fixed only when re installed angular/cli manually. Follow following steps. (run all command under Angular project dir)

1)Remove webpack by using following command.

npm remove webpack

2)Install cli by using following command.

npm install --save-dev @angular/cli@latest

after successfully test app, it will work :)

if not then follow below steps.

1) Delete node_module folder.

2) Clear cache by using following command.

npm cache clean --force

3) Install node packages by using following command.

npm install

4)Install angular@cli by using following command.

npm install --save-dev @angular/cli@latest

Note :if failed,try again :)

5) Celebrate :)

How to create an executable .exe file from a .m file

mcc -?

explains that the syntax to make *.exe (Standalone Application) with *.m is:

 mcc -m <matlabFile.m> 

For example:

mcc -m file.m

will create file.exe in the curent directory.

using javascript to detect whether the url exists before display in iframe

I found this worked in my scenario.

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

$.get("urlToCheck.com").done(function () {
  alert("success");
}).fail(function () {
   alert("failed.");
});

MySQL Install: ERROR: Failed to build gem native extension

on OSX mountain Lion: If you have brew installed, then brew install mysql and follow the instructions on creating a test database with mysql on your machine. You don't have to go all the way through, I didn't need to After I did that I was able to bundle install and rake.

How do I base64 encode a string efficiently using Excel VBA?

As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.

I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As Variant
  Dim objNode As Variant

  Set objXML = CreateObject("MSXML2.DOMDocument")
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.text

  Set objNode = Nothing
  Set objXML = Nothing
End Function

Setting and getting localStorage with jQuery

The localStorage can only store string content and you are trying to store a jQuery object since html(htmlString) returns a jQuery object.

You need to set the string content instead of an object. And use the setItem method to add data and getItem to get data.

window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));

How can I make a div stick to the top of the screen once it's been scrolled to?

Not an exact solution but a great alternative to consider

this CSS ONLY Top of screen scroll bar. Solved all the problem with ONLY CSS, NO JavaScript, NO JQuery, No Brain work (lol).

Enjoy my fiddle :D all the codes are included in there :)

CSS

#menu {
position: fixed;
height: 60px;
width: 100%;
top: 0;
left: 0;
border-top: 5px solid #a1cb2f;
background: #fff;
-moz-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
-webkit-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
z-index: 999999;
}

.w {
    width: 900px;
    margin: 0 auto;
    margin-bottom: 40px;
}<br type="_moz">

Put the content long enough so you can see the effect here :) Oh, and the reference is in there as well, for the fact he deserve his credit

CSS ONLY Top of screen scroll bar

new Runnable() but no new thread?

Runnable is often used to provide the code that a thread should run, but Runnable itself has nothing to do with threads. It's just an object with a run() method.

In Android, the Handler class can be used to ask the framework to run some code later on the same thread, rather than on a different one. Runnable is used to provide the code that should run later.

Input and Output binary streams using JERSEY?

This example shows how to publish log files in JBoss through a rest resource. Note the get method uses the StreamingOutput interface to stream the content of the log file.

@Path("/logs/")
@RequestScoped
public class LogResource {

private static final Logger logger = Logger.getLogger(LogResource.class.getName());
@Context
private UriInfo uriInfo;
private static final String LOG_PATH = "jboss.server.log.dir";

public void pipe(InputStream is, OutputStream os) throws IOException {
    int n;
    byte[] buffer = new byte[1024];
    while ((n = is.read(buffer)) > -1) {
        os.write(buffer, 0, n);   // Don't allow any extra bytes to creep in, final write
    }
    os.close();
}

@GET
@Path("{logFile}")
@Produces("text/plain")
public Response getLogFile(@PathParam("logFile") String logFile) throws URISyntaxException {
    String logDirPath = System.getProperty(LOG_PATH);
    try {
        File f = new File(logDirPath + "/" + logFile);
        final FileInputStream fStream = new FileInputStream(f);
        StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                try {
                    pipe(fStream, output);
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
        return Response.ok(stream).build();
    } catch (Exception e) {
        return Response.status(Response.Status.CONFLICT).build();
    }
}

@POST
@Path("{logFile}")
public Response flushLogFile(@PathParam("logFile") String logFile) throws URISyntaxException {
    String logDirPath = System.getProperty(LOG_PATH);
    try {
        File file = new File(logDirPath + "/" + logFile);
        PrintWriter writer = new PrintWriter(file);
        writer.print("");
        writer.close();
        return Response.ok().build();
    } catch (Exception e) {
        return Response.status(Response.Status.CONFLICT).build();
    }
}    

}

PostgreSQL next value of the sequences?

If your are not in a session you can just nextval('you_sequence_name') and it's just fine.

how to draw directed graphs using networkx in python?

Instead of regular nx.draw you may want to use:

nx.draw_networkx(G[, pos, arrows, with_labels])

For example:

nx.draw_networkx(G, arrows=True, **options)

You can add options by initialising that ** variable like this:

options = {
    'node_color': 'blue',
    'node_size': 100,
    'width': 3,
    'arrowstyle': '-|>',
    'arrowsize': 12,
}

Also some functions support the directed=True parameter In this case this state is the default one:

G = nx.DiGraph(directed=True)

The networkx reference is found here.

Graph with arrows image

jQuery trigger file input

This is probably the best answer, keeping in mind the cross browser issues.

CSS:

#file {
  opacity: 0;
  width: 1px;
  height: 1px;
}

JS:

$(".file-upload").on('click',function(){
   $("[name='file']").click();
});

HTML:

<a class="file-upload">Upload</a>
<input type="file" name="file">

store and retrieve a class object in shared preference

Yes .You can store and retrive the object using Sharedpreference

With block equivalent in C#?

Although C# doesn't have any direct equivalent for the general case, C# 3 gain object initializer syntax for constructor calls:

var foo = new Foo { Property1 = value1, Property2 = value2, etc };

See chapter 8 of C# in Depth for more details - you can download it for free from Manning's web site.

(Disclaimer - yes, it's in my interest to get the book into more people's hands. But hey, it's a free chapter which gives you more information on a related topic...)

What's the function like sum() but for multiplication? product()?

Update:

In Python 3.8, the prod function was added to the math module. See: math.prod().

Older info: Python 3.7 and prior

The function you're looking for would be called prod() or product() but Python doesn't have that function. So, you need to write your own (which is easy).

Pronouncement on prod()

Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.

Alternative with reduce()

As you suggested, it is not hard to make your own using reduce() and operator.mul():

from functools import reduce  # Required in Python 3
import operator
def prod(iterable):
    return reduce(operator.mul, iterable, 1)

>>> prod(range(1, 5))
24

Note, in Python 3, the reduce() function was moved to the functools module.

Specific case: Factorials

As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:

>>> import math

>>> math.factorial(10)
3628800

Alternative with logarithms

If your data consists of floats, you can compute a product using sum() with exponents and logarithms:

>>> from math import log, exp

>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))
218.53799999999993

>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8
218.53799999999998

Note, the use of log() requires that all the inputs are positive.

Random / noise functions for GLSL

It occurs to me that you could use a simple integer hash function and insert the result into a float's mantissa. IIRC the GLSL spec guarantees 32-bit unsigned integers and IEEE binary32 float representation so it should be perfectly portable.

I gave this a try just now. The results are very good: it looks exactly like static with every input I tried, no visible patterns at all. In contrast the popular sin/fract snippet has fairly pronounced diagonal lines on my GPU given the same inputs.

One disadvantage is that it requires GLSL v3.30. And although it seems fast enough, I haven't empirically quantified its performance. AMD's Shader Analyzer claims 13.33 pixels per clock for the vec2 version on a HD5870. Contrast with 16 pixels per clock for the sin/fract snippet. So it is certainly a little slower.

Here's my implementation. I left it in various permutations of the idea to make it easier to derive your own functions from.

/*
    static.frag
    by Spatial
    05 July 2013
*/

#version 330 core

uniform float time;
out vec4 fragment;



// A single iteration of Bob Jenkins' One-At-A-Time hashing algorithm.
uint hash( uint x ) {
    x += ( x << 10u );
    x ^= ( x >>  6u );
    x += ( x <<  3u );
    x ^= ( x >> 11u );
    x += ( x << 15u );
    return x;
}



// Compound versions of the hashing algorithm I whipped together.
uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y)                         ); }
uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z)             ); }
uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); }



// Construct a float with half-open range [0:1] using low 23 bits.
// All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0.
float floatConstruct( uint m ) {
    const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask
    const uint ieeeOne      = 0x3F800000u; // 1.0 in IEEE binary32

    m &= ieeeMantissa;                     // Keep only mantissa bits (fractional part)
    m |= ieeeOne;                          // Add fractional part to 1.0

    float  f = uintBitsToFloat( m );       // Range [1:2]
    return f - 1.0;                        // Range [0:1]
}



// Pseudo-random value in half-open range [0:1].
float random( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }
float random( vec2  v ) { return floatConstruct(hash(floatBitsToUint(v))); }
float random( vec3  v ) { return floatConstruct(hash(floatBitsToUint(v))); }
float random( vec4  v ) { return floatConstruct(hash(floatBitsToUint(v))); }





void main()
{
    vec3  inputs = vec3( gl_FragCoord.xy, time ); // Spatial and temporal inputs
    float rand   = random( inputs );              // Random per-pixel value
    vec3  luma   = vec3( rand );                  // Expand to RGB

    fragment = vec4( luma, 1.0 );
}

Screenshot:

Output of random(vec3) in static.frag

I inspected the screenshot in an image editing program. There are 256 colours and the average value is 127, meaning the distribution is uniform and covers the expected range.

How to install Jdk in centos

Here is something that might help. Use the root privileges. if you have .bin then simply add the execution permission to the bin file.

chmod a+x jdk*.bin

next step is to run the .bin file which is simply

./jdk*.bin in the location you want to install.

you are done.

Load external css file like scripts in jquery which is compatible in ie also

I think what the OP wanted to do was to load a style sheet asynchronously and add it. This works for me in Chrome 22, FF 16 and IE 8 for sets of CSS rules stored as text:

$.ajax({
    url: href,
    dataType: 'text',
    success: function(data) {
        $('<style type="text/css">\n' + data + '</style>').appendTo("head");                    
    }                  
});

In my case, I also sometimes want the loaded CSS to replace CSS that was previously loaded this way. To do that, I put a comment at the beginning, say "/* Flag this ID=102 */", and then I can do this:

// Remove old style
$("head").children().each(function(index, ele) {
    if (ele.innerHTML && ele.innerHTML.substring(0, 30).match(/\/\* Flag this ID=102 \*\//)) {
        $(ele).remove();
        return false;    // Stop iterating since we removed something
    }
});

How to force a hover state with jQuery?

Also, you could try triggering a mouseover.

$("#btn").click(function() {
   $("#link").trigger("mouseover");
});

Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.

Random date in C#

This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.

Func<DateTime> RandomDayFunc()
{
    DateTime start = new DateTime(1995, 1, 1); 
    Random gen = new Random(); 
    int range = ((TimeSpan)(DateTime.Today - start)).Days; 
    return () => start.AddDays(gen.Next(range));
}

Change date format in a Java string

You can also use substring()

String date_s = "2011-01-18 00:00:00.0";
date_s.substring(0,10);

If you want a space in front of the date, use

String date_s = " 2011-01-18 00:00:00.0";
date_s.substring(1,11);

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

React.js: How to append a component on click?

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;

Windows Forms - Enter keypress activates submit button?

You can subscribe to the KeyUp event of the TextBox.

private void txtInput_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
       DoSomething();
}

SQL 'like' vs '=' performance

You should also keep in mind that when using like, some sql flavors will ignore indexes, and that will kill performance. This is especially true if you don't use the "starts with" pattern like your example.

You should really look at the execution plan for the query and see what it's doing, guess as little as possible.

This being said, the "starts with" pattern can and is optimized in sql server. It will use the table index. EF 4.0 switched to like for StartsWith for this very reason.

Purpose of returning by const value?

It's pretty pointless to return a const value from a function.

It's difficult to get it to have any effect on your code:

const int foo() {
   return 3;
}

int main() {
   int x = foo();  // copies happily
   x = 4;
}

and:

const int foo() {
   return 3;
}

int main() {
   foo() = 4;  // not valid anyway for built-in types
}

// error: lvalue required as left operand of assignment

Though you can notice if the return type is a user-defined type:

struct T {};

const T foo() {
   return T();
}

int main() {
   foo() = T();
}

// error: passing ‘const T’ as ‘this’ argument of ‘T& T::operator=(const T&)’ discards qualifiers

it's questionable whether this is of any benefit to anyone.

Returning a reference is different, but unless Object is some template parameter, you're not doing that.

bootstrap multiselect get selected values

In my case i was using jQuery validation rules with

submitHandler function and submitting the data as new FormData(form);

Select Option

<select class="selectpicker" id="branch" name="branch" multiple="multiple" title="Of Branch" data-size="6" required>
  <option disabled>Multiple Branch Select</option>
  <option value="Computer">Computer</option>
  <option value="Civil">Civil</option>
  <option value="EXTC">EXTC</option>
  <option value="ETRX">ETRX</option>
  <option value="Mechinical">Mechinical</option>
</select>

<input type="hidden" name="new_branch" id="new_branch">

Get the multiple selected value and set to new_branch input value & while submitting the form get value from new_branch

Just replace hidden with text to view on the output

<input type="text" name="new_branch" id="new_branch">

Script (jQuery / Ajax)

<script>
    $(document).ready(function() {

      $('#branch').on('change', function(){
          var selected = $(this).find("option:selected"); //get current selected value
          var arrSelected = []; //Array to store your multiple value in stack
          selected.each(function(){
            arrSelected.push($(this).val()); //Stack the value
          });
          $('#new_branch').val(arrSelected); //It will set the multiple selected value to input new_branch
      });

    });
</script>

Nginx location "not equal to" regex

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}

Get all files and directories in specific path fast

I know this is old, but... Another option may be to use the FileSystemWatcher like so:

void SomeMethod()
{
    System.IO.FileSystemWatcher m_Watcher = new System.IO.FileSystemWatcher();
    m_Watcher.Path = path;
    m_Watcher.Filter = "*.*";
    m_Watcher.NotifyFilter = m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    m_Watcher.Created += new FileSystemEventHandler(OnChanged);
    m_Watcher.EnableRaisingEvents = true;
}

private void OnChanged(object sender, FileSystemEventArgs e)
    {
        string path = e.FullPath;

        lock (listLock)
        {
            pathsToUpload.Add(path);
        }
    }

This would allow you to watch the directories for file changes with an extremely lightweight process, that you could then use to store the names of the files that changed so that you could back them up at the appropriate time.

Creating a dynamic choice field

the problem is when you do

def __init__(self, user, *args, **kwargs):
    super(waypointForm, self).__init__(*args, **kwargs)
    self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.filter(user=user)])

in a update request, the previous value will lost!

Delete last commit in bitbucket

I've had trouble with git revert in the past (mainly because I'm not quite certain how it works.) I've had trouble reverting because of merge problems..

My simple solution is this.

Step 1.

 git clone <your repos URL> .

your project in another folder, then:

Step 2.

git reset --hard <the commit you wanna go to>

then Step 3.

in your latest (and main) project dir (the one that has the problematic last commit) paste the files of step 2

Step 4.

git commit -m "Fixing the previous messy commit" 

Step 5.

Enjoy

What exactly is an instance in Java?

When you use the keyword new for example JFrame j = new JFrame(); you are creating an instance of the class JFrame.

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

Take a look here
Creating Objects


The types of the Java programming language are divided into two categories: primitive types and reference types.
The reference types are class types, interface types, and array types.
There is also a special null type.
An object is a dynamically created instance of a class type or a dynamically created array.
The values of a reference type are references to objects.

Refer Types, Values, and Variables for more information

How to set the holo dark theme in a Android app?

By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.

So just set it to:

<style name="AppTheme" parent="android:Theme.Holo" />

Setting "checked" for a checkbox with jQuery

You can do this if you have the id to check it

document.getElementById('ElementId').checked = false

And this to uncheck

document.getElementById('ElementId').checked = true

How do I uninstall a package installed using npm link?

The package can be uninstalled using the same uninstall or rm command that can be used for removing installed packages. The only thing to keep in mind is that the link needs to be uninstalled globally - the --global flag needs to be provided.

In order to uninstall the globally linked foo package, the following command can be used (using sudo if necessary, depending on your setup and permissions)

sudo npm rm --global foo

This will uninstall the package.

To check whether a package is installed, the npm ls command can be used:

npm ls --global foo

Can I get JSON to load into an OrderedDict?

Simple version for Python 2.7+

my_ordered_dict = json.loads(json_str, object_pairs_hook=collections.OrderedDict)

Or for Python 2.4 to 2.6

import simplejson as json
import ordereddict

my_ordered_dict = json.loads(json_str, object_pairs_hook=ordereddict.OrderedDict)

Saving image to file

You could try to save the image using this approach

SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
   int width = Convert.ToInt32(drawImage.Width); 
   int height = Convert.ToInt32(drawImage.Height); 
   Bitmap bmp = new Bitmap(width,height);        
   drawImage.DrawToBitmap(bmp, new Rectangle(0, 0, width, height);
   bmp.Save(dialog.FileName, ImageFormat.Jpeg);
}

'module' object has no attribute 'DataFrame'

I have faced similar problem, 'int' object has no attribute 'DataFrame',

This was because i have mistakenly used pd as a variable in my code and assigned an integer to it, while using the same pd as my pandas dataframe object by declaring - import pandas as pd.

I realized this, and changed my variable to something else, and fixed the error.

How to pass a URI to an intent?

The Uri.parse(extras.getString("imageUri")) was causing an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.putExtra(java.lang.String, android.os.Parcelable)' on a null object reference 

So I changed to the following:

intent.putExtra("imageUri", imageUri)

and

Uri uri = (Uri) getIntent().get("imageUri");

This solved the problem.

Deleting array elements in JavaScript - delete vs splice

Because delete only removes the object from the element in the array, the length of the array won't change. Splice removes the object and shortens the array.

The following code will display "a", "b", "undefined", "d"

myArray = ['a', 'b', 'c', 'd']; delete myArray[2];

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

Whereas this will display "a", "b", "d"

myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

How to save a git commit message from windows cmd?

Press Shift-zz. Saves changes and Quits. Escape didn't work for me.

I am using Git Bash in windows. And couldn't get past this either. My commit messages are simple so I dont want to add another editor atm.

How can I do string interpolation in JavaScript?

I use this pattern in a lot of languages when I don't know how to do it properly yet and just want to get an idea down quickly:

// JavaScript
let stringValue = 'Hello, my name is {name}. You {action} my {relation}.'
    .replace(/{name}/g    ,'Indigo Montoya')
    .replace(/{action}/g  ,'killed')
    .replace(/{relation}/g,'father')
    ;

While not particularily efficient, I find it readable. It always works, and its always available:

' VBScript
dim template = "Hello, my name is {name}. You {action} my {relation}."
dim stringvalue = template
stringValue = replace(stringvalue, "{name}"    ,"Luke Skywalker")     
stringValue = replace(stringvalue, "{relation}","Father")     
stringValue = replace(stringvalue, "{action}"  ,"are")

ALWAYS

* COBOL
INSPECT stringvalue REPLACING FIRST '{name}'     BY 'Grendel'
INSPECT stringvalue REPLACING FIRST '{relation}' BY 'Mother'
INSPECT stringvalue REPLACING FIRST '{action}'   BY 'did unspeakable things to'

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

Make sure that the htaccess file is readable by apache:

chmod 644 /var/www/abc/.htaccess 

And make sure the directory it's in is readable and executable:

chmod 755 /var/www/abc/

What is the best collation to use for MySQL with PHP?

The main difference is sorting accuracy (when comparing characters in the language) and performance. The only special one is utf8_bin which is for comparing characters in binary format.

utf8_general_ci is somewhat faster than utf8_unicode_ci, but less accurate (for sorting). The specific language utf8 encoding (such as utf8_swedish_ci) contain additional language rules that make them the most accurate to sort for those languages. Most of the time I use utf8_unicode_ci (I prefer accuracy to small performance improvements), unless I have a good reason to prefer a specific language.

You can read more on specific unicode character sets on the MySQL manual - http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html

Android: making a fullscreen application

just do this in your manifest file in your activity tag

android:theme="@style/Theme.AppCompat.Light.NoActionBar"

Auto select file in Solution Explorer from its open tab

There's a very nice extension to VS2010, which does exactly this: Solution Explorer Tools.

This extension adds a button which selects the current file in the solution explorer, as well as convenient buttons for collapsing and expanding projects.

How do I get the width and height of a HTML5 canvas?

None of those worked for me. Try this.

console.log($(canvasjQueryElement)[0].width)

How to add a recyclerView inside another recyclerView

you can use LayoutInflater to inflate your dynamic data as a layout file.

UPDATE : first create a LinearLayout inside your CardView's layout and assign an ID for it. after that create a layout file that you want to inflate. at last in your onBindViewHolder method in your "RAdaper" class. write these codes :

  mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

  view = mInflater.inflate(R.layout.my_list_custom_row, parent, false);

after that you can initialize data and ClickListeners with your RAdapter Data. hope it helps.

this and this may useful :)

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

This worked for me:

keytool -exportcert -alias androiddebugkey -keystore

Put path-to-debug-or-production-keystore here like C:\users\youruser.android\debug.keystore -list -v

Make sure you already are in the Java\jdk*\bin directory in a command or terminal window.

Then use Android as the password.

Sometimes web resources could be misleading. These are the ones working:

Initializing an Array of Structs in C#

Change const to static readonly and initialise it like this

static readonly MyStruct[] MyArray = new[] {
    new MyStruct { label = "a", id = 1 },
    new MyStruct { label = "b", id = 5 },
    new MyStruct { label = "q", id = 29 }
};

In C#, why is String a reference type that behaves like a value type?

Isn't just as simple as Strings are made up of characters arrays. I look at strings as character arrays[]. Therefore they are on the heap because the reference memory location is stored on the stack and points to the beginning of the array's memory location on the heap. The string size is not known before it is allocated ...perfect for the heap.

That is why a string is really immutable because when you change it even if it is of the same size the compiler doesn't know that and has to allocate a new array and assign characters to the positions in the array. It makes sense if you think of strings as a way that languages protect you from having to allocate memory on the fly (read C like programming)

Access POST values in Symfony2 request object

There is one trick with ParameterBag::get() method. You can set $deep parameter to true and access the required deep nested value without extra variable:

$request->request->get('form[some][deep][data]', null, true);

Also you have possibility to set a default value (2nd parameter of get() method), it can avoid redundant isset($form['some']['deep']['data']) call.

How do I set the default font size in Vim?

For the first one remove the spaces. Whitespace matters for the set command.

set guifont=Monaco:h20

For the second one it should be (the h specifies the height)

set guifont=Monospace:h20

My recommendation for setting the font is to do (if your version supports it)

set guifont=*

This will pop up a menu that allows you to select the font. After selecting the font, type

set guifont?

To show what the current guifont is set to. After that copy that line into your vimrc or gvimrc. If there are spaces in the font add a \ to escape the space.

set guifont=Monospace\ 20

Install opencv for Python 3.3

Whether or not you install opencv3 manually or from Gohlke's whl package, I found the need to create/edit the file cv.py in site_packages as follows to make compatable with old code:

import cv2 as cv

What does from __future__ import absolute_import actually do?

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

In particular:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Note that python2 pkg/main2.py has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.

How to backup a local Git repository?

Found the simple official way after wading through the walls of text above that would make you think there is none.

Create a complete bundle with:

$ git bundle create <filename> --all

Restore it with:

$ git clone <filename> <folder>

This operation is atomic AFAIK. Check official docs for the gritty details.

Regarding "zip": git bundles are compressed and surprisingly small compared to the .git folder size.

How can I select all elements without a given class in jQuery?

You could use this to pick all li elements without class:

$('ul#list li:not([class])')

How do I show the schema of a table in a MySQL database?

describe [db_name.]table_name;

for formatted output, or

show create table [db_name.]table_name;

for the SQL statement that can be used to create a table.

HTTP vs HTTPS performance

The HTTPS indeed affects page speed...

The quotes above reveal the foolishness of many people about site security and speed. HTTPS / SSL server handshaking creates an initial stall in making Internet connections. There’s a slow delay before anything starts to render on your visitor’s browser screen. This delay is measured in Time-to-First-Byte information.

HTTPS handshake overhead appears in Time-to-First-Byte information (TTFB). Common TTFB ranges from under 100 milliseconds (best-case) to over 1.5 seconds (worst case). But, of course, with HTTPS it’s 500 milliseconds worse.

Roundtrip, wireless 3G connections can be 500 milliseconds or more. The extra trips double delays to 1 second or more. This is a big, negative impact on mobile performance. Very bad news.

My advice, if you're not exchanging sensitive data then you don't need SSL at all, but if you do like an ecommerce website then you can just enable HTTPS on certain pages where sensitive data is exchanged like Login and checkout.

Source: Pagepipe

How to use PHP with Visual Studio

I don't understand how other answers don't answer the original question about how to use PHP (not very consistent with the title).
PHP files or PHP code embedded in HTML code start always with the tag <?php and ends with ?>.

You can embed PHP code inside HTML like this (you have to save the file using .php extension to let PHP server recognize and process it, ie: index.php):

<body>
   <?php echo "<div>Hello World!</div>" ?>
</body>

or you can use a whole php file, ie: test.php:

<?php    
$mycontent = "Hello World!";
echo "<div>$mycontent</div>";
?> // is not mandatory to put this at the end of the file

there's no document.ready in PHP, the scripts are processed when they are invoked from the browser or from another PHP file.

Get values from label using jQuery

I am changing your id to current-month (having no space)

alert($('#current-month').attr('month'));
alert($('#current-month').attr('year'));

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

I have this problem in Mozilla. All time: Error: Unknown error acquiring position.

Now i'm using 47 Mozilla. I have tried everything, but all time this problem. BUT then i open about:config in my addsress bar, go geo.wifi.ui and changed it value to "https://location.services.mozilla.com/v1/geolocate?key=test". works!

If u have Position acquisition timed out error, try to increase timeout value:

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0       
};
navigator.geolocation.getCurrentPosition(success, error, options);

Set UILabel line spacing

Edit: Evidently NSAttributedString will do it, on iOS 6 and later. Instead of using an NSString to set the label's text, create an NSAttributedString, set attributes on it, then set it as the .attributedText on the label. The code you want will be something like this:

NSMutableAttributedString* attrString = [[NSMutableAttributedString  alloc] initWithString:@"Sample text"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:24];
[attrString addAttribute:NSParagraphStyleAttributeName
    value:style
    range:NSMakeRange(0, strLength)];
uiLabel.attributedText = attrString;

NSAttributedString's old attributedStringWithString did the same thing, but now that is being deprecated.

For historical reasons, here's my original answer:

Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, create multiple labels, or use a different font (perhaps one edited for a specific line height, see Phillipe's answer).

Long answer: In the print and online world, the space between lines of text is known as "leading" (rhymes with 'heading', and comes from the lead metal used decades ago). Leading is a read-only property of UIFont, which was deprecated in 4.0 and replaced by lineHeight. As far as I know, there's no way to create a font with a specific set of parameters such as lineHeight; you get the system fonts and any custom font you add, but can't tweak them once installed.

There is no spacing parameter in UILabel, either.

I'm not particularly happy with UILabel's behavior as is, so I suggest writing your own subclass or using a 3rd-party library. That will make the behavior independent of your font choice and be the most reusable solution.

I wish there was more flexibility in UILabel, and I'd be happy to be proven wrong!

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

i found that in the deployment assembly, there was the entry:

[persisted container] org.maven.ide.eclipse.maven2_classpath_container

i removed it, and added the maven dependencies entry, and it works fine now.

How to verify if nginx is running or not?

The modern (systemctl) way of doing it:

systemctl is-active nginx

You can use the exit value in your shell scripts as follows:

systemctl -q is-active nginx && echo "It is active, do something"

Display filename before matching line

How about this, which I managed to achieve thanks, in part, to this post.

You want to find several files, lets say logs with different names but a pattern (e.g. filename=logfile.DATE), inside several directories with a pattern (e.g. /logsapp1, /logsapp2). Each file has a pattern you want to grep (e.g. "init time"), and you want to have the "init time" of each file, but knowing which file it belongs to.

find ./logsapp* -name logfile* | xargs -I{} grep "init time" {} \dev\null | tee outputfilename.txt

Then the outputfilename.txt would be something like

./logsapp1/logfile.22102015: init time: 10ms
./logsapp1/logfile.21102015: init time: 15ms
./logsapp2/logfile.21102015: init time: 17ms
./logsapp2/logfile.22102015: init time: 11ms

In general

find ./path_pattern/to_files* -name filename_pattern* | xargs -I{} grep "grep_pattern" {} \dev\null | tee outfilename.txt

Explanation:

find command will search the filenames based in the pattern

then, pipe xargs -I{} will redirect the find output to the {}

which will be the input for grep ""pattern" {}

Then the trick to make grep display the filenames \dev\null

and finally, write the output in file with tee outputfile.txt

This worked for me in grep version 9.0.5 build 1989.

Can you issue pull requests from the command line on GitHub?

With the Hub command-line wrapper you can link it to git and then you can do git pull-request

From the man page of hub:

   git pull-request [-f] [TITLE|-i ISSUE|ISSUE-URL] [-b BASE] [-h HEAD]
          Opens a pull request on GitHub for the project that the "origin" remote points to. The default head of the pull request is the current branch. Both base and head of the pull request can be explicitly given in one  of  the  following  formats:  "branch",  "owner:branch",
          "owner/repo:branch". This command will abort operation if it detects that the current topic branch has local commits that are not yet pushed to its upstream branch on the remote. To skip this check, use -f.

          If TITLE is omitted, a text editor will open in which title and body of the pull request can be entered in the same manner as git commit message.

          If instead of normal TITLE an issue number is given with -i, the pull request will be attached to an existing GitHub issue. Alternatively, instead of title you can paste a full URL to an issue on GitHub.

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

perhaps this comes too late, but still it could be nice to "document it" for others out there.

I received the same error after experimenting and testing with Remote Desktop Services on a MS Server 2012 with MS SQL Server 2012.

During the Remote Desktop Services install one is asked to create a (local) certificate, and so I did. After finishing the test/experiments I removed the Remote Desktop Services. That's when this error appeared (I cannot say whether the error occured during the test with RDS, I don't remember if I used/tried the SQL Connection during the RDS test).

I am not sure how to solve this since the default certificate does not work for me, but the "RDS" certificate does.

BTW, the certificates are found in App: "SQL Server Configuration Manager" -> "SQL Server Network Configuration" -> Right click: "Protocols for " -> Select "Properties" -> Tab "Certificate"

My default SQL Certificate is named: ConfigMgr SQL Server Identification Certificate, has expiration date: 2114-06-09.

Hope this can give a hint to others.

/Kim

raw vs. html_safe vs. h to unescape html

The difference is between Rails’ html_safe() and raw(). There is an excellent post by Yehuda Katz on this, and it really boils down to this:

def raw(stringish)

  stringish.to_s.html_safe

end

Yes, raw() is a wrapper around html_safe() that forces the input to String and then calls html_safe() on it. It’s also the case that raw() is a helper in a module whereas html_safe() is a method on the String class which makes a new ActiveSupport::SafeBuffer instance — that has a @dirty flag in it.

Refer to "Rails’ html_safe vs. raw".

Filtering a list of strings based on contents

This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:

>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']

Another way is to use the filter function. In Python 2:

>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']

In Python 3, it returns an iterator instead of a list, but you can cast it:

>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']

Though it's better practice to use a comprehension.

Where to put the gradle.properties file

Gradle looks for gradle.properties files in these places:

  • in project build dir (that is where your build script is)
  • in sub-project dir
  • in gradle user home (defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle)

Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).

Reference: https://gradle.org/docs/current/userguide/build_environment.html

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

The ideal answer found in the forum mentioned above is this:

sed -i 's/facebook-android-sdk:4.+/facebook-android-sdk:4.22.1/g' ./node_modules/react-native-fbsdk/android/build.gradle

This works

Shell script to capture Process ID and kill it if exist

A lot of *NIX systems also have either or both pkill(1) and killall(1) which, allows you to kill processes by name. Using them, you can avoid the whole parsing ps problem.

Write-back vs Write-Through caching?

Write-Back is a more complex one and requires a complicated Cache Coherence Protocol(MOESI) but it is worth it as it makes the system fast and efficient.

The only benefit of Write-Through is that it makes the implementation extremely simple and no complicated cache coherency protocol is required.

Laravel 5 Carbon format datetime

Just use the date() and strtotime() function and save your time

$suborder['payment_date'] = date('d-m-Y', strtotime($item['created_at']));

Don't stress!!!

#1062 - Duplicate entry for key 'PRIMARY'

  1. Make sure PRIMARY KEY was selected AUTO_INCREMENT.
  2. Just enable Auto increment by :
    ALTER TABLE [table name] AUTO_INCREMENT = 1
  3. When you execute the insert command you have to skip this key.

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

PostgreSQL 9.0 or later:

Recent versions of Postgres (since late 2010) have the string_agg(expression, delimiter) function which will do exactly what the question asked for, even letting you specify the delimiter string:

SELECT company_id, string_agg(employee, ', ')
FROM mytable
GROUP BY company_id;

Postgres 9.0 also added the ability to specify an ORDER BY clause in any aggregate expression; otherwise, the order is undefined. So you can now write:

SELECT company_id, string_agg(employee, ', ' ORDER BY employee)
FROM mytable
GROUP BY company_id;

Or indeed:

SELECT string_agg(actor_name, ', ' ORDER BY first_appearance)

PostgreSQL 8.4 or later:

PostgreSQL 8.4 (in 2009) introduced the aggregate function array_agg(expression) which concatenates the values into an array. Then array_to_string() can be used to give the desired result:

SELECT company_id, array_to_string(array_agg(employee), ', ')
FROM mytable
GROUP BY company_id;

string_agg for pre-8.4 versions:

In case anyone comes across this looking for a compatibilty shim for pre-9.0 databases, it is possible to implement everything in string_agg except the ORDER BY clause.

So with the below definition this should work the same as in a 9.x Postgres DB:

SELECT string_agg(name, '; ') AS semi_colon_separated_names FROM things;

But this will be a syntax error:

SELECT string_agg(name, '; ' ORDER BY name) AS semi_colon_separated_names FROM things;
--> ERROR: syntax error at or near "ORDER"

Tested on PostgreSQL 8.3.

CREATE FUNCTION string_agg_transfn(text, text, text)
    RETURNS text AS 
    $$
        BEGIN
            IF $1 IS NULL THEN
                RETURN $2;
            ELSE
                RETURN $1 || $3 || $2;
            END IF;
        END;
    $$
    LANGUAGE plpgsql IMMUTABLE
COST 1;

CREATE AGGREGATE string_agg(text, text) (
    SFUNC=string_agg_transfn,
    STYPE=text
);

Custom variations (all Postgres versions)

Prior to 9.0, there was no built-in aggregate function to concatenate strings. The simplest custom implementation (suggested by Vajda Gabo in this mailing list post, among many others) is to use the built-in textcat function (which lies behind the || operator):

CREATE AGGREGATE textcat_all(
  basetype    = text,
  sfunc       = textcat,
  stype       = text,
  initcond    = ''
);

Here is the CREATE AGGREGATE documentation.

This simply glues all the strings together, with no separator. In order to get a ", " inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the "textcat" above. Here is one I put together and tested on 8.3.12:

CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$
  BEGIN
    IF acc IS NULL OR acc = '' THEN
      RETURN instr;
    ELSE
      RETURN acc || ', ' || instr;
    END IF;
  END;
$$ LANGUAGE plpgsql;

This version will output a comma even if the value in the row is null or empty, so you get output like this:

a, b, c, , e, , g

If you would prefer to remove extra commas to output this:

a, b, c, e, g

Then add an ELSIF check to the function like this:

CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$
  BEGIN
    IF acc IS NULL OR acc = '' THEN
      RETURN instr;
    ELSIF instr IS NULL OR instr = '' THEN
      RETURN acc;
    ELSE
      RETURN acc || ', ' || instr;
    END IF;
  END;
$$ LANGUAGE plpgsql;

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

What is the N+1 query problem

The N+1 query problem happens when the data access framework executed N additional SQL statements to fetch the same data that could have been retrieved when executing the primary SQL query.

The larger the value of N, the more queries will be executed, the larger the performance impact. And, unlike the slow query log that can help you find slow running queries, the N+1 issue won’t be spot because each individual additional query runs sufficiently fast to not trigger the slow query log.

The problem is executing a large number of additional queries that, overall, take sufficient time to slow down response time.

Let’s consider we have the following post and post_comments database tables which form a one-to-many table relationship:

The post and post_comments tables

We are going to create the following 4 post rows:

INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence - Part 1', 1)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence - Part 2', 2)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence - Part 3', 3)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence - Part 4', 4)

And, we will also create 4 post_comment child records:

INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Excellent book to understand Java Persistence', 1)
 
INSERT INTO post_comment (post_id, review, id)
VALUES (2, 'Must-read for Java developers', 2)
 
INSERT INTO post_comment (post_id, review, id)
VALUES (3, 'Five Stars', 3)
 
INSERT INTO post_comment (post_id, review, id)
VALUES (4, 'A great reference book', 4)

N+1 query problem with plain SQL

If you select the post_comments using this SQL query:

List<Tuple> comments = entityManager.createNativeQuery("""
    SELECT
        pc.id AS id,
        pc.review AS review,
        pc.post_id AS postId
    FROM post_comment pc
    """, Tuple.class)
.getResultList();

And, later, you decide to fetch the associated post title for each post_comment:

for (Tuple comment : comments) {
    String review = (String) comment.get("review");
    Long postId = ((Number) comment.get("postId")).longValue();
 
    String postTitle = (String) entityManager.createNativeQuery("""
        SELECT
            p.title
        FROM post p
        WHERE p.id = :postId
        """)
    .setParameter("postId", postId)
    .getSingleResult();
 
    LOGGER.info(
        "The Post '{}' got this review '{}'",
        postTitle,
        review
    );
}

You are going to trigger the N+1 query issue because, instead of one SQL query, you executed 5 (1 + 4):

SELECT
    pc.id AS id,
    pc.review AS review,
    pc.post_id AS postId
FROM post_comment pc
 
SELECT p.title FROM post p WHERE p.id = 1
-- The Post 'High-Performance Java Persistence - Part 1' got this review
-- 'Excellent book to understand Java Persistence'
    
SELECT p.title FROM post p WHERE p.id = 2
-- The Post 'High-Performance Java Persistence - Part 2' got this review
-- 'Must-read for Java developers'
     
SELECT p.title FROM post p WHERE p.id = 3
-- The Post 'High-Performance Java Persistence - Part 3' got this review
-- 'Five Stars'
     
SELECT p.title FROM post p WHERE p.id = 4
-- The Post 'High-Performance Java Persistence - Part 4' got this review
-- 'A great reference book'

Fixing the N+1 query issue is very easy. All you need to do is extract all the data you need in the original SQL query, like this:

List<Tuple> comments = entityManager.createNativeQuery("""
    SELECT
        pc.id AS id,
        pc.review AS review,
        p.title AS postTitle
    FROM post_comment pc
    JOIN post p ON pc.post_id = p.id
    """, Tuple.class)
.getResultList();
 
for (Tuple comment : comments) {
    String review = (String) comment.get("review");
    String postTitle = (String) comment.get("postTitle");
 
    LOGGER.info(
        "The Post '{}' got this review '{}'",
        postTitle,
        review
    );
}

This time, only one SQL query is executed to fetch all the data we are further interested in using.

N+1 query problem with JPA and Hibernate

When using JPA and Hibernate, there are several ways you can trigger the N+1 query issue, so it’s very important to know how you can avoid these situations.

For the next examples, consider we are mapping the post and post_comments tables to the following entities:

Post and PostComment entities

The JPA mappings look like this:

@Entity(name = "Post")
@Table(name = "post")
public class Post {
 
    @Id
    private Long id;
 
    private String title;
 
    //Getters and setters omitted for brevity
}
 
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
 
    @Id
    private Long id;
 
    @ManyToOne
    private Post post;
 
    private String review;
 
    //Getters and setters omitted for brevity
}

FetchType.EAGER

Using FetchType.EAGER either implicitly or explicitly for your JPA associations is a bad idea because you are going to fetch way more data that you need. More, the FetchType.EAGER strategy is also prone to N+1 query issues.

Unfortunately, the @ManyToOne and @OneToOne associations use FetchType.EAGER by default, so if your mappings look like this:

@ManyToOne
private Post post;

You are using the FetchType.EAGER strategy, and, every time you forget to use JOIN FETCH when loading some PostComment entities with a JPQL or Criteria API query:

List<PostComment> comments = entityManager
.createQuery("""
    select pc
    from PostComment pc
    """, PostComment.class)
.getResultList();

You are going to trigger the N+1 query issue:

SELECT 
    pc.id AS id1_1_, 
    pc.post_id AS post_id3_1_, 
    pc.review AS review2_1_ 
FROM 
    post_comment pc

SELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 1
SELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 2
SELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 3
SELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 4

Notice the additional SELECT statements that are executed because the post association has to be fetched prior to returning the List of PostComment entities.

Unlike the default fetch plan, which you are using when calling the find method of the EnrityManager, a JPQL or Criteria API query defines an explicit plan that Hibernate cannot change by injecting a JOIN FETCH automatically. So, you need to do it manually.

If you didn't need the post association at all, you are out of luck when using FetchType.EAGER because there is no way to avoid fetching it. That's why it's better to use FetchType.LAZY by default.

But, if you wanted to use post association, then you can use JOIN FETCH to avoid the N+1 query problem:

List<PostComment> comments = entityManager.createQuery("""
    select pc
    from PostComment pc
    join fetch pc.post p
    """, PostComment.class)
.getResultList();

for(PostComment comment : comments) {
    LOGGER.info(
        "The Post '{}' got this review '{}'", 
        comment.getPost().getTitle(), 
        comment.getReview()
    );
}

This time, Hibernate will execute a single SQL statement:

SELECT 
    pc.id as id1_1_0_, 
    pc.post_id as post_id3_1_0_, 
    pc.review as review2_1_0_, 
    p.id as id1_0_1_, 
    p.title as title2_0_1_ 
FROM 
    post_comment pc 
INNER JOIN 
    post p ON pc.post_id = p.id
    
-- The Post 'High-Performance Java Persistence - Part 1' got this review 
-- 'Excellent book to understand Java Persistence'

-- The Post 'High-Performance Java Persistence - Part 2' got this review 
-- 'Must-read for Java developers'

-- The Post 'High-Performance Java Persistence - Part 3' got this review 
-- 'Five Stars'

-- The Post 'High-Performance Java Persistence - Part 4' got this review 
-- 'A great reference book'

FetchType.LAZY

Even if you switch to using FetchType.LAZY explicitly for all associations, you can still bump into the N+1 issue.

This time, the post association is mapped like this:

@ManyToOne(fetch = FetchType.LAZY)
private Post post;

Now, when you fetch the PostComment entities:

List<PostComment> comments = entityManager
.createQuery("""
    select pc
    from PostComment pc
    """, PostComment.class)
.getResultList();

Hibernate will execute a single SQL statement:

SELECT 
    pc.id AS id1_1_, 
    pc.post_id AS post_id3_1_, 
    pc.review AS review2_1_ 
FROM 
    post_comment pc

But, if afterward, you are going to reference the lazy-loaded post association:

for(PostComment comment : comments) {
    LOGGER.info(
        "The Post '{}' got this review '{}'", 
        comment.getPost().getTitle(), 
        comment.getReview()
    );
}

You will get the N+1 query issue:

SELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 1
-- The Post 'High-Performance Java Persistence - Part 1' got this review 
-- 'Excellent book to understand Java Persistence'

SELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 2
-- The Post 'High-Performance Java Persistence - Part 2' got this review 
-- 'Must-read for Java developers'

SELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 3
-- The Post 'High-Performance Java Persistence - Part 3' got this review 
-- 'Five Stars'

SELECT p.id AS id1_0_0_, p.title AS title2_0_0_ FROM post p WHERE p.id = 4
-- The Post 'High-Performance Java Persistence - Part 4' got this review 
-- 'A great reference book'

Because the post association is fetched lazily, a secondary SQL statement will be executed when accessing the lazy association in order to build the log message.

Again, the fix consists in adding a JOIN FETCH clause to the JPQL query:

List<PostComment> comments = entityManager.createQuery("""
    select pc
    from PostComment pc
    join fetch pc.post p
    """, PostComment.class)
.getResultList();

for(PostComment comment : comments) {
    LOGGER.info(
        "The Post '{}' got this review '{}'", 
        comment.getPost().getTitle(), 
        comment.getReview()
    );
}

And, just like in the FetchType.EAGER example, this JPQL query will generate a single SQL statement.

Even if you are using FetchType.LAZY and don't reference the child association of a bidirectional @OneToOne JPA relationship, you can still trigger the N+1 query issue.

How to automatically detect the N+1 query issue

If you want to automatically detect N+1 query issue in your data access layer, you can use the db-util open-source project.

First, you need to add the following Maven dependency:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>db-util</artifactId>
    <version>${db-util.version}</version>
</dependency>

Afterward, you just have to use SQLStatementCountValidator utility to assert the underlying SQL statements that get generated:

SQLStatementCountValidator.reset();

List<PostComment> comments = entityManager.createQuery("""
    select pc
    from PostComment pc
    """, PostComment.class)
.getResultList();

SQLStatementCountValidator.assertSelectCount(1);

In case you are using FetchType.EAGER and run the above test case, you will get the following test case failure:

SELECT 
    pc.id as id1_1_, 
    pc.post_id as post_id3_1_, 
    pc.review as review2_1_ 
FROM 
    post_comment pc

SELECT p.id as id1_0_0_, p.title as title2_0_0_ FROM post p WHERE p.id = 1

SELECT p.id as id1_0_0_, p.title as title2_0_0_ FROM post p WHERE p.id = 2


-- SQLStatementCountMismatchException: Expected 1 statement(s) but recorded 3 instead!

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

Priority queue in .Net

Here is the another implementation from NGenerics team:

NGenerics PriorityQueue

Getting 400 bad request error in Jquery Ajax POST

The question is a bit old... but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.

You have to get name and value from craft in your template :

<script type="text/javascript">
    window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>

and pass them in your request

data: window.csrfTokenName+"="+window.csrfTokenValue

How to use ArrayAdapter<myClass>

Here's a quick and dirty example of how to use an ArrayAdapter if you don't want to bother yourself with extending the mother class:

class MyClass extends Activity {
    private ArrayAdapter<String> mAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mAdapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_dropdown_item_1line, android.R.id.text1);

        final ListView list = (ListView) findViewById(R.id.list);
        list.setAdapter(mAdapter);

        //Add Some Items in your list:
        for (int i = 1; i <= 10; i++) {
            mAdapter.add("Item " + i);
        }

        // And if you want selection feedback:
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Do whatever you want with the selected item
                Log.d(TAG, mAdapter.getItem(position) + " has been selected!");
            }
        });
    }
}

How to Flatten a Multidimensional Array?

Just posting a some else solution)

function flatMultidimensionalArray(array &$_arr): array
{
    $result = [];
    \array_walk_recursive($_arr, static function (&$value, &$key) use (&$result) {
        $result[$key] = $value;
    });

    return $result;
}

How to stop an app on Heroku?

Go to your dashboard on heroku. Select the app. There is a dynos section. Just pull the sliders for the dynos down, (a decrease in dynos is to the left), to the number of dynos you want to be running. The slider goes to 0. Then save your changes. Boom.

According to the comment below: there is a pencil icon that needs to be clicked to accomplish this. I have not checked - but am putting it here in case it helps.

SQL Server ON DELETE Trigger

I would suggest the use of exists instead of in because in some scenarios that implies null values the behavior is different, so

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    DELETE FROM database2.dbo.table2 childTable
    WHERE bar = 4 AND exists (SELECT id FROM deleted where deleted.id = childTable.id)
GO

Parsing huge logfiles in Node.js - read in line-by-line

I had the same problem yet. After comparing several modules that seem to have this feature, I decided to do it myself, it's simpler than I thought.

gist: https://gist.github.com/deemstone/8279565

var fetchBlock = lineByline(filepath, onEnd);
fetchBlock(function(lines, start){ ... });  //lines{array} start{int} lines[0] No.

It cover the file opened in a closure, that fetchBlock() returned will fetch a block from the file, end split to array (will deal the segment from last fetch).

I've set the block size to 1024 for each read operation. This may have bugs, but code logic is obvious, try it yourself.

Reading a .txt file using Scanner class in Java

You have to put file extension here

File file = new File("10_Random.txt");

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

I used this solution

            OpenQA.Selenium.Chrome.ChromeOptions chromeoptions = new OpenQA.Selenium.Chrome.ChromeOptions();
            chromeoptions.AddArgument("--start-maximized");
            OpenQA.Selenium.Chrome.ChromeDriver chrome = new OpenQA.Selenium.Chrome.ChromeDriver(chromeoptions);

How to cancel a Task in await?

Read up on Cancellation (which was introduced in .NET 4.0 and is largely unchanged since then) and the Task-Based Asynchronous Pattern, which provides guidelines on how to use CancellationToken with async methods.

To summarize, you pass a CancellationToken into each method that supports cancellation, and that method must check it periodically.

private async Task TryTask()
{
  CancellationTokenSource source = new CancellationTokenSource();
  source.CancelAfter(TimeSpan.FromSeconds(1));
  Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token);

  // (A canceled task will raise an exception when awaited).
  await task;
}

private int slowFunc(int a, int b, CancellationToken cancellationToken)
{
  string someString = string.Empty;
  for (int i = 0; i < 200000; i++)
  {
    someString += "a";
    if (i % 1000 == 0)
      cancellationToken.ThrowIfCancellationRequested();
  }

  return a + b;
}

How to stop execution after a certain time in Java?

long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
    // run
}

IOException: Too many open files

Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing

/etc/security/limits.conf

by adding something like this

jetty soft nofile 2048
jetty hard nofile 4096

where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf

log off and then log in again and run

ulimit -n

to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.

The default limit 1024 can be too low for large Java applications.

Setting width to wrap_content for TextView through code

There is another way to achieve same result. In case you need to set only one parameter, for example 'height':

TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);

Write Base64-encoded image to file

No need to use BufferedImage, as you already have the image file in a byte array

    byte dearr[] = Base64.decodeBase64(crntImage);
    FileOutputStream fos = new FileOutputStream(new File("c:/decode/abc.bmp")); 
    fos.write(dearr); 
    fos.close();

How can I disable HREF if onclick is executed?

Simply disable default browser behaviour using preventDefault and pass the event within your HTML.

<a href=/foo onclick= yes_js_login(event)>Lorem ipsum</a>

yes_js_login = function(e) {
  e.preventDefault();
}

How do I run a Java program from the command line on Windows?

It is easy. If you have saved your file as A.text first thing you should do is save it as A.java. Now it is a Java file.

Now you need to open cmd and set path to you A.java file before compile it. you can refer this for that.

Then you can compile your file using command

javac A.java

Then run it using

java A

So that is how you compile and run a java program in cmd. You can also go through these material that is Java in depth lessons. Lot of things you need to understand in Java is covered there for beginners.

Reset the Value of a Select Box

I found a little utility function a while back and I've been using it for resetting my form elements ever since (source: http://www.learningjquery.com/2007/08/clearing-form-data):

function clearForm(form) {
  // iterate over all of the inputs for the given form element
  $(':input', form).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase(); // normalize case
    // it's ok to reset the value attr of text inputs, 
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared 
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

... or as a jQuery plugin...

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

Have log4net use application config file for configuration data

Have you tried adding a configsection handler to your app.config? e.g.

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

Detect if an element is visible with jQuery

You're looking for:

.is(':visible')

Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code
}

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.


Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {
    $('#testElement').fadeToggle('fast');
}

How to get the caller's method name in the called method?

I found a way if you're going across classes and want the class the method belongs to AND the method. It takes a bit of extraction work but it makes its point. This works in Python 2.7.13.

import inspect, os

class ClassOne:
    def method1(self):
        classtwoObj.method2()

class ClassTwo:
    def method2(self):
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 4)
        print '\nI was called from', calframe[1][3], \
        'in', calframe[1][4][0][6: -2]

# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()

# start the program
os.system('cls')
classoneObj.method1()

How to open .mov format video in HTML video Tag?

Instead of using <source> tag, use <src> attribute of <video> as below and you will see the action.

<video width="320" height="240" src="mov1.mov"></video>

or

you can give multiple tags within the tag, each with a different video source. The browser will automatically go through the list and pick the first one it’s able to play. For example:

<video id="sampleMovie" width="640" height="360" preload controls>
    <source src="HTML5Sample_H264.mov" />
    <source src="HTML5Sample_Ogg.ogv" />
    <source src="HTML5Sample_WebM.webm" />
</video>

If you test that code in Chrome, you’ll get the H.264 video. Run it in Firefox, though, and you’ll see the Ogg video in the same place.

Make one div visible and another invisible

You can use the display property of style. Intialy set the result section style as

style = "display:none"

Then the div will not be visible and there won't be any white space.

Once the search results are being populated change the display property using the java script like

document.getElementById("someObj").style.display = "block"

Using java script you can make the div invisible

document.getElementById("someObj").style.display = "none"

Difference between java.exe and javaw.exe

The difference is in the subsystem that each executable targets.

  • java.exe targets the CONSOLE subsystem.
  • javaw.exe targets the WINDOWS subsystem.

Select multiple records based on list of Id's with linq

Nice answers abowe, but don't forget one IMPORTANT thing - they provide different results!

  var idList = new int[1, 2, 2, 2, 2]; // same user is selected 4 times
  var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e)).ToList();

This will return 2 rows from DB (and this could be correct, if you just want a distinct sorted list of users)

BUT in many cases, you could want an unsorted list of results. You always have to think about it like about a SQL query. Please see the example with eshop shopping cart to illustrate what's going on:

  var priceListIDs = new int[1, 2, 2, 2, 2]; // user has bought 4 times item ID 2
  var shoppingCart = _dataContext.ShoppingCart
                     .Join(priceListIDs, sc => sc.PriceListID, pli => pli, (sc, pli) => sc)
                     .ToList();

This will return 5 results from DB. Using 'contains' would be wrong in this case.

Generate pdf from HTML in div using Javascript

If you want to export a table, you can take a look at this export sample provided by the Shield UI Grid widget.

It is done by extending the configuration like this:

...
exportOptions: {
    proxy: "/filesaver/save",
    pdf: {
        fileName: "shieldui-export",
        author: "John Smith",
        dataSource: {
            data: gridData
        },
        readDataSource: true,
        header: {
            cells: [
                { field: "id", title: "ID", width: 50 },
                { field: "name", title: "Person Name", width: 100 },
                { field: "company", title: "Company Name", width: 100 },
                { field: "email", title: "Email Address" }
            ]
        }
    }
}
...

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

Eclipse Error: "Failed to connect to remote VM"

Create setenv.bat file in nib folder of Tomcat. Add SET JPDA_ADDRESS = 8787 ; Override the jpda port Open cmd, go to bin folder of Tomcat and Start tomcat using catalina jpda start Set up a debug point on eclipse Next compile your project. Check localhost:8080/ Deploy the war or jar under webapps folder and this must deploy war on Tomcat. Then send the request. the debug point will get hit NOTE : Don't edit catalina.bat file. make changes in setenv.bat file

Reading *.wav files in Python

Different Python modules to read wav:

There is at least these following libraries to read wave audio files:

The most simple example:

This is a simple example with SoundFile:

import soundfile as sf
data, samplerate = sf.read('existing_file.wav') 

Format of the output:

Warning, the data are not always in the same format, that depends on the library. For instance:

from scikits import audiolab
from scipy.io import wavfile
from sys import argv
for filepath in argv[1:]:
    x, fs, nb_bits = audiolab.wavread(filepath)
    print('Reading with scikits.audiolab.wavread:', x)
    fs, x = wavfile.read(filepath)
    print('Reading with scipy.io.wavfile.read:', x)

Output:

Reading with scikits.audiolab.wavread: [ 0.          0.          0.         ..., -0.00097656 -0.00079346 -0.00097656]
Reading with scipy.io.wavfile.read: [  0   0   0 ..., -32 -26 -32]

SoundFile and Audiolab return floats between -1 and 1 (as matab does, that is the convention for audio signals). Scipy and wave return integers, which you can convert to floats according to the number of bits of encoding, for example:

from scipy.io.wavfile import read as wavread
samplerate, x = wavread(audiofilename)  # x is a numpy array of integers, representing the samples 
# scale to -1.0 -- 1.0
if x.dtype == 'int16':
    nb_bits = 16  # -> 16-bit wav files
elif x.dtype == 'int32':
    nb_bits = 32  # -> 32-bit wav files
max_nb_bit = float(2 ** (nb_bits - 1))
samples = x / (max_nb_bit + 1)  # samples is a numpy array of floats representing the samples 

Retrieving Android API version programmatically

I improved code i used

public static float getAPIVerison() {

    float f=1f;
    try {
        StringBuilder strBuild = new StringBuilder();
        strBuild.append(android.os.Build.VERSION.RELEASE.substring(0, 2));
        f= Float.valueOf(strBuild.toString());
    } catch (NumberFormatException e) {
        Log.e("myApp", "error retriving api version" + e.getMessage());
    }

    return f;
}

JRE installation directory in Windows

where java works for me to list all java exe but java -verbose tells you which rt.jar is used and thus which jre (full path):

[Opened C:\Program Files\Java\jre6\lib\rt.jar]
...

Edit: win7 and java:

java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)

Practical uses of different data structures

Any ranking of various data structures will be at least partially tied to problem context. It would help to learn how to analyze time and space performance of algorithms. Typically, "big O notation" is used, e.g. binary search is in O(log n) time, which means that the time to search for an element is the log (in base 2, implicitly) of the number of elements. Intuitively, since every step discards half of the remaining data as irrelevant, doubling the number of elements will increases the time by 1 step. (Binary search scales rather well.) Space performance concerns how the amount of memory grows for larger data sets. Also, note that big-O notation ignores constant factors - for smaller data sets, an O(n^2) algorithm may still be faster than an O(n * log n) algorithm that has a higher constant factor. Complex algorithms often have more work to do on startup.

Besides time and space, other characteristics include whether a data structure is sorted (trees and skiplists are sorted, hash tables are not), persistence (binary trees can reuse pointers from older versions, while hash tables are modified in place), etc.

While you'll need to learn the behavior of several data structures to be able to compare them, one way to develop a sense for why they differ in performance is to closely study a few. I'd suggest comparing singly-linked lists, binary search trees, and skip lists, all of which are relatively simple, but have very different characteristics. Think about how much work it takes to find a value, add a new value, find all values in order, etc.

There are various texts on analyzing algorithms / data structure performance that people recommend, but what really made them make sense to me was learning OCaml. Dealing with complex data structures is ML's strong suit, and their behavior is much clearer when you can avoid pointers and memory management as in C. (Learning OCaml just to understand data structures is almost certainly the long way around, though. :) )

0xC0000005: Access violation reading location 0x00000000

The problem here, as explained in other comments, is that the pointer is being dereference without being properly initialized. Operating systems like Linux keep the lowest addresses (eg first 32MB: 0x00_0000 -0x200_0000) out of the virtual address space of a process. This is done because dereferencing zeroed non-initialized pointers is a common mistake, like in this case. So when this type of mistake happens, instead of actually reading a random variable that happens to be at address 0x0 (but not the memory address the pointer would be intended for if initialized properly), the pointer would be reading from a memory address outside of the process's virtual address space. This causes a page fault, which results in a segmentation fault, and a signal is sent to the process to kill it. That's why you are getting the access violation error.

"Cannot instantiate the type..."

Queue is an Interface not a class.

C++, how to declare a struct in a header file

You should not place an using directive in an header file, it creates unnecessary headaches.

Also you need an include guard in your header.

EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.

git push says "everything up-to-date" even though I have local changes

I had this problem today and it didn't have anything to do with any of the other answers. Here's what I did and how I fixed it:

A repository of mine recently moved, but I had a local copy. I branched off of my local "master" branch and made some changes--and then I remembered that the repository had moved. I used git remote set-url origin https://<my_new_repository_url> to set the new URL but when I pushed it would just say "Everything up to date" instead of pushing my new branch to master.

I ended up solving it by rebasing onto origin/master and then pushing with explicit branch names, like this:

$ git rebase <my_branch> origin/master
$ git push origin <my_branch>

I hope this helps anyone who had my same problem!

Difference between frontend, backend, and middleware in web development

Here is one breakdown:

Front-end tier -> User Interface layer usually consisting of a mix of HTML, Javascript, CSS, Flash, and various server-side code like ASP.Net, classic ASP, PHP, etc. Think of this as being closest to the user in terms of code.

Middleware, middle-tier -> One tier back, generally referred to as the "plumbing" part of a system. Java and C# are common languages for writing this part that could be viewed as the glue between the UI and the data and can be webservices or WCF components or other SOA components possibly.

Back-end tier -> Databases and other data stores are generally at this level. Oracle, MS-SQL, MySQL, SAP, and various off-the-shelf pieces of software come to mind for this piece of software that is the final processing of the data.

Overlap can exist between any of these as you could have everything poured into one layer like an ASP.Net website that uses the built-in AJAX functionality that generates Javascript while the code behind may contain database commands making the code behind contain both middle and back-end tiers. Alternatively, one could use VBScript to act as all the layers using ADO objects and merging all three tiers into one.

Similarly, taking middleware and either front or back-end can be combined in some cases.

Bottlenecks generally have a few different levels to them:

1) Database or back-end processing -> This can vary from payroll or sales or other tasks where the throughput to the database is bogging things down.

2) Middleware bottlenecks -> This would be where some web service may be hitting capacity but the front and back ends have bandwidth to handle more traffic. Alternatively, there may be some server that is part of a system that isn't quite the UI part or the raw data that can be a bottleneck using something like Biztalk or MSMQ.

3) Front-end bottlenecks -> This could client or server-side issues. For example, if you took a low-end PC and had it load a web page that consisted of a lot of data being downloaded, the client could be where the bottleneck is. Similarly, the server could be queuing up requests if it is getting hammered with requests like what Amazon.com or other high-traffic websites may get at times.

Some of this is subject to interpretation, so it isn't perfect by any means and YMMV.


EDIT: Something to consider is that some systems can have multiple front-ends or back-ends. For example, a content management system will likely have a way for site visitors to view the content that is a front-end but what about how content editors are able to change the data on the site? The ability to pull up this data could be seen as front-end since it is a UI component or it could be seen as a back-end since it is used by internal users rather than the general public viewing the site. Thus, there is something to be said for context here.

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

It looks like this error 0xe0434352 applies to a number of different errors.

In case it helps anyone, I ran into this error when I was trying to install my application on a new Windows 10 installation. It worked on other machines, and looked like the app momentarily would start before dying. After much trial and error the problem turned out to be that the app required DirectX9. Though a later version of DirectX was present it had to have version 9. Hope that saves someone some frustration.

How to create UILabel programmatically using Swift?

Swift 4.2 and Xcode 10 Initialize label before viewDidLoad.

lazy var topLeftLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "TopLeft"
    return label
}()

In viewDidLoad add label to the view and apply constraints.

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(topLeftLabel)
    topLeftLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
    topLeftLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
}

Best XML parser for Java

If speed and memory is no problem, dom4j is a really good option. If you need speed, using a StAX parser like Woodstox is the right way, but you have to write more code to get things done and you have to get used to process XML in streams.

Uncaught SyntaxError: Invalid or unexpected token

I also had an issue with multiline strings in this scenario. @Iman's backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:

'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'

Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.

// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

ERROR 1064 (42000) in MySQL

ERROR 1064 (42000) at line 1:

This error is very common. The main reason of the occurrence of this error is: When user accidentally edited or false edit the .sql file.

how to get javaScript event source element?

Try something like this:

<html>
  <body>

    <script type="text/javascript">
        function doSomething(event) {
          var source = event.target || event.srcElement;
          console.log(source);
          alert('test');
          if(window.event) {
            // IE8 and earlier
            // doSomething
           } else if(e.which) {
            // IE9/Firefox/Chrome/Opera/Safari
            // doSomething
           }
        }
     </script>

    <button onclick="doSomething('param')" id="id_button">
      action
    </button>

  </body>      
</html>

How to count the number of lines of a string in javascript

Using a regular expression you can count the number of lines as

 str.split(/\r\n|\r|\n/).length

Alternately you can try split method as below.

var lines = $("#ptest").val().split("\n");  
alert(lines.length);

working solution: http://jsfiddle.net/C8CaX/

how to display none through code behind

try this

<div id="login_div" runat="server">

and on the code behind.

login_div.Style.Add("display", "none");

How to change button background image on mouseOver?

You can create a class based on a Button with specific images for MouseHover and MouseDown like this:

public class AdvancedImageButton : Button {

public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }

protected override void OnMouseEnter(System.EventArgs e)
{
  base.OnMouseEnter(e);
  if (HoverImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = HoverImage;
}

protected override void OnMouseLeave(System.EventArgs e)
{
  base.OnMouseLeave(e);
  if (HoverImage == null) return;
  base.Image = PlainImage;
}

protected override void OnMouseDown(MouseEventArgs e)
{
  base.OnMouseDown(e);
  if (PressedImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = PressedImage;
}

}

This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.

How can I send an email through the UNIX mailx command?

mail [-s subject] [-c ccaddress] [-b bccaddress] toaddress

-c and -b are optional.

-s : Specify subject;if subject contains spaces, use quotes.

-c : Send carbon copies to list of users seperated by comma.

-b : Send blind carbon copies to list of users seperated by comma.

Hope my answer clarifies your doubt.

Why would a JavaScript variable start with a dollar sign?

$ is used to DISTINGUISH between common variables and jquery variables in case of normal variables. let you place a order in FLIPKART then if the order is a variable showing you the string output then it is named simple as "order" but if we click on place order then an object is returned that object will be denoted by $ as "$order" so that the programmer may able to snip out the javascript variables and jquery variables in the entire code.

HTML5: Slider with two inputs possible?

Sure you can simply use two sliders overlaying each other and add a bit of javascript (actually not more than 5 lines) that the selectors are not exceeding the min/max values (like in @Garys) solution.

Attached you'll find a short snippet adapted from a current project including some CSS3 styling to show what you can do (webkit only). I also added some labels to display the selected values.

It uses JQuery but a vanillajs version is no magic though.

@Update: The code below was just a proof of concept. Due to many requests I've added a possible solution for Mozilla Firefox (without changing the original code). You may want to refractor the code below before using it.

_x000D_
_x000D_
    (function() {

        function addSeparator(nStr) {
            nStr += '';
            var x = nStr.split('.');
            var x1 = x[0];
            var x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + '.' + '$2');
            }
            return x1 + x2;
        }

        function rangeInputChangeEventHandler(e){
            var rangeGroup = $(this).attr('name'),
                minBtn = $(this).parent().children('.min'),
                maxBtn = $(this).parent().children('.max'),
                range_min = $(this).parent().children('.range_min'),
                range_max = $(this).parent().children('.range_max'),
                minVal = parseInt($(minBtn).val()),
                maxVal = parseInt($(maxBtn).val()),
                origin = $(this).context.className;

            if(origin === 'min' && minVal > maxVal-5){
                $(minBtn).val(maxVal-5);
            }
            var minVal = parseInt($(minBtn).val());
            $(range_min).html(addSeparator(minVal*1000) + ' €');


            if(origin === 'max' && maxVal-5 < minVal){
                $(maxBtn).val(5+ minVal);
            }
            var maxVal = parseInt($(maxBtn).val());
            $(range_max).html(addSeparator(maxVal*1000) + ' €');
        }

     $('input[type="range"]').on( 'input', rangeInputChangeEventHandler);
})();
_x000D_
body{
font-family: sans-serif;
font-size:14px;
}
input[type='range'] {
  width: 210px;
  height: 30px;
  overflow: hidden;
  cursor: pointer;
    outline: none;
}
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
  -webkit-appearance: none;
    background: none;
}
input[type='range']::-webkit-slider-runnable-track {
  width: 200px;
  height: 1px;
  background: #003D7C;
}

input[type='range']:nth-child(2)::-webkit-slider-runnable-track{
  background: none;
}

input[type='range']::-webkit-slider-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}


input[type='range']:nth-child(1)::-webkit-slider-thumb{
  z-index: 2;
}

.rangeslider{
    position: relative;
    height: 60px;
    width: 210px;
    display: inline-block;
    margin-top: -5px;
    margin-left: 20px;
}
.rangeslider input{
    position: absolute;
}
.rangeslider{
    position: absolute;
}

.rangeslider span{
    position: absolute;
    margin-top: 30px;
    left: 0;
}

.rangeslider .right{
   position: relative;
   float: right;
   margin-right: -5px;
}


/* Proof of concept for Firefox */
@-moz-document url-prefix() {
  .rangeslider::before{
    content:'';
    width:100%;
    height:2px;
    background: #003D7C;
    display:block;
    position: relative;
    top:16px;
  }

  input[type='range']:nth-child(1){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }

  input[type='range']:nth-child(2){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }
input[type='range']::-moz-range-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}

  input[type='range']:nth-child(1)::-moz-range-thumb {
      transform: translateY(-20px);    
  }
  input[type='range']:nth-child(2)::-moz-range-thumb {
      transform: translateY(-20px);    
  }
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="rangeslider">
                                <input class="min" name="range_1" type="range" min="1" max="100" value="10" />
                                <input class="max" name="range_1" type="range" min="1" max="100" value="90" />
                                <span class="range_min light left">10.000 €</span>
                                <span class="range_max light right">90.000 €</span>
                            </div>
_x000D_
_x000D_
_x000D_

MongoDB and "joins"

one kind of join a query in mongoDB, is ask at one collection for id that match , put ids in a list (idlist) , and do find using on other (or same) collection with $in : idlist

u = db.friends.find({"friends": something }).toArray()
idlist= []
u.forEach(function(myDoc) { idlist.push(myDoc.id ); } )
db.family.find({"id": {$in : idlist} } )

How to draw an empty plot?

I suggest that someone needs to make empty plot in order to add some graphics on it later. So, using

plot(1, type="n", xlab="", ylab="", xlim=c(0, 10), ylim=c(0, 10))

you can specify the axes limits of your graphic.

Notepad++ Multi editing

In the position where you want to add text, do:

Shift + Alt + down arrow

and select the lines you want. Then type. The text you type is inserted on all of the lines you selected.

Can I use a binary literal in C or C++?

As already answered, the C standards have no way to directly write binary numbers. There are compiler extensions, however, and apparently C++14 includes the 0b prefix for binary. (Note that this answer was originally posted in 2010.)

One popular workaround is to include a header file with helper macros. One easy option is also to generate a file that includes macro definitions for all 8-bit patterns, e.g.:

#define B00000000 0
#define B00000001 1
#define B00000010 2
…

This results in only 256 #defines, and if larger than 8-bit binary constants are needed, these definitions can be combined with shifts and ORs, possibly with helper macros (e.g., BIN16(B00000001,B00001010)). (Having individual macros for every 16-bit, let alone 32-bit, value is not plausible.)

Of course the downside is that this syntax requires writing all the leading zeroes, but this may also make it clearer for uses like setting bit flags and contents of hardware registers. For a function-like macro resulting in a syntax without this property, see bithacks.h linked above.

Send Post Request with params using Retrofit

Post data to backend using retrofit

 implementation 'com.squareup.retrofit2:retrofit:2.8.1'
 implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
 implementation 'com.google.code.gson:gson:2.8.6'
 implementation 'com.squareup.okhttp3:logging-interceptor:4.5.0'

public interface UserService {
  @POST("users/")
  Call<UserResponse> userRegistration(@Body UserRegistration 
    userRegistration);
}



public class ApiClient {

    private static Retrofit getRetrofit(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.larntech.net/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();



        return retrofit;

    }


    public static UserService getService(){
        UserService userService = getRetrofit().create(UserService.class);
        return userService;
    }

}

Expansion of variables inside single quotes in a command in Bash

Does this work for you?

eval repo forall -c '....$variable'

How to use store and use session variables across pages?

Starting a Session:

Put below code at the top of file.

<?php session_start();?>

Storing a session variable:

<?php $_SESSION['id']=10; ?>

To Check if data stored in session variable:

<?php if(isset($_SESSION['id']) && !empty(isset($_SESSION['id'])))
echo “Session id “.$_SESSION['id'].” exist”;
else
echo “Session not set “;?>

?> detail here http://skillrow.com/sessions-in-php-4/

How to create an on/off switch with Javascript/CSS?

Outline: Create two elements: a slider/switch and a trough as a parent of the slider. To toggle the state, switch the slider element between an "on" and an "off" class. In the style for one class, set "left" to 0 and leave "right" the default; for the other class, do the opposite:

<style type="text/css">
.toggleSwitch {
    width: ...;
    height: ...;
    /* add other styling as appropriate to position element */
    position: relative;
}
.slider {
    background-image: url(...);
    position: absolute;
    width: ...;
    height: ...;
}
.slider.on {
    right: 0;
}
.slider.off {
    left: 0;
}
</style>
<script type="text/javascript">
function replaceClass(elt, oldClass, newClass) {
    var oldRE = RegExp('\\b'+oldClass+'\\b');
    elt.className = elt.className.replace(oldRE, newClass);
}
function toggle(elt, on, off) {
    var onRE = RegExp('\\b'+on+'\\b');
    if (onRE.test(elt.className)) {
        elt.className = elt.className.replace(onRE, off);
    } else {
        replaceClass(elt, off, on);
    }
}
</script>
...
<div class="toggleSwitch" onclick="toggle(this.firstChild, 'on', 'off');"><div class="slider off" /></div>

Alternatively, just set the background image for the "on" and "off" states, which is a much easier approach than mucking about with positioning.

Difference between MEAN.js and MEAN.io

Here is a side-by-side comparison of several application starters/generators and other technologies including MEAN.js, MEAN.io, and cleverstack. I keep adding alternatives as I find time and as that happens, the list of potentially provided benefits keeps growing too. Today it's up to around 1600. If anyone wants to help improve its accuracy or completeness, click the next link and do a questionnaire about something you know.

Compare app technologies project

From this database, the system generates reports like the following:

MeanJS vs MeanIO trade-off report

How to run Spring Boot web application in Eclipse itself?

In my case, I had to select the "src/main/java" and select the "Run As" menu Just like this, so that "Spring Boot App" would be displayed as here.

How do I use cx_freeze?

find the cxfreeze script and run it. It will be in the same path as your other python helper scripts, such as pip.

cxfreeze Main.py --target-dir dist

read more at: http://cx-freeze.readthedocs.org/en/latest/script.html#script

How do I create ColorStateList programmatically?

Sometimes this will be enough:

int colorInt = getResources().getColor(R.color.ColorVerificaLunes);
ColorStateList csl = ColorStateList.valueOf(colorInt);

Detect URLs in text with JavaScript

Here is what I ended up using as my regex:

var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

This doesn't include trailing punctuation in the URL. Crescent's function works like a charm :) so:

function linkify(text) {
    var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(urlRegex, function(url) {
        return '<a href="' + url + '">' + url + '</a>';
    });
}

How to convert binary string value to decimal

public static void convertStringToDecimal(String binary)
{
    int decimal=0;
    int power=0;
    while(binary.length()>0)
    {
        int temp = Integer.parseInt(binary.charAt((binary.length())-1)+"");
        decimal+=temp*Math.pow(2, power++);
        binary=binary.substring(0,binary.length()-1);
    }
    System.out.println(decimal);
}

Checking to see if one array's elements are in another array in PHP

Here's a way I am doing it after researching it for a while. I wanted to make a Laravel API endpoint that checks if a field is "in use", so the important information is: 1) which DB table? 2) what DB column? and 3) is there a value in that column that matches the search terms?

Knowing this, we can construct our associative array:

$SEARCHABLE_TABLE_COLUMNS = [
    'users' => [ 'email' ],
];

Then, we can set our values that we will check:

$table = 'users';
$column = 'email';
$value = '[email protected]';

Then, we can use array_key_exists() and in_array() with eachother to execute a one, two step combo and then act upon the truthy condition:

// step 1: check if 'users' exists as a key in `$SEARCHABLE_TABLE_COLUMNS`
if (array_key_exists($table, $SEARCHABLE_TABLE_COLUMNS)) {

    // step 2: check if 'email' is in the array: $SEARCHABLE_TABLE_COLUMNS[$table]
    if (in_array($column, $SEARCHABLE_TABLE_COLUMNS[$table])) {

        // if table and column are allowed, return Boolean if value already exists
        // this will either return the first matching record or null
        $exists = DB::table($table)->where($column, '=', $value)->first();

        if ($exists) return response()->json([ 'in_use' => true ], 200);
        return response()->json([ 'in_use' => false ], 200);
    }

    // if $column isn't in $SEARCHABLE_TABLE_COLUMNS[$table],
    // then we need to tell the user we can't proceed with their request
    return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}

// if $table isn't a key in $SEARCHABLE_TABLE_COLUMNS,
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);

I apologize for the Laravel-specific PHP code, but I will leave it because I think you can read it as pseudo-code. The important part is the two if statements that are executed synchronously.

array_key_exists() and in_array() are PHP functions.

source:

The nice thing about the algorithm that I showed above is that you can make a REST endpoint such as GET /in-use/{table}/{column}/{value} (where table, column, and value are variables).

You could have:

$SEARCHABLE_TABLE_COLUMNS = [
    'accounts' => [ 'account_name', 'phone', 'business_email' ],
    'users' => [ 'email' ],
];

and then you could make GET requests such as:

GET /in-use/accounts/account_name/Bob's Drywall (you may need to uri encode the last part, but usually not)

GET /in-use/accounts/phone/888-555-1337

GET /in-use/users/email/[email protected]

Notice also that no one can do:

GET /in-use/users/password/dogmeat1337 because password is not listed in your list of allowed columns for user.

Good luck on your journey.

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

Join 'methods' are available in Arrays and the classes that extend AbstractCollections but doesn't override toString() method (like virtually all collections in java.util).

For instance:

String s= java.util.Arrays.toString(collectionOfStrings.toArray());
s = s.substing(1, s.length()-1);// [] are guaranteed to be there

That's quite weird way since it works only for numbers alike data SQL wise.

How do I hide a menu item in the actionbar?

You are trying to access a menu item from an activity, which dont have the access to scope. The call to find the menu item will return null, because the view is not binded with neither the activity nor the layout you are calling from.

The menu items are binded with items such as "Navigation Bar" which in turn are binded with the corresponding activity.

So initialize those views in activity (), and then access the menu items withing that views.

Navigation navView;
navView = findViewById(R.id.navigationView);

MenuItem item = navView.getMenu().findItem(R.id.item_hosting);
item.setVisible(false);

Format date and time in a Windows batch script

To generate a YYYY-MM-DD hh:mm:ss (24-hour) timestamp I use:

SET CURRENTTIME=%TIME%
IF "%CURRENTTIME:~0,1%"==" " (SET CURRENTTIME=0%CURRENTTIME:~1%)
FOR /F "tokens=2-4 delims=/ " %%A IN ('DATE /T') DO (SET TIMESTAMP=%%C-%%A-%%B %CURRENTTIME%)

python: how to get information about a function?

Try

help(my_list)

to get built-in help messages.

How to fix SSL certificate error when running Npm on Windows?

npm config set strict-ssl false

solved the issue for me. In this case both my agent and artifact depository are behind a private subnet on aws cloud

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

Put <packaging>war</packaging> in your pom.xml if you are using Maven. In that case, maybe it is with jar packaging

You must have Maven libs in Deployment Assembly

using CASE in the WHERE clause

You can transform logical implication A => B to NOT A or B. This is one of the most basic laws of logic. In your case it is something like this:

SELECT *
FROM logs 
WHERE pw='correct' AND (id>=800 OR success=1)  
AND YEAR(timestamp)=2011

I also transformed NOT id<800 to id>=800, which is also pretty basic.

How can I increase the size of a bootstrap button?

You can try to use btn-sm, btn-xs and btn-lg classes like this:

.btn-xl {
    padding: 10px 20px;
    font-size: 20px;
    border-radius: 10px;
}

JSFIDDLE DEMO

You can make use of Bootstrap .btn-group-justified css class. Or you can simply add:

.btn-xl {
    padding: 10px 20px;
    font-size: 20px;
    border-radius: 10px;
    width:50%;    //Specify your width here
}

JSFIDDLE DEMO

Node.js project naming conventions for files & folders

Based on 'Google JavaScript Style Guide'

File names must be all lowercase and may include underscores (_) or dashes (-), but no additional punctuation. Follow the convention that your project uses. Filenames’ extension must be .js.

vbscript output to console

I came across this post and went back to an approach that I used some time ago which is similar to @MadAntrax's.

The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.

This assumes that your objective is to stream output to the console, rather than having output go to message boxes.

The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:

    Option Explicit

'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE

'// Now we can use the Consol object to write to and read from the console
With CONS

    '// Simply write a line
     .print "CSCRIPT Console demo script"

     '// Arguments are passed through correctly, if present
     .Print "Arg count=" & wscript.arguments.count

     '// List all the arguments on the console log
     dim ix
     for ix = 0 to wscript.arguments.count -1
        .print "Arg(" & ix & ")=" & wscript.arguments(ix)
     next

     '// Prompt for some text from the user
     dim sMsg : sMsg = .prompt( "Enter any text:" )

     '// Write out the text in a box
     .Box sMsg

     '// Pause with the message "Hit enter to continue"
     .Pause

End With     




'= =========== End of script - the cCONSOLE class code follows here

Here is the code for the cCONSOLE class

     CLASS cCONSOLE
 '= =================================================================
 '= 
 '=    This class provides automatic switch to CScript and has methods
 '=    to write to and read from the CSCript console. It transparently
 '=    switches to CScript if the script has been started in WScript.
 '=
 '= =================================================================

    Private oOUT
    Private oIN


    Private Sub Class_Initialize()
    '= Run on creation of the cCONSOLE object, checks for cScript operation


        '= Check to make sure we are running under CScript, if not restart
        '= then run using CScript and terminate this instance.
        dim oShell
        set oShell = CreateObject("WScript.Shell")

        If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
            '= Not running under CSCRIPT

            '= Get the arguments on the command line and build an argument list
            dim ArgList, IX
            ArgList = ""

            For IX = 0 to wscript.arguments.count - 1
                '= Add the argument to the list, enclosing it in quotes
                argList = argList & " """ & wscript.arguments.item(IX) & """"
            next

            '= Now restart with CScript and terminate this instance
            oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
            WScript.Quit

        End If

        '= Running under CScript so OK to continue
        set oShell = Nothing

        '= Save references to stdout and stdin for use with Print, Read and Prompt
        set oOUT = WScript.StdOut
        set oIN = WScript.StdIn

        '= Print out the startup box 
            StartBox
            BoxLine Wscript.ScriptName
            BoxLine "Started at " & Now()
            EndBox


    End Sub

    '= Utility methods for writing a box to the console with text in it

            Public Sub StartBox()

                Print "  " & String(73, "_") 
                Print " |" & Space(73) & "|"
            End Sub

            Public Sub BoxLine(sText)

                Print Left(" |" & Centre( sText, 74) , 75) & "|"
            End Sub

            Public Sub EndBox()
                Print " |" & String(73, "_") & "|"
                Print ""
            End Sub

            Public Sub Box(sMsg)
                StartBox
                BoxLine sMsg
                EndBox
            End Sub

    '= END OF Box utility methods


            '= Utility to center given text padded out to a certain width of text
            '= assuming font is monospaced
            Public Function Centre(sText, nWidth)
                dim iLen
                iLen = len(sText)

                '= Check for overflow
                if ilen > nwidth then Centre = sText : exit Function

                '= Calculate padding either side
                iLen = ( nWidth - iLen ) / 2

                '= Generate text with padding
                Centre = left( space(iLen) & sText & space(ilen), nWidth )
            End Function



    '= Method to write a line of text to the console
    Public Sub Print( sText )

        oOUT.WriteLine sText
    End Sub

    '= Method to prompt user input from the console with a message
    Public Function Prompt( sText )
        oOUT.Write sText
        Prompt = Read()
    End Function

    '= Method to read input from the console with no prompting
    Public Function Read()
        Read = oIN.ReadLine
    End Function

    '= Method to provide wait for n seconds
    Public Sub Wait(nSeconds)
        WScript.Sleep  nSeconds * 1000 
    End Sub

    '= Method to pause for user to continue
    Public Sub Pause
        Prompt "Hit enter to continue..."
    End Sub


 END CLASS

How do I get the current username in Windows PowerShell?

I thought it would be valuable to summarize and compare the given answers.

If you want to access the environment variable:

(easier/shorter/memorable option)

  • [Environment]::UserName -- @ThomasBratt
  • $env:username -- @Eoin
  • whoami -- @galaktor

If you want to access the Windows access token:

(more dependable option)

  • [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -- @MarkSeemann

If you want the name of the logged in user

(rather than the name of the user running the PowerShell instance)

  • $(Get-WMIObject -class Win32_ComputerSystem | select username).username -- @TwonOfAn on this other forum

Comparison

@Kevin Panko's comment on @Mark Seemann's answer deals with choosing one of the categories over the other:

[The Windows access token approach] is the most secure answer, because $env:USERNAME can be altered by the user, but this will not be fooled by doing that.

In short, the environment variable option is more succinct, and the Windows access token option is more dependable.

I've had to use @Mark Seemann's Windows access token approach in a PowerShell script that I was running from a C# application with impersonation.

The C# application is run with my user account, and it runs the PowerShell script as a service account. Because of a limitation of the way I'm running the PowerShell script from C#, the PowerShell instance uses my user account's environment variables, even though it is run as the service account user.

In this setup, the environment variable options return my account name, and the Windows access token option returns the service account name (which is what I wanted), and the logged in user option returns my account name.


Testing

Also, if you want to compare the options yourself, here is a script you can use to run a script as another user. You need to use the Get-Credential cmdlet to get a credential object, and then run this script with the script to run as another user as argument 1, and the credential object as argument 2.

Usage:

$cred = Get-Credential UserTo.RunAs
Run-AsUser.ps1 "whoami; pause" $cred
Run-AsUser.ps1 "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; pause" $cred

Contents of Run-AsUser.ps1 script:

param(
  [Parameter(Mandatory=$true)]
  [string]$script,
  [Parameter(Mandatory=$true)]
  [System.Management.Automation.PsCredential]$cred
)

Start-Process -Credential $cred -FilePath 'powershell.exe' -ArgumentList 'noprofile','-Command',"$script"

How do you replace all the occurrences of a certain character in a string?

The problem is you're not doing anything with the result of replace. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.

line[8] = line[8].replace(letter, "")

Extract csv file specific columns to list in Python

This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv module:

import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)

If you want your lists as in the question, you can now do:

names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()

React JS - Uncaught TypeError: this.props.data.map is not a function

I had the same problem. The solution was to change the useState initial state value from string to array. In App.js, previous useState was

const [favoriteFilms, setFavoriteFilms] = useState('');

I changed it to

const [favoriteFilms, setFavoriteFilms] = useState([]);

and the component that uses those values stopped throwing error with .map function.

How do I see what character set a MySQL database / table / column is?

show global variables where variable_name like 'character_set_%' or variable_name like 'collation%'

Protect .NET code from reverse engineering?

It's impossible to fully secure an application, sorry.

How to update ruby on linux (ubuntu)?

Generally the verions of programs are linked to the version of your operating system. So if you were running gutsy you would either have to upgrade to the new jaunty jackalope version which has ruby 1.9 or add the respoistories for jaunty to your /etc/apt/sources.list file. Once you have done that you can start up the synaptic package manager and you should see it in there.

Grep for beginning and end of line?

Many answers provided for this question. Just wanted to add one more which uses bashism-

#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"

@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).

How do I merge changes to a single file, rather than merging commits?

Here's what I do in these situations. It's a kludge but it works just fine for me.

  1. Create another branch based off of your working branch.
  2. git pull/git merge the revision (SHA1) which contains the file you want to copy. So this will merge all of your changes, but we are only using this branch to grab the one file.
  3. Fix up any Conflicts etc. investigate your file.
  4. checkout your working branch
  5. Checkout the file commited from your merge.
  6. Commit it.

I tried patching and my situation was too ugly for it. So in short it would look like this:

Working Branch: A Experimental Branch: B (contains file.txt which has changes I want to fold in.)

git checkout A

Create new branch based on A:

git checkout -b tempAB

Merge B into tempAB

git merge B

Copy the sha1 hash of the merge:

git log

commit 8dad944210dfb901695975886737dc35614fa94e
Merge: ea3aec1 0f76e61
Author: matthewe <[email protected]>
Date:   Wed Oct 3 15:13:24 2012 -0700

Merge branch 'B' into tempAB

Checkout your working branch:

git checkout A

Checkout your fixed-up file:

git checkout 7e65b5a52e5f8b1979d75dffbbe4f7ee7dad5017 file.txt

And there you should have it. Commit your result.

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

You will have to hand code it, SQL Profiler reveals the following.

SMSE executes quite a long string of queries when it generates the statement.

The following query (or something along its lines) is used to extract the text:

SELECT
NULL AS [Text],
ISNULL(smsp.definition, ssmsp.definition) AS [Definition]
FROM
sys.all_objects AS sp
LEFT OUTER JOIN sys.sql_modules AS smsp ON smsp.object_id = sp.object_id
LEFT OUTER JOIN sys.system_sql_modules AS ssmsp ON ssmsp.object_id = sp.object_id
WHERE
(sp.type = N'P' OR sp.type = N'RF' OR sp.type='PC')and(sp.name=N'#test___________________________________________________________________________________________________________________00003EE1' and SCHEMA_NAME(sp.schema_id)=N'dbo')

It returns the pure CREATE which is then substituted with ALTER in code somewhere.

The SET ANSI NULL stuff and the GO statements and dates are all prepended to this.

Go with sp_helptext, its simpler ...

Purpose of #!/usr/bin/python3 shebang

To clarify how the shebang line works for windows, from the 3.7 Python doc:

  • If the first line of a script file starts with #!, it is known as a “shebang” line. Linux and other Unix like operating systems have native support for such lines and they are commonly used on such systems to indicate how a script should be executed.
  • The Python Launcher for Windows allows the same facilities to be used with Python scripts on Windows
  • To allow shebang lines in Python scripts to be portable between Unix and Windows, the launcher supports a number of ‘virtual’ commands to specify which interpreter to use. The supported virtual commands are:
    • /usr/bin/env python
      • The /usr/bin/env form of shebang line has one further special property. Before looking for installed Python interpreters, this form will search the executable PATH for a Python executable. This corresponds to the behaviour of the Unix env program, which performs a PATH search.
    • /usr/bin/python
    • /usr/local/bin/python
    • python

Animation CSS3: display + opacity

I had the same problem. I tried using animations instead of transitions - as suggested by @MichaelMullany and @Chris - but it only worked for webkit browsers even if I copy-pasted with "-moz" and "-o" prefixes.

I was able to get around the problem by using visibility instead of display. This works for me because my child element is position: absolute, so document flow isn't being affected. It might work for others too.

This is what the original code would look like using my solution:

.child {
    position: absolute;
    opacity: 0;
    visibility: hidden;

    -webkit-transition: opacity 0.5s ease-in-out;
    -moz-transition: opacity 0.5s ease-in-out;
    transition: opacity 0.5s ease-in-out;
}

.parent:hover .child {
    position: relative;
    opacity: 0.9;
    visibility: visible;
}

iPhone and WireShark

The tcpdump tool is available under gnu.

You can use it instead of wireshark.

Regex matching in a Bash if statement

There are a couple of important things to know about bash's [[ ]] construction. The first:

Word splitting and pathname expansion are not performed on the words between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.

The second thing:

An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.

Consequently, $v on either side of the =~ will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.

So if you write: [[ $x =~ [$0-9a-zA-Z] ]], the $0 inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0 ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]], then the right-hand side will be treated as an ordinary string, not a regex (and $0 will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]

Similarly, the expression between the [[ and ]] is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]. Other characters similarly need to be escaped, like #, which would start a comment if not quoted. Of course, you can put the pattern into a variable:

pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...

For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:

# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...

Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:

valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...

! negates the test, turning it into a "does not match" operator, and a [^...] regex character class means "any character other than ...".

The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ] into $valid, even if $valid were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ] in a character class, it needs to go at the beginning. - can go at the beginning or the end, so if you need both ] and -, you need to start with ] and end with -, leading to the regex "I know what I'm doing" emoticon: [][-])

How to enable LogCat/Console in Eclipse for Android?

In Eclipse, Goto Window-> Show View -> Other -> Android-> Logcat.

Logcat is nothing but a console of your Emulator or Device.

System.out.println does not work in Android. So you have to handle every thing in Logcat. More Info Look out this Documentation.

Edit 1: System.out.println is working on Logcat. If you use that the Tag will be like System.out and Message will be your message.

MySQL: ALTER TABLE if column not exists

I used this approach (Without using stored procedure):

SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbl_name' AND COLUMN_NAME = 'column_name'

If it didnt return any rows then the column doesn't exists then alter the table:

ALTER TABLE tbl_name ADD COLUMN column_name TINYINT(1) NOT NULL DEFAULT 1

Hope this helps.

How do I call one constructor from another in Java?

Using this(args). The preferred pattern is to work from the smallest constructor to the largest.

public class Cons {

    public Cons() {
        // A no arguments constructor that sends default values to the largest
        this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
    }

    public Cons(int arg1, int arg2) {
       // An example of a partial constructor that uses the passed in arguments
        // and sends a hidden default value to the largest
        this(arg1,arg2, madeUpArg3Value);
    }

    // Largest constructor that does the work
    public Cons(int arg1, int arg2, int arg3) {
        this.arg1 = arg1;
        this.arg2 = arg2;
        this.arg3 = arg3;
    }
}

You can also use a more recently advocated approach of valueOf or just "of":

public class Cons {
    public static Cons newCons(int arg1,...) {
        // This function is commonly called valueOf, like Integer.valueOf(..)
        // More recently called "of", like EnumSet.of(..)
        Cons c = new Cons(...);
        c.setArg1(....);
        return c;
    }
} 

To call a super class, use super(someValue). The call to super must be the first call in the constructor or you will get a compiler error.

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

I wanted to filter out dfbc rows that had a BUSINESS_ID that was also in the BUSINESS_ID of dfProfilesBusIds

dfbc = dfbc[~dfbc['BUSINESS_ID'].isin(dfProfilesBusIds['BUSINESS_ID'])]