Programs & Examples On #Quad

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

App.settings - the Angular way?

If you are using , there is yet another option:

Angular CLI provides environment files in src/environments (default ones are environment.ts (dev) and environment.prod.ts (production)).

Note that you need to provide the config parameters in all environment.* files, e.g.,

environment.ts:

export const environment = {
  production: false,
  apiEndpoint: 'http://localhost:8000/api/v1'
};

environment.prod.ts:

export const environment = {
  production: true,
  apiEndpoint: '__your_production_server__'
};

and use them in your service (the correct environment file is chosen automatically):

api.service.ts

// ... other imports
import { environment } from '../../environments/environment';

@Injectable()
export class ApiService {     

  public apiRequest(): Observable<MyObject[]> {
    const path = environment.apiEndpoint + `/objects`;
    // ...
  }

// ...
}

Read more on application environments on Github (Angular CLI version 6) or in the official Angular guide (version 7).

Install pip in docker

While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt and python-pip. Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    php5-mcrypt \
    python-pip

However, according to this answer you should think about installing the python3-pip package instead of the python-pip package when using Python 3.x.

Furthermore, to make the php5-mcrypt package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository command missing in the Ubuntu Docker image so I installed the package software-properties-common at first to make the command available.

Splitting up the statements and putting apt-get update and apt-get install into one RUN command is also recommended here.

Oh and by the way, you actually don't need the -y flag at apt-get update because there is nothing that has to be confirmed automatically.

Finally:

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
    apache2 \
    curl \
    git \
    libapache2-mod-php5 \
    php5 \
    php5-mcrypt \
    php5-mysql \
    python3.4 \
    python3-pip

Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

Try x-1 in (i for i in range(x)) for large x values, which uses a generator comprehension to avoid invoking the range.__contains__ optimisation.

How many bits is a "word"?

On x86/x64 processors, a byte is 8 bits, and there are 256 possible binary states in 8 bits, 0 thru 255. This is how the OS translates your keyboard key strokes into letters on the screen. When you press the 'A' key, the keyboard sends a binary signal equal to the number 97 to the computer, and the computer prints a lowercase 'a' on the screen. You can confirm this in any Windows text editing software by holding an ALT key, typing 97 on the NUMPAD, then releasing the ALT key. If you replace '97' with any number from 0 to 255, you will see the character associated with that number on the system's character code page printed on the screen.

If a character is 8 bits, or 1 byte, then a WORD must be at least 2 characters, so 16 bits or 2 bytes. Traditionally, you might think of a word as a varying number of characters, but in a computer, everything that is calculable is based on static rules. Besides, a computer doesn't know what letters and symbols are, it only knows how to count numbers. So, in computer language, if a WORD is equal to 2 characters, then a double-word, or DWORD, is 2 WORDs, which is the same as 4 characters or bytes, which is equal to 32 bits. Furthermore, a quad-word, or QWORD, is 2 DWORDs, same as 4 WORDs, 8 characters, or 64 bits.

Note that these terms are limited in function to the Windows API for developers, but may appear in other circumstances (eg. the Linux dd command uses numerical suffixes to compound byte and block sizes, where c is 1 byte and w is bytes).

Drawing Circle with OpenGL

There is another way to draw a circle - draw it in fragment shader. Create a quad:

float right = 0.5;
float bottom = -0.5;
float left = -0.5;
float top = 0.5;
float quad[20] = {
    //x, y, z, lx, ly
    right, bottom, 0, 1.0, -1.0,
    right, top, 0, 1.0, 1.0,
    left, top, 0, -1.0, 1.0,
    left, bottom, 0, -1.0, -1.0,
};

Bind VBO:

unsigned int glBuffer;
glGenBuffers(1, &glBuffer);
glBindBuffer(GL_ARRAY_BUFFER, glBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*20, quad, GL_STATIC_DRAW);

and draw:

#define BUFFER_OFFSET(i) ((char *)NULL + (i))
glEnableVertexAttribArray(ATTRIB_VERTEX);
glEnableVertexAttribArray(ATTRIB_VALUE);
glVertexAttribPointer(ATTRIB_VERTEX , 3, GL_FLOAT, GL_FALSE, 20, 0);
glVertexAttribPointer(ATTRIB_VALUE , 2, GL_FLOAT, GL_FALSE, 20, BUFFER_OFFSET(12));
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

Vertex shader

attribute vec2 value;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
varying vec2 val;
void main() {
    val = value;
    gl_Position = projectionMatrix*viewMatrix*vertex;
}

Fragment shader

varying vec2 val;
void main() {
    float R = 1.0;
    float R2 = 0.5;
    float dist = sqrt(dot(val,val));
    if (dist >= R || dist <= R2) {
        discard;
    }
    float sm = smoothstep(R,R-0.01,dist);
    float sm2 = smoothstep(R2,R2+0.01,dist);
    float alpha = sm*sm2;
    gl_FragColor = vec4(0.0, 0.0, 1.0, alpha);
}

Don't forget to enable alpha blending:

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

UPDATE: Read more

How can I open a .tex file?

A .tex file should be a LaTeX source file.

If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.

Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.


Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.

You can also check out this question and answer for how to do it: How to compile a LaTeX document?

Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.

How do I catch a numpy warning like it's an exception (not just for testing)?

To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings('error')
    try:
        answer = 1 / 0
    except Warning as e:
        print('error found:', e)

You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.

Solving Quadratic Equation

# syntaxis:2.7
# solution for quadratic equation
# a*x**2 + b*x + c = 0

d = b**2-4*a*c # discriminant

if d < 0:
    print 'No solutions'
elif d == 0:
    x1 = -b / (2*a)
    print 'The sole solution is',x1
else: # if d > 0
    x1 = (-b + math.sqrt(d)) / (2*a)
    x2 = (-b - math.sqrt(d)) / (2*a)
    print 'Solutions are',x1,'and',x2

How prevent CPU usage 100% because of worker process in iis

I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.

Solution:

First of all find the application which is causing heavy memory usage.

You can find this in the Details section of the Task Manager.

Next.

  1. Open the IIS manager.
  2. Click on Application Pools. You'll find many application pools which your system is using.
  3. Now from the task manager you've found which application is causing the heavy memory consumption. There would be multiple options for that and you need to select the one which is having '1' in it's Application column of your web application.
  4. When you click on the application pool on the right hand side you'll see an option Advance settings under Edit Application pools. Go to Advanced Settings. 5.Now under General category set the Enable 32-bit Applications to True
  5. Restart the IIS server or you can see the consumption goes down in performance section of your Task Manager.

If this solution works for you please add a comment so that I can know.

Utilizing multi core for tar+gzip/bzip compression/decompression

You can use pigz instead of gzip, which does gzip compression on multiple cores. Instead of using the -z option, you would pipe it through pigz:

tar cf - paths-to-archive | pigz > archive.tar.gz

By default, pigz uses the number of available cores, or eight if it could not query that. You can ask for more with -p n, e.g. -p 32. pigz has the same options as gzip, so you can request better compression with -9. E.g.

tar cf - paths-to-archive | pigz -9 -p 32 > archive.tar.gz

Quadratic and cubic regression in Excel

The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.

Difference between nVidia Quadro and Geforce cards?

Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".

Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.

For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.

Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.

Any reason not to use '+' to concatenate two strings?

I have done a quick test:

import sys

str = e = "a xxxxxxxxxx very xxxxxxxxxx long xxxxxxxxxx string xxxxxxxxxx\n"

for i in range(int(sys.argv[1])):
    str = str + e

and timed it:

mslade@mickpc:/binks/micks/ruby/tests$ time python /binks/micks/junk/strings.py  8000000
8000000 times

real    0m2.165s
user    0m1.620s
sys     0m0.540s
mslade@mickpc:/binks/micks/ruby/tests$ time python /binks/micks/junk/strings.py  16000000
16000000 times

real    0m4.360s
user    0m3.480s
sys     0m0.870s

There is apparently an optimisation for the a = a + b case. It does not exhibit O(n^2) time as one might suspect.

So at least in terms of performance, using + is fine.

OpenCV Python rotate image by X degrees around specific point

You can easily rotate the images using opencv python-

def funcRotate(degree=0):
    degree = cv2.getTrackbarPos('degree','Frame')
    rotation_matrix = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)
    rotated_image = cv2.warpAffine(original, rotation_matrix, (width, height))
    cv2.imshow('Rotate', rotated_image)

If you are thinking of creating a trackbar, then simply create a trackbar using cv2.createTrackbar() and the call the funcRotate()fucntion from your main script. Then you can easily rotate it to any degree you want. Full details about the implementation can be found here as well- Rotate images at any degree using Trackbars in opencv

How to calculate the angle between a line and the horizontal axis?

Based on reference "Peter O".. Here is the java version

private static final float angleBetweenPoints(PointF a, PointF b) {
float deltaY = b.y - a.y;
float deltaX = b.x - a.x;
return (float) (Math.atan2(deltaY, deltaX)); }

How do I compile the asm generated by GCC?

You can use GAS, which is gcc's backend assembler:

http://linux.die.net/man/1/as

how to draw smooth curve through N points using javascript HTML5 canvas?

This code is perfect for me:

this.context.beginPath();
this.context.moveTo(data[0].x, data[0].y);
for (let i = 1; i < data.length; i++) {
  this.context.bezierCurveTo(
    data[i - 1].x + (data[i].x - data[i - 1].x) / 2,
    data[i - 1].y,
    data[i - 1].x + (data[i].x - data[i - 1].x) / 2,
    data[i].y,
    data[i].x,
    data[i].y);
}

you have correct smooth line and correct endPoints NOTICE! (y = "canvas height" - y);

Creating a 3D sphere in Opengl using Visual C++

I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:

inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
    int curRow = r * sectors;
    int nextRow = (r+1) * sectors;

    indices.push_back(curRow + s);
    indices.push_back(nextRow + s);
    indices.push_back(nextRow + (s+1));

    indices.push_back(curRow + s);
    indices.push_back(nextRow + (s+1));
    indices.push_back(curRow + (s+1));
}

void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
             float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);

    for(int r = 0; r < rings; ++r) {
        for(int s = 0; s < sectors; ++s) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

            texcoords.push_back(vec2(s*S, r*R));
            vertices.push_back(vec3(x,y,z) * radius);
            push_indices(indices, sectors, r, s);
        }
    }
}

JList add/remove Item

The problem is

listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());

you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.

Try

private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
    {
        lm2 = new DefaultListModel();
        listaTitolari.setModel(lm2);
    }
    lm2.addElement(listaTitolari.getSelectedValue());
    lm1.removeElement(listaTitolari.getSelectedValue());        
} 

$ is not a function - jQuery error

As RPM1984 refers to, this is mostly likely caused by the fact that your script is loading before jQuery is loaded.

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

Removing the xml declaration solved it

<?xml version='1.0' encoding='utf-8'?>

How to create a CPU spike with a bash command

I use stress for this kind of thing, you can tell it how many cores to max out.. it allows for stressing memory and disk as well.

Example to stress 2 cores for 60 seconds

stress --cpu 2 --timeout 60

What does O(log n) mean exactly?

The best way I've always had to mentally visualize an algorithm that runs in O(log n) is as follows:

If you increase the problem size by a multiplicative amount (i.e. multiply its size by 10), the work is only increased by an additive amount.

Applying this to your binary tree question so you have a good application: if you double the number of nodes in a binary tree, the height only increases by 1 (an additive amount). If you double it again, it still only increased by 1. (Obviously I'm assuming it stays balanced and such). That way, instead of doubling your work when the problem size is multiplied, you're only doing very slightly more work. That's why O(log n) algorithms are awesome.

Removing duplicates from a list of lists

>>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
>>> k = sorted(k)
>>> k
[[1, 2], [1, 2], [3], [4], [4], [5, 6, 2]]
>>> dedup = [k[i] for i in range(len(k)) if i == 0 or k[i] != k[i-1]]
>>> dedup
[[1, 2], [3], [4], [5, 6, 2]]

I don't know if it's necessarily faster, but you don't have to use to tuples and sets.

Time complexity of accessing a Python dict

It would be easier to make suggestions if you provided example code and data.

Accessing the dictionary is unlikely to be a problem as that operation is O(1) on average, and O(N) amortized worst case. It's possible that the built-in hashing functions are experiencing collisions for your data. If you're having problems with has the built-in hashing function, you can provide your own.

Python's dictionary implementation reduces the average complexity of dictionary lookups to O(1) by requiring that key objects provide a "hash" function. Such a hash function takes the information in a key object and uses it to produce an integer, called a hash value. This hash value is then used to determine which "bucket" this (key, value) pair should be placed into.

You can overwrite the __hash__ method in your class to implement a custom hash function like this:

def __hash__(self):    
    return hash(str(self))

Depending on what your data actually looks like, you might be able to come up with a faster hash function that has fewer collisions than the standard function. However, this is unlikely. See the Python Wiki page on Dictionary Keys for more information.

Peak-finding algorithm for Python/SciPy

To detect both positive and negative peaks, PeakDetect is helpful.

from peakdetect import peakdetect

peaks = peakdetect(data, lookahead=20) 
# Lookahead is the distance to look ahead from a peak to determine if it is the actual peak. 
# Change lookahead as necessary 
higherPeaks = np.array(peaks[0])
lowerPeaks = np.array(peaks[1])
plt.plot(data)
plt.plot(higherPeaks[:,0], higherPeaks[:,1], 'ro')
plt.plot(lowerPeaks[:,0], lowerPeaks[:,1], 'ko')

PeakDetection

WCF gives an unsecured or incorrectly secured fault error

I've also had this problem from a service reference that was out of date, even with the server & client on the same machine. Running 'Update Service Reference' will generally fix it if this is the issue.

Is embedding background image data into CSS as Base64 good or bad practice?

I tried to create an online concept of CSS/HTML analyzer tool:

http://www.motobit.com/util/base64/css-images-to-base64.asp

It can:

  • Download and parse HTML/CSS files, extract href/src/url elements
  • Detect compression (gzip) and size data on the URL
  • Compare original data size, base64 data size and gzipped base64 data size
  • Convert the URL (image, font, css, ...) to a base64 data URI scheme.
  • Count number of requests which can be spared by Data URIs

Comments/suggestions are welcome.

Antonin

How do I calculate r-squared using Python and Numpy?

I originally posted the benchmarks below with the purpose of recommending numpy.corrcoef, foolishly not realizing that the original question already uses corrcoef and was in fact asking about higher order polynomial fits. I've added an actual solution to the polynomial r-squared question using statsmodels, and I've left the original benchmarks, which while off-topic, are potentially useful to someone.


statsmodels has the capability to calculate the r^2 of a polynomial fit directly, here are 2 methods...

import statsmodels.api as sm
import statsmodels.formula.api as smf

# Construct the columns for the different powers of x
def get_r2_statsmodels(x, y, k=1):
    xpoly = np.column_stack([x**i for i in range(k+1)])    
    return sm.OLS(y, xpoly).fit().rsquared

# Use the formula API and construct a formula describing the polynomial
def get_r2_statsmodels_formula(x, y, k=1):
    formula = 'y ~ 1 + ' + ' + '.join('I(x**{})'.format(i) for i in range(1, k+1))
    data = {'x': x, 'y': y}
    return smf.ols(formula, data).fit().rsquared # or rsquared_adj

To further take advantage of statsmodels, one should also look at the fitted model summary, which can be printed or displayed as a rich HTML table in Jupyter/IPython notebook. The results object provides access to many useful statistical metrics in addition to rsquared.

model = sm.OLS(y, xpoly)
results = model.fit()
results.summary()

Below is my original Answer where I benchmarked various linear regression r^2 methods...

The corrcoef function used in the Question calculates the correlation coefficient, r, only for a single linear regression, so it doesn't address the question of r^2 for higher order polynomial fits. However, for what it's worth, I've come to find that for linear regression, it is indeed the fastest and most direct method of calculating r.

def get_r2_numpy_corrcoef(x, y):
    return np.corrcoef(x, y)[0, 1]**2

These were my timeit results from comparing a bunch of methods for 1000 random (x, y) points:

  • Pure Python (direct r calculation)
    • 1000 loops, best of 3: 1.59 ms per loop
  • Numpy polyfit (applicable to n-th degree polynomial fits)
    • 1000 loops, best of 3: 326 µs per loop
  • Numpy Manual (direct r calculation)
    • 10000 loops, best of 3: 62.1 µs per loop
  • Numpy corrcoef (direct r calculation)
    • 10000 loops, best of 3: 56.6 µs per loop
  • Scipy (linear regression with r as an output)
    • 1000 loops, best of 3: 676 µs per loop
  • Statsmodels (can do n-th degree polynomial and many other fits)
    • 1000 loops, best of 3: 422 µs per loop

The corrcoef method narrowly beats calculating the r^2 "manually" using numpy methods. It is >5X faster than the polyfit method and ~12X faster than the scipy.linregress. Just to reinforce what numpy is doing for you, it's 28X faster than pure python. I'm not well-versed in things like numba and pypy, so someone else would have to fill those gaps, but I think this is plenty convincing to me that corrcoef is the best tool for calculating r for a simple linear regression.

Here's my benchmarking code. I copy-pasted from a Jupyter Notebook (hard not to call it an IPython Notebook...), so I apologize if anything broke on the way. The %timeit magic command requires IPython.

import numpy as np
from scipy import stats
import statsmodels.api as sm
import math

n=1000
x = np.random.rand(1000)*10
x.sort()
y = 10 * x + (5+np.random.randn(1000)*10-5)

x_list = list(x)
y_list = list(y)

def get_r2_numpy(x, y):
    slope, intercept = np.polyfit(x, y, 1)
    r_squared = 1 - (sum((y - (slope * x + intercept))**2) / ((len(y) - 1) * np.var(y, ddof=1)))
    return r_squared
    
def get_r2_scipy(x, y):
    _, _, r_value, _, _ = stats.linregress(x, y)
    return r_value**2
    
def get_r2_statsmodels(x, y):
    return sm.OLS(y, sm.add_constant(x)).fit().rsquared
    
def get_r2_python(x_list, y_list):
    n = len(x_list)
    x_bar = sum(x_list)/n
    y_bar = sum(y_list)/n
    x_std = math.sqrt(sum([(xi-x_bar)**2 for xi in x_list])/(n-1))
    y_std = math.sqrt(sum([(yi-y_bar)**2 for yi in y_list])/(n-1))
    zx = [(xi-x_bar)/x_std for xi in x_list]
    zy = [(yi-y_bar)/y_std for yi in y_list]
    r = sum(zxi*zyi for zxi, zyi in zip(zx, zy))/(n-1)
    return r**2
    
def get_r2_numpy_manual(x, y):
    zx = (x-np.mean(x))/np.std(x, ddof=1)
    zy = (y-np.mean(y))/np.std(y, ddof=1)
    r = np.sum(zx*zy)/(len(x)-1)
    return r**2
    
def get_r2_numpy_corrcoef(x, y):
    return np.corrcoef(x, y)[0, 1]**2
    
print('Python')
%timeit get_r2_python(x_list, y_list)
print('Numpy polyfit')
%timeit get_r2_numpy(x, y)
print('Numpy Manual')
%timeit get_r2_numpy_manual(x, y)
print('Numpy corrcoef')
%timeit get_r2_numpy_corrcoef(x, y)
print('Scipy')
%timeit get_r2_scipy(x, y)
print('Statsmodels')
%timeit get_r2_statsmodels(x, y)

Handling very large numbers in Python

python supports arbitrarily large integers naturally:

In [1]: 59**3*61**4*2*3*5*7*3*5*7
Out[1]: 62702371781194950
In [2]: _ % 61**4
Out[2]: 0

How do ports work with IPv6?

I'm pretty certain that ports only have a part in tcp and udp. So it's exactly the same even if you use a new IP protocol

jQuery checkbox check/uncheck

 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});

Understanding implicit in Scala

A very basic example of Implicits in scala.

Implicit parameters:

val value = 10
implicit val multiplier = 3
def multiply(implicit by: Int) = value * by
val result = multiply // implicit parameter wiil be passed here
println(result) // It will print 30 as a result

Note: Here multiplier will be implicitly passed into the function multiply. Missing parameters to the function call are looked up by type in the current scope meaning that code will not compile if there is no implicit variable of type Int in the scope.

Implicit conversions:

implicit def convert(a: Double): Int = a.toInt
val res = multiply(2.0) // Type conversions with implicit functions
println(res)  // It will print 20 as a result

Note: When we call multiply function passing a double value, the compiler will try to find the conversion implicit function in the current scope, which converts Int to Double (As function multiply accept Int parameter). If there is no implicit convert function then the compiler will not compile the code.

What's the equivalent of Java's Thread.sleep() in JavaScript?

The simple answer is that there is no such function.

The closest thing you have is:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

Here are a couple of other SO questions that deal with threads in JavaScript:

And this question may also be helpful:

How do I set the background color of my main screen in Flutter?

I think you can also use a scaffold to do the white background. Here's some piece of code that may help.

import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
  @override
    Widget build(BuildContext context) {

      return new MaterialApp(
        title: 'Testing',
        home: new Scaffold(
        //Here you can set what ever background color you need.
          backgroundColor: Colors.white,
        ),
      );
    }
}

Hope this helps .

How do I get the value of text input field using JavaScript?

If your input is in a form and you want to get value after submit you can do like

<form onsubmit="submitLoginForm(event)">
    <input type="text" name="name">
    <input type="password" name="password">
    <input type="submit" value="Login">
</form>

<script type="text/javascript">

    function submitLoginForm(event){
        event.preventDefault();

        console.log(event.target['name'].value);
        console.log(event.target['password'].value);
    }
</script>

Benefit of this way: Example your page have 2 form for input sender and receiver information.

If you don't use form for get value then
- You can set 2 different id(or tag or name ...) for each field like sender-name and receiver-name, sender-address and receiver-address, ...
- If you set same value for 2 input, then after getElementsByName (or getElementsByTagName ...) you need to remember 0 or 1 is sender or receiver. Later if you change the order of 2 form in html, you need to check this code again

If you use form, then you can use name, address, ...

How to check if an element is off-screen

Well... I've found some issues in every proposed solution here.

  • You should be able to choose if you want entire element to be on screen or just any part of it
  • Proposed solutions fails if element is higher/wider than window and kinda covers browser window.

Here is my solution that include jQuery .fn instance function and expression. I've created more variables inside my function than I could, but for complex logical problem I like to divide it into smaller, clearly named pieces.

I'm using getBoundingClientRect method that returns element position relatively to the viewport so I don't need to care about scroll position

Useage:

$(".some-element").filter(":onscreen").doSomething();
$(".some-element").filter(":entireonscreen").doSomething();
$(".some-element").isOnScreen(); // true / false
$(".some-element").isOnScreen(true); // true / false (partially on screen)
$(".some-element").is(":onscreen"); // true / false (partially on screen)
$(".some-element").is(":entireonscreen"); // true / false 

Source:

$.fn.isOnScreen = function(partial){

    //let's be sure we're checking only one element (in case function is called on set)
    var t = $(this).first();

    //we're using getBoundingClientRect to get position of element relative to viewport
    //so we dont need to care about scroll position
    var box = t[0].getBoundingClientRect();

    //let's save window size
    var win = {
        h : $(window).height(),
        w : $(window).width()
    };

    //now we check against edges of element

    //firstly we check one axis
    //for example we check if left edge of element is between left and right edge of scree (still might be above/below)
    var topEdgeInRange = box.top >= 0 && box.top <= win.h;
    var bottomEdgeInRange = box.bottom >= 0 && box.bottom <= win.h;

    var leftEdgeInRange = box.left >= 0 && box.left <= win.w;
    var rightEdgeInRange = box.right >= 0 && box.right <= win.w;


    //here we check if element is bigger then window and 'covers' the screen in given axis
    var coverScreenHorizontally = box.left <= 0 && box.right >= win.w;
    var coverScreenVertically = box.top <= 0 && box.bottom >= win.h;

    //now we check 2nd axis
    var topEdgeInScreen = topEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
    var bottomEdgeInScreen = bottomEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );

    var leftEdgeInScreen = leftEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
    var rightEdgeInScreen = rightEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );

    //now knowing presence of each edge on screen, we check if element is partially or entirely present on screen
    var isPartiallyOnScreen = topEdgeInScreen || bottomEdgeInScreen || leftEdgeInScreen || rightEdgeInScreen;
    var isEntirelyOnScreen = topEdgeInScreen && bottomEdgeInScreen && leftEdgeInScreen && rightEdgeInScreen;

    return partial ? isPartiallyOnScreen : isEntirelyOnScreen;

};

$.expr.filters.onscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

$.expr.filters.entireonscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

How to get week number of the month from the date in sql server 2008

Code is below:

set datefirst 7
declare @dt datetime='29/04/2016 00:00:00'
select (day(@dt)+datepart(WEEKDAY,dateadd(d,-day(@dt),@dt+1)))/7

How to return a value from pthread threads in C?

#include<stdio.h>
#include<pthread.h>
void* myprint(void *x)
{
 int k = *((int *)x);
 printf("\n Thread created.. value of k [%d]\n",k);
 //k =11;
 pthread_exit((void *)k);

}
int main()
{
 pthread_t th1;
 int x =5;
 int *y;
 pthread_create(&th1,NULL,myprint,(void*)&x);
 pthread_join(th1,(void*)&y);
 printf("\n Exit value is [%d]\n",y);
}  

Java Loop every minute

Use Thread.sleep(long millis).

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

One minute would be (60*1000) = 60000 milliseconds.


For example, this loop will print the current time once every 5 seconds:

    try {
        while (true) {
            System.out.println(new Date());
            Thread.sleep(5 * 1000);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

If your sleep period becomes too large for int, explicitly compute in long (e.g. 1000L).

Iterating over a 2 dimensional python list

>>> [el[0] if i < len(mylist) else el[1] for i,el in enumerate(mylist + mylist)]
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']

How do I check if a number is positive or negative in C#?

bool isNegative(int n) {
  int i;
  for (i = 0; i <= Int32.MaxValue; i++) {
    if (n == i) 
      return false;
  }
  return true;
}

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

The error is:

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

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

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

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

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

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

System.Net.WebException HTTP status code

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

For Java 8 the following method works:

  1. Form an URI from file URI string
  2. Create a file from the URI (not directly from URI string, absolute URI string are not paths)

Refer, below code snippet

    String fileURiString="file:///D:/etc/MySQL.txt";
    URI fileURI=new URI(fileURiString);
    File file=new File(fileURI);//File file=new File(fileURiString) - will generate exception

    FileInputStream fis=new FileInputStream(file);
    fis.close();

How to have Ellipsis effect on Text

_x000D_
_x000D_
const styles = theme => ({_x000D_
 contentClass:{_x000D_
    overflow: 'hidden',_x000D_
    textOverflow: 'ellipsis',_x000D_
    display: '-webkit-box',_x000D_
    WebkitLineClamp:1,_x000D_
    WebkitBoxOrient:'vertical'_x000D_
 }   _x000D_
})
_x000D_
render () {_x000D_
  return(_x000D_
    <div className={classes.contentClass}>_x000D_
      {'content'}_x000D_
    </div>_x000D_
  )_x000D_
}
_x000D_
_x000D_
_x000D_

What is the difference between require() and library()?

?library

and you will see:

library(package) and require(package) both load the package with name package and put it on the search list. require is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as library() does by default) if the package does not exist. Both functions check and update the list of currently loaded packages and do not reload a package which is already loaded. (If you want to reload such a package, call detach(unload = TRUE) or unloadNamespace first.) If you want to load a package without putting it on the search list, use requireNamespace.

How do I remove the file suffix and path portion from a path string in Bash?

The basename does that, removes the path. It will also remove the suffix if given and if it matches the suffix of the file but you would need to know the suffix to give to the command. Otherwise you can use mv and figure out what the new name should be some other way.

How to create file execute mode permissions in Git on Windows?

There's no need to do this in two commits, you can add the file and mark it executable in a single commit:

C:\Temp\TestRepo>touch foo.sh

C:\Temp\TestRepo>git add foo.sh

C:\Temp\TestRepo>git ls-files --stage
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0       foo.sh

As you note, after adding, the mode is 0644 (ie, not executable). However, we can mark it as executable before committing:

C:\Temp\TestRepo>git update-index --chmod=+x foo.sh

C:\Temp\TestRepo>git ls-files --stage
100755 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0       foo.sh

And now the file is mode 0755 (executable).

C:\Temp\TestRepo>git commit -m"Executable!"
[master (root-commit) 1f7a57a] Executable!
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100755 foo.sh

And now we have a single commit with a single executable file.

How to remove trailing and leading whitespace for user-provided input in a batch file?

I had to create a Function.

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION


set "TextString=    Purple Cows are flying in the Air Tonight         "
echo REM ^^Notice there is whitespace at the start and end of the TextString
echo "!TextString!"
CALL:trimWhiteSpace "!TextString!" OutPutString
echo Resulting Trimmed Text: "!OutPutString!"
echo REM ^^Now there should be no White space at the start or end.

Exit /B

Add this to the bottom of your batch file:

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B


::TRIM FUNCTIONS AREA::
:: USAGE:
:: trimWhiteSpace "!InputText!" OutputText
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: trimWhiteSpace "!InputText!" !OutputText!
:: ^^Because it has a ! around the OutPutText
:: Make Sure to add " around the InputText when running the call.
:: If you don't add the " then it will only accept the first word before a space.
::Example:
::  set "TextString=    Purple Cows are flying in the Air Tonight         "
::  echo REM ^^Notice there is whitespace at the start and end of the TextString
::  echo "!TextString!"
::  CALL:trimWhiteSpace "!TextString!" OutPutString
::  echo Resulting Trimmed Text: "!OutPutString!"
::  echo REM ^^Now there should be no White space at the start or end.

:trimWhiteSpace
set textToTrim=%~1
CALL:trimWhiteSpaceOnTheRight "!textToTrim!" OutPutString
SET textToTrim=!OutPutString!
CALL:trimWhiteSpaceOnTheLeft "!textToTrim!" OutPutString
SET %2=!OutPutString!
GOTO:EOF

:trimWhiteSpaceOnTheRight
set str=%~1
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
SET %2=%str%
GOTO:EOF

:trimWhiteSpaceOnTheLeft
set str=%~1
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
SET %2=%str%
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

Java equivalent to Explode and Implode(PHP)

I'm not familiar with PHP, but I think String.split is Java equivalent to PHP explode. As for implode, standart library does not provide such functionality. You just iterate over your array and build string using StringBuilder/StringBuffer. Or you can try excellent Google Guava Splitter and Joiner or split/join methods from Apache Commons StringUtils.

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I was thinking the error is due to "s3:ListObjects" action but I had to add the action "s3:ListBucket" to solve the issue "AccessDenied for ListObjects for S3 bucket"

What is getattr() exactly and how do I use it?

Another use of getattr() in implementing a switch statement in Python. It uses both reflection to get the case type.

import sys

class SwitchStatement(object):
    """ a class to implement switch statement and a way to show how to use gettattr in Pythion"""

    def case_1(self):
        return "value for case_1"

    def case_2(self):
        return "value for case_2"

    def case_3(self):
        return "value for case_3"

    def case_4(self):
        return "value for case_4"

    def case_value(self, case_type=1):
        """This is the main dispatchmethod, that uses gettattr"""
        case_method = 'case_' + str(case_type)
        # fetch the relevant method name
        # Get the method from 'self'. Default to a lambda.
        method = getattr(self, case_method, lambda: "Invalid case type")
        # Call the method as we return it
        return method()

def main(_):
    switch = SwitchStatement()
    print swtich.case_value(_)

if __name__ == '__main__':
    main(int(sys.argv[1]))

How to detect internet speed in JavaScript?

Well, this is 2017 so you now have Network Information API (albeit with a limited support across browsers as of now) to get some sort of estimate downlink speed information:

navigator.connection.downlink

This is effective bandwidth estimate in Mbits per sec. The browser makes this estimate from recently observed application layer throughput across recently active connections. Needless to say, the biggest advantage of this approach is that you need not download any content just for bandwidth/ speed calculation.

You can look at this and a couple of other related attributes here

Due to it's limited support and different implementations across browsers (as of Nov 2017), would strongly recommend read this in detail

How to get current user in asp.net core

I got my solution

var claim = HttpContext.User.CurrentUserID();

public static class XYZ
{
    public static int CurrentUserID(this ClaimsPrincipal claim)
    {
        var userID = claimsPrincipal.Claims.ToList().Find(r => r.Type == 
         "UserID").Value;
        return Convert.ToInt32(userID);
    }
    public static string CurrentUserRole(this ClaimsPrincipal claim)
    {
        var role = claimsPrincipal.Claims.ToList().Find(r => r.Type == 
        "Role").Value;
        return role;
    }
}

EC2 instance types's exact network performance?

Bandwidth is tiered by instance size, here's a comprehensive answer:

For t2/m3/c3/c4/r3/i2/d2 instances:

  • t2.nano = ??? (Based on the scaling factors, I'd expect 20-30 MBit/s)
  • t2.micro = ~70 MBit/s (qiita says 63 MBit/s) - t1.micro gets about ~100 Mbit/s
  • t2.small = ~125 MBit/s (t2, qiita says 127 MBit/s, cloudharmony says 125 Mbit/s with spikes to 200+ Mbit/s)
  • *.medium = t2.medium gets 250-300 MBit/s, m3.medium ~400 MBit/s
  • *.large = ~450-600 MBit/s (the most variation, see below)
  • *.xlarge = 700-900 MBit/s
  • *.2xlarge = ~1 GBit/s +- 10%
  • *.4xlarge = ~2 GBit/s +- 10%
  • *.8xlarge and marked specialty = 10 Gbit, expect ~8.5 GBit/s, requires enhanced networking & VPC for full throughput

m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.

I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).

Caveats & Notes:

The large instance size has the most variation reported:

  • m1.large is ~800 Mbit/s (!!!)
  • t2.large = ~500 MBit/s
  • c3.large = ~500-570 Mbit/s (different results from different sources)
  • c4.large = ~520 MBit/s (I've confirmed this independently, by the way)
  • m3.large is better at ~700 MBit/s
  • m4.large is ~445 Mbit/s
  • r3.large is ~390 Mbit/s

Burstable (T2) instances appear to exhibit burstable networking performance too:

  • The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:

  • t2.small (PDF)

  • t2.medium (PDF)
  • t2.large (PDF)

Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.

How to do vlookup and fill down (like in Excel) in R?

The poster didn't ask about looking up values if exact=FALSE, but I'm adding this as an answer for my own reference and possibly others.

If you're looking up categorical values, use the other answers.

Excel's vlookup also allows you to match match approximately for numeric values with the 4th argument(1) match=TRUE. I think of match=TRUE like looking up values on a thermometer. The default value is FALSE, which is perfect for categorical values.

If you want to match approximately (perform a lookup), R has a function called findInterval, which (as the name implies) will find the interval / bin that contains your continuous numeric value.

However, let's say that you want to findInterval for several values. You could write a loop or use an apply function. However, I've found it more efficient to take a DIY vectorized approach.

Let's say that you have a grid of values indexed by x and y:

grid <- list(x = c(-87.727, -87.723, -87.719, -87.715, -87.711), 
             y = c(41.836, 41.839, 41.843, 41.847, 41.851), 
             z = (matrix(data = c(-3.428, -3.722, -3.061, -2.554, -2.362, 
                                  -3.034, -3.925, -3.639, -3.357, -3.283, 
                                  -0.152, -1.688, -2.765, -3.084, -2.742, 
                                   1.973,  1.193, -0.354, -1.682, -1.803, 
                                   0.998,  2.863,  3.224,  1.541, -0.044), 
                         nrow = 5, ncol = 5)))

and you have some values you want to look up by x and y:

df <- data.frame(x = c(-87.723, -87.712, -87.726, -87.719, -87.722, -87.722), 
                 y = c(41.84, 41.842, 41.844, 41.849, 41.838, 41.842), 
                 id = c("a", "b", "c", "d", "e", "f")

Here is the example visualized:

contour(grid)
points(df$x, df$y, pch=df$id, col="blue", cex=1.2)

Contour Plot

You can find the x intervals and y intervals with this type of formula:

xrng <- range(grid$x)
xbins <- length(grid$x) -1
yrng <- range(grid$y)
ybins <- length(grid$y) -1
df$ix <- trunc( (df$x - min(xrng)) / diff(xrng) * (xbins)) + 1
df$iy <- trunc( (df$y - min(yrng)) / diff(yrng) * (ybins)) + 1

You could take it one step further and perform a (simplistic) interpolation on the z values in grid like this:

df$z <- with(df, (grid$z[cbind(ix, iy)] + 
                      grid$z[cbind(ix + 1, iy)] +
                      grid$z[cbind(ix, iy + 1)] + 
                      grid$z[cbind(ix + 1, iy + 1)]) / 4)

Which gives you these values:

contour(grid, xlim = range(c(grid$x, df$x)), ylim = range(c(grid$y, df$y)))
points(df$x, df$y, pch=df$id, col="blue", cex=1.2)
text(df$x + .001, df$y, lab=round(df$z, 2), col="blue", cex=1)

Contour plot with values

df
#         x      y id ix iy        z
# 1 -87.723 41.840  a  2  2 -3.00425
# 2 -87.712 41.842  b  4  2 -3.11650
# 3 -87.726 41.844  c  1  3  0.33150
# 4 -87.719 41.849  d  3  4  0.68225
# 6 -87.722 41.838  e  2  1 -3.58675
# 7 -87.722 41.842  f  2  2 -3.00425

Note that ix, and iy could have also been found with a loop using findInterval, e.g. here's one example for the second row

findInterval(df$x[2], grid$x)
# 4
findInterval(df$y[2], grid$y)
# 2

Which matches ix and iy in df[2]

Footnote: (1) The fourth argument of vlookup was previously called "match", but after they introduced the ribbon it was renamed to "[range_lookup]".

vue.js 2 how to watch store values from vuex

It's as simple as:

watch: {
  '$store.state.drawer': function() {
    console.log(this.$store.state.drawer)
  }
}

regex for zip-code

^\d{5}(?:[-\s]\d{4})?$
  • ^ = Start of the string.
  • \d{5} = Match 5 digits (for condition 1, 2, 3)
  • (?:…) = Grouping
  • [-\s] = Match a space (for condition 3) or a hyphen (for condition 2)
  • \d{4} = Match 4 digits (for condition 2, 3)
  • …? = The pattern before it is optional (for condition 1)
  • $ = End of the string.

SQL Server tables: what is the difference between @, # and ##?

# and ## tables are actual tables represented in the temp database. These tables can have indexes and statistics, and can be accessed across sprocs in a session (in the case of a global temp table, it is available across sessions).

The @table is a table variable.

For more: http://www.sqlteam.com/article/temporary-tables

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

Javascript dynamic array of strings

var junk=new Array();
junk.push('This is a string.');

Et cetera.

jQuery hyperlinks - href value?

using jquery, you may want to get only to those with a '#'

$('a[href=#]').click(function(){return false;});

if you use the newest jquery (1.3.x), there's no need to bind it again when the page changes:

$('a[href=#]').live('click', function(){return false;});

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

How do I use dataReceived event of the SerialPort Port Object in C#?

Might very well be the Console.ReadLine blocking your callback's Console.Writeline, in fact. The sample on MSDN looks ALMOST identical, except they use ReadKey (which doesn't lock the console).

What's an easy way to read random line from a file in Unix command line?

using a bash script:

#!/bin/bash
# replace with file to read
FILE=tmp.txt
# count number of lines
NUM=$(wc - l < ${FILE})
# generate random number in range 0-NUM
let X=${RANDOM} % ${NUM} + 1
# extract X-th line
sed -n ${X}p ${FILE}

Unmarshaling nested JSON objects

Yes. With gjson all you have to do now is:

bar := gjson.Get(json, "foo.bar")

bar could be a struct property if you like. Also, no maps.

Are the decimal places in a CSS width respected?

Although fractional pixels may appear to round up on individual elements (as @SkillDrick demonstrates very well) it's important to know that the fractional pixels are actually respected in the actual box model.

This can best be seen when elements are stacked next to (or on top of) each other; in other words, if I were to place 400 0.5 pixel divs side by side, they would have the same width as a single 200 pixel div. If they all actually rounded up to 1px (as looking at individual elements would imply) we'd expect the 200px div to be half as long.

This can be seen in this runnable code snippet:

_x000D_
_x000D_
body {_x000D_
  color:            white;_x000D_
  font-family:      sans-serif;_x000D_
  font-weight:      bold;_x000D_
  background-color: #334;_x000D_
}_x000D_
_x000D_
.div_house div {_x000D_
  height:           10px;_x000D_
  background-color: orange;_x000D_
  display:          inline-block;_x000D_
}_x000D_
_x000D_
div#small_divs div {_x000D_
  width:            0.5px;_x000D_
}_x000D_
_x000D_
div#large_div div {_x000D_
  width:            200px;_x000D_
}
_x000D_
<div class="div_house" id="small_divs">_x000D_
  <p>0.5px div x 400</p>_x000D_
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>_x000D_
</div>_x000D_
<br>_x000D_
<div class="div_house" id="large_div">_x000D_
  <p>200px div x 1</p>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Html.HiddenFor value property not getting set

A simple answer is to use @Html.TextboxFor but place it in a div that is hidden with style. Example: In View:

<div style="display:none"> @Html.TextboxFor(x=>x.CRN) </div>

Expand a random range from 1–5 to 1–7

int getOneToSeven(){
    int added = 0;
    for(int i = 1; i<=7; i++){
        added += getOneToFive();
    }
    return (added)%7+1;
}

How do I make an HTML text box show a hint when empty?

Use a background image to render the text:

 input.foo { }
 input.fooempty { background-image: url("blah.png"); }

Then all you have to do is detect value == 0 and apply the right class:

 <input class="foo fooempty" value="" type="text" name="bar" />

And the jQuery JavaScript code looks like this:

jQuery(function($)
{
    var target = $("input.foo");
    target.bind("change", function()
    {
        if( target.val().length > 1 )
        {
            target.addClass("fooempty");
        }
        else
        {
            target.removeClass("fooempty");
        }
    });
});

Best way to increase heap size in catalina.bat file

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Original answer here

After you run startup.bat, you can easily confirm the correct settings have been applied provided you have turned @echo on somewhere in your catatlina.bat file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"):

enter image description here

How can I reduce the waiting (ttfb) time

If you are using PHP, try using <?php flush(); ?> after </head> and before </body> or whatever section you want to output quickly (like the header or content). It will output the actually code without waiting for php to end. Don't use this function all the time, or the speed increase won't be noticable.

More info

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

Read file from resources folder in Spring Boot

Below is my working code.

List<sampleObject> list = new ArrayList<>();
File file = new ClassPathResource("json/test.json").getFile();
ObjectMapper objectMapper = new ObjectMapper();
sampleObject = Arrays.asList(objectMapper.readValue(file, sampleObject[].class));

Hope it helps one!

How do I set up a private Git repository on GitHub? Is it even possible?

Bitbucket - Their plans seem to be the best. They give you way more than GitHub do for free accounts - in fact, I'm still only using the free plan - no need to sign up to the paid ones; plus the interface is almost identical to GitHub.

A repository on Bitbucket can have up to five private users with unlimited public or private repositories - the only thing you seem to be paying for with the paid accounts are more users to access your private repositories.

Is there a difference between "==" and "is"?

Have a look at Stack Overflow question Python's “is” operator behaves unexpectedly with integers.

What it mostly boils down to is that "is" checks to see if they are the same object, not just equal to each other (the numbers below 256 are a special case).

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

PNG has 2 advantages: it has smaller size and it's more widely used and supported (except in case favicons). As mentioned before ICO, can have multiple size icons, which is useful for desktop applications, but not too much for websites. I would recommend you to put a favicon.ico in the root of your application. An if you have access to the Head of your website pages use the tag to point to a png file. So older browser will show the favicon.ico and newer ones the png.

To create Png and Icon files I would recommend The Gimp.

Convert .pfx to .cer

the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

URL Encoding the data works as well for me

For example

var data = '<b>Hello</b>'

In Browser call encodeURIComponent(data) before posting

On Server call HttpUtility.UrlDecode(received_data) to decode

That way you can control exactly which fields area allowed to have html

What is the difference between Sessions and Cookies in PHP?

A cookie is a bit of data stored by the browser and sent to the server with every request.

A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)

Understanding Apache's access log

And what does "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19" means ?

This is the value of User-Agent, the browser identification string.

For this reason, most Web browsers use a User-Agent string value as follows:

Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]. For example, Safari on the iPad has used the following:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 The components of this string are as follows:

Mozilla/5.0: Previously used to indicate compatibility with the Mozilla rendering engine. (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us): Details of the system in which the browser is running. AppleWebKit/531.21.10: The platform the browser uses. (KHTML, like Gecko): Browser platform details. Mobile/7B405: This is used by the browser to indicate specific enhancements that are available directly in the browser or through third parties. An example of this is Microsoft Live Meeting which registers an extension so that the Live Meeting service knows if the software is already installed, which means it can provide a streamlined experience to joining meetings.

This value will be used to identify what browser is being used by end user.

Refer

CSS :not(:last-child):after selector

Your sample does not work in IE for me, you have to specify Doctype header in your document to render your page in standard way in IE to use the content CSS property:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<html>

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

</html>

Second way is to use CSS 3 selectors

li:not(:last-of-type):after
{
    content:           " |";
}

But you still need to specify Doctype

And third way is to use JQuery with some script like following:

<script type="text/javascript" src="jquery-1.4.1.js"></script>
<link href="style2.css" rel="stylesheet" type="text/css">
</head>
<html>

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

<script type="text/javascript">
  $(document).ready(function () {
      $("li:not(:last)").append(" | ");
    });
</script>

Advantage of third way is that you dont have to specify doctype and jQuery will take care of compatibility.

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

  1. You seem to be including one C file from anther. #include should normally be used with header files only.

  2. Within the definition of struct ast_node you refer to struct AST_NODE, which doesn't exist. C is case-sensitive.

Python datetime strptime() and strftime(): how to preserve the timezone information

Here is my answer in Python 2.7

Print current time with timezone

from datetime import datetime
import tzlocal  # pip install tzlocal

print datetime.now(tzlocal.get_localzone()).strftime("%Y-%m-%d %H:%M:%S %z")

Print current time with specific timezone

from datetime import datetime
import pytz # pip install pytz

print datetime.now(pytz.timezone('Asia/Taipei')).strftime("%Y-%m-%d %H:%M:%S %z")

It will print something like

2017-08-10 20:46:24 +0800

How to implement 2D vector array?

Just use the following methods to create a 2-D vector.

int rows, columns;        

// . . .

vector < vector < int > > Matrix(rows, vector< int >(columns,0));

OR

vector < vector < int > > Matrix;

Matrix.assign(rows, vector < int >(columns, 0));

//Do your stuff here...

This will create a Matrix of size rows * columns and initializes it with zeros because we are passing a zero(0) as a second argument in the constructor i.e vector < int > (columns, 0).

Validate form field only on submit or user input

Invoking of validation on form element could be handled by triggering change event on this element:

a) exemple: trigger change on separated element in form

$scope.formName.elementName.$$element.change();

b) exemple: trigger change event for each of form elements for example on ng-submit, ng-click, ng-blur ...

vm.triggerChangeForFormElements = function() {
    // trigger change event for each of form elements
    angular.forEach($scope.formName, function (element, name) {
        if (!name.startsWith('$')) {
            element.$$element.change();
        }
    });
};

c) and one more way for that

    var handdleChange = function(form){
        var formFields = angular.element(form)[0].$$controls;
        angular.forEach(formFields, function(field){
            field.$$element.change();
        });
    };

How to normalize a histogram in MATLAB?

[f,x]=hist(data)

The area for each individual bar is height*width. Since MATLAB will choose equidistant points for the bars, so the width is:

delta_x = x(2) - x(1)

Now if we sum up all the individual bars the total area will come out as

A=sum(f)*delta_x

So the correctly scaled plot is obtained by

bar(x, f/sum(f)/(x(2)-x(1)))

Refused to execute script, strict MIME type checking is enabled?

Try to use express.static() if you are using Node.js.

You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do as below -

i.e. : app.use(express.static('public'));

This approach resolved my issue.

Thanks,

Styling HTML email for Gmail

Use inline styles for everything. This site will convert your classes to inline styles: http://premailer.dialect.ca/

Connecting to SQL Server with Visual Studio Express Editions

I just happened to have started my home business application in windows forms for the convenience. I'm currently using Visual C# Express 2010 / SQL Server 2008 R2 Express to develop it. I got the same problem as OP where I need to connect to an instance of SQL server. I'm skipping details here but that database will be a merged database synched between 2-3 computers that will also use the application I'm developing right now.

I found a quick workaround, at least, I think I did because I'm now able to use my stored procedures in tableadapters without any issues so far.

I copy pasted an SQL connection that I used in a different project at work (VS2010 Premium) in the app.config and changed everything I needed there. When I went back to my Settings.settings, I just had to confirm that I wanted what was inside the app.config file. The only downsides I can see is that you can't "test" the connection since when you go inside the configuration of the connection string you can't go anywhere since "SQL Server" is not an option. The other downside is that you need to input everything manually since you can't use any wizards to make it work.

I don't know if I should have done it that way but at least I can connect to my SQL server now :).

EDIT :

It only works with SQL Server 2008 R2 Express instances. If you try with SQL Server 2008 R2 Workgroup and up, you'll get a nasty warning from Visual C# 2010 Express telling you that "you can't use that connection with the current version of Visual Studio". I got that when I was trying to modify some of my tableadapters. I switched back to an SQL Express instance to develop and it's working fine again.

Understanding PIVOT function in T-SQL

A PIVOT used to rotate the data from one column into multiple columns.

For your example here is a STATIC Pivot meaning you hard code the columns that you want to rotate:

create table temp
(
  id int,
  teamid int,
  userid int,
  elementid int,
  phaseid int,
  effort decimal(10, 5)
)

insert into temp values (1,1,1,3,5,6.74)
insert into temp values (2,1,1,3,6,8.25)
insert into temp values (3,1,1,4,1,2.23)
insert into temp values (4,1,1,4,5,6.8)
insert into temp values (5,1,1,4,6,1.5)

select elementid
  , [1] as phaseid1
  , [5] as phaseid5
  , [6] as phaseid6
from
(
  select elementid, phaseid, effort
  from temp
) x
pivot
(
  max(effort)
  for phaseid in([1], [5], [6])
)p

Here is a SQL Demo with a working version.

This can also be done through a dynamic PIVOT where you create the list of columns dynamically and perform the PIVOT.

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.phaseid) 
            FROM temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT elementid, ' + @cols + ' from 
            (
                select elementid, phaseid, effort
                from temp
           ) x
            pivot 
            (
                 max(effort)
                for phaseid in (' + @cols + ')
            ) p '


execute(@query)

The results for both:

ELEMENTID   PHASEID1    PHASEID5    PHASEID6
3           Null        6.74        8.25
4           2.23        6.8         1.5

Query to select data between two dates with the format m/d/yyyy

Try this:

select * from xxx where dates between convert(datetime,'10/10/2012',103) and convert(dattime,'10/12/2012',103)

How to call a Web Service Method?

In visual studio, use the "Add Web Reference" feature and then enter in the URL of your web service.

By adding a reference to the DLL, you not referencing it as a web service, but simply as an assembly.

When you add a web reference it create a proxy class in your project that has the same or similar methods/arguments as your web service. That proxy class communicates with your web service via SOAP but hides all of the communications protocol stuff so you don't have to worry about it.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Adding Buttons To Google Sheets and Set value to Cells on clicking

Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.

In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.

Remove a symlink to a directory

rm should remove the symbolic link.

skrall@skrall-desktop:~$ mkdir bar
skrall@skrall-desktop:~$ ln -s bar foo
skrall@skrall-desktop:~$ ls -l foo
lrwxrwxrwx 1 skrall skrall 3 2008-10-16 16:22 foo -> bar
skrall@skrall-desktop:~$ rm foo
skrall@skrall-desktop:~$ ls -l foo
ls: cannot access foo: No such file or directory
skrall@skrall-desktop:~$ ls -l bar
total 0
skrall@skrall-desktop:~$ 

Invalid length parameter passed to the LEFT or SUBSTRING function

This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding

ABS(CHARINDEX(' ', PostCode ) -1))

which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1) is a -ve value. Correct me if I'm wrong!

Why use prefixes on member variables in C++ classes

The main reason for a member prefix is to distinguish between a member function local and a member variable with the same name. This is useful if you use getters with the name of the thing.

Consider:

class person
{
public:
    person(const std::string& full_name)
        : full_name_(full_name)
    {}

    const std::string& full_name() const { return full_name_; }
private:
    std::string full_name_;
};

The member variable could not be called full_name in this case. You need to rename the member function to get_full_name() or decorate the member variable somehow.

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

How do I set headers using python's urllib?

Use urllib2 and create a Request object which you then hand to urlopen. http://docs.python.org/library/urllib2.html

I dont really use the "old" urllib anymore.

req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
response = urllib2.urlopen(req).read()

untested....

How to compute the similarity between two text documents?

Here's a little app to get you started...

import difflib as dl

a = file('file').read()
b = file('file1').read()

sim = dl.get_close_matches

s = 0
wa = a.split()
wb = b.split()

for i in wa:
    if sim(i, wb):
        s += 1

n = float(s) / float(len(wa))
print '%d%% similarity' % int(n * 100)

Multi-Column Join in Hibernate/JPA Annotations

If this doesn't work I'm out of ideas. This way you get the 4 columns in both tables (as Bar owns them and Foo uses them to reference Bar) and the generated IDs in both entities. The set of 4 columns has to be unique in Bar so the many-to-one relation doesn't become a many-to-many.

@Embeddable
public class AnEmbeddedObject
{
    @Column(name = "column_1")
    private Long column1;
    @Column(name = "column_2")
    private Long column2;
    @Column(name = "column_3")
    private Long column3;
    @Column(name = "column_4")
    private Long column4;
}

@Entity
public class Foo
{
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seqGen")
    @SequenceGenerator(name = "seqGen", sequenceName = "FOO_ID_SEQ", allocationSize = 1)
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "column_1", referencedColumnName = "column_1"),
        @JoinColumn(name = "column_2", referencedColumnName = "column_2"),
        @JoinColumn(name = "column_3", referencedColumnName = "column_3"),
        @JoinColumn(name = "column_4", referencedColumnName = "column_4")
    })
    private Bar bar;
}

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {
    "column_1",
    "column_2",
    "column_3",
    "column_4"
}))
public class Bar
{
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seqGen")
    @SequenceGenerator(name = "seqGen", sequenceName = "BAR_ID_SEQ", allocationSize = 1)
    private Long id;
    @Embedded
    private AnEmbeddedObject anEmbeddedObject;
}

Responsive bootstrap 3 timepicker?

Kendo UI provides the best and ultimate collection of JavaScript UI components with libraries for jQuery, Angular, React, and Vue. You can quickly build eye-catching, high-performance, responsive web applications regardless of your JavaScript framework choice. Here is a timepicker UI component from them:

Also below is an alternate and a simple solution

<!--Css-->
<link href="css/timepicker.css" type="text/css" rel="stylesheet" />

<!--Html-->
<div class="row">
    <div class="col">
        <label class="label-in">Time</label>
        <input class="timepicker" id="event-time" type="text" value="" required="">
    </div>
</div>

<!--Script-->
<script src="Scripts/ClockPicker.js"></script>
<script>
   $('.timepicker').timepicker({
     });
</script>

Here is yet another popular framework Bootstrap Time Picker from mdbootstrap

push multiple elements to array

There are many answers recommend to use: Array.prototype.push(a, b). It's nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.

See What is the most efficient way to concatenate N arrays? for more details.

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

in mvc 5

              @Html.EditorFor(x => x.Address, 
              new {htmlAttributes = new {@class = "form-control", 
                   @placeholder = "Complete Address", @cols = 10, @rows = 10 } })

Accessing constructor of an anonymous class

It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.

Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.

How to display tables on mobile using Bootstrap?

Bootstrap 3 introduces responsive tables:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

Bootstrap 4 is similar, but with more control via some new classes:

...responsive across all viewports ... with .table-responsive. Or, pick a maximum breakpoint with which to have a responsive table up to by using .table-responsive{-sm|-md|-lg|-xl}.

Credit to Jason Bradley for providing an example:

Responsive Tables

Bridged networking not working in Virtualbox under Windows 10

In Case some one is looking and none of the above resolves your issue : https://forums.virtualbox.org/viewtopic.php?f=6&t=90650&p=434965#p434965

placing the WIFI as the first adapter [MTDesktop, AllowALL] and the LAN WIRED [MTServer,AllowAll] as the second adapter. In the Guest machine I disable the First Adapter in Adapter Settings. I can then ping internal, external whatever.

Format a JavaScript string using placeholders and an object of substitutions?

Just use replace()

var values = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
var substitutedString = "My Name is %NAME% and my age is %AGE%.".replace("%NAME%", $values["%NAME%"]).replace("%AGE%", $values["%AGE%"]);

Horizontal ListView in Android?

There is a great library for that, called TwoWayView, it's very easy to implement, just include the project library into your work space and add it as a library project to your original project, and then follow the following steps which are originally mentioned here:

First, let's add a style indicating the orientation of the ListView (horizontal or vertical) in (res/values/styles.xml):

<style name="TwoWayView">
    <item name="android:orientation">horizontal</item>
</style>

Then,

In your Layout XML, use the following code to add the TwoWayView:

<org.lucasr.twowayview.TwoWayView 
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:id="@+id/lvItems"
     style="@style/TwoWayView"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:drawSelectorOnTop="false"
     tools:context=".MainActivity" />

and finally, just declare it and deal with it like any regular ListView:

TwoWayView lvTest = (TwoWayView) findViewById(R.id.lvItems);

All the methods of ListView will work here as usual, but there is only one difference I noticed, which is when setting the choice mode, the method setChoiceMode not takes an int value but a value from enum called ChoiceMode, so list_view.setChoiceMode(ListView.CHOICE_MODE_SINGLE); will be lvTest.setChoiceMode(ChoiceMode.SINGLE); // or MULTIPLE or NONE.

How do I create a right click context menu in Java Swing?

You are probably manually calling setVisible(true) on the menu. That can cause some nasty buggy behavior in the menu.

The show(Component, int x, int x) method handles all of the things you need to happen, (Highlighting things on mouseover and closing the popup when necessary) where using setVisible(true) just shows the menu without adding any additional behavior.

To make a right click popup menu simply create a JPopupMenu.

class PopUpDemo extends JPopupMenu {
    JMenuItem anItem;
    public PopUpDemo() {
        anItem = new JMenuItem("Click Me!");
        add(anItem);
    }
}

Then, all you need to do is add a custom MouseListener to the components you would like the menu to popup for.

class PopClickListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
        if (e.isPopupTrigger())
            doPop(e);
    }

    public void mouseReleased(MouseEvent e) {
        if (e.isPopupTrigger())
            doPop(e);
    }

    private void doPop(MouseEvent e) {
        PopUpDemo menu = new PopUpDemo();
        menu.show(e.getComponent(), e.getX(), e.getY());
    }
}

// Then on your component(s)
component.addMouseListener(new PopClickListener());

Of course, the tutorials have a slightly more in-depth explanation.

Note: If you notice that the popup menu is appearing way off from where the user clicked, try using the e.getXOnScreen() and e.getYOnScreen() methods for the x and y coordinates.

How to run an awk commands in Windows?

You can download and run the setup file. This should install your AWK in "C:\Program Files (x86)\GnuWin32". You can run the awk or gawk command from the bin folder or add the folder ``C:\Program Files (x86)\GnuWin32\binto yourPATH`.

enter image description here

How to merge remote changes at GitHub?

When I got this error, I backed up my entire project folder. Then I did something like

$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master

...depending on your branch name (if it's not master).

Then I did git pull --rebase. After that, I replaced the pulled files with my backed-up project's files. Now I am ready to commit my changes again and push.

Defining static const integer members in class definition

My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.

You are sort of correct. You are allowed to initialize static const integrals in the class declaration but that is not a definition.

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr038.htm

Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line).

Any idea as to what's going on?

std::min takes its parameters by const reference. If it took them by value you'd not have this problem but since you need a reference you also need a definition.

Here's chapter/verse:

9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

See Chu's answer for a possible workaround.

Sass nth-child nesting

You're trying to do &(2), &(4) which won't work

#romtest {
  .detailed {
    th {
      &:nth-child(2) {//your styles here}
      &:nth-child(4) {//your styles here}
      &:nth-child(6) {//your styles here}
      }
  }
}

How to switch to another domain and get-aduser

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite

Get-ADUser -Server $dc.HostName[0] `
    -Filter { EmailAddress -Like "*Smith_Karla*" } `
    -Properties EmailAddress

jQuery Mobile Page refresh mechanism

function refreshPage()
{
    jQuery.mobile.changePage(window.location.href, {
        allowSamePageTransition: true,
        transition: 'none',
        reloadPage: true
    });
}

Taken from here http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/ also tested on jQuery Mobile 1.2.0

I want to multiply two columns in a pandas DataFrame and add the result into a new column

You can use the DataFrame apply method:

order_df['Value'] = order_df.apply(lambda row: (row['Prices']*row['Amount']
                                               if row['Action']=='Sell'
                                               else -row['Prices']*row['Amount']),
                                   axis=1)

It is usually faster to use these methods rather than over for loops.

What does "async: false" do in jQuery.ajax()?

Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.

WebAPI to Return XML

You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.

If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.

Accept: application/xml

You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1

EDIT: based on your edited question with code:

Simple return list of string, instead of converting it to XML. try it using Fiddler.

public List<string> Get(int tenantID, string dataType, string ActionName)
    {
       List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
       return SQLResult;
     }

For example if your list is like:

List<string> list = new List<string>();
list.Add("Test1");
list.Add("Test2");
list.Add("Test3");
return list;

and you specify Accept: application/xml the output will be:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>Test1</string>
  <string>Test2</string>
  <string>Test3</string>
</ArrayOfstring>

and if you specify 'Accept: application/json' in the request then the output will be:

[
  "Test1",
  "Test2",
  "Test3"
]

So let the client request the content type, instead of you sending the customized xml.

Android design support library for API 28 (P) not working

Design support library for androidX is implementation 'com.google.android.material:material:1.0.0'

How to remove line breaks (no characters!) from the string?

To work properly also on Windows I'd suggest to use

$buffer = str_replace(array("\r\n", "\r", "\n"), "", $buffer);

"\r\n" - for Windows, "\r" - for Mac and "\n" - for Linux

ValueError: invalid literal for int () with base 10

I got into the same issue when trying to use readlines() inside for loop for same file object... My suspicion is firing readling() inside readline() for same file object caused this error.

Best solution can be use seek(0) to reset file pointer or Handle condition with setting some flag then create new object for same file by checking set condition....

Can HTML checkboxes be set to readonly?

Just use simple disabled tag like this below.

<input type="checkbox" name="email"  disabled>

Saving an Object (Data persistence)

You could use the pickle module in the standard library. Here's an elementary application of it to your example:

import pickle

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

with open('company_data.pkl', 'wb') as output:
    company1 = Company('banana', 40)
    pickle.dump(company1, output, pickle.HIGHEST_PROTOCOL)

    company2 = Company('spam', 42)
    pickle.dump(company2, output, pickle.HIGHEST_PROTOCOL)

del company1
del company2

with open('company_data.pkl', 'rb') as input:
    company1 = pickle.load(input)
    print(company1.name)  # -> banana
    print(company1.value)  # -> 40

    company2 = pickle.load(input)
    print(company2.name) # -> spam
    print(company2.value)  # -> 42

You could also define your own simple utility like the following which opens a file and writes a single object to it:

def save_object(obj, filename):
    with open(filename, 'wb') as output:  # Overwrites any existing file.
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

# sample usage
save_object(company1, 'company1.pkl')

Update

Since this is such a popular answer, I'd like touch on a few slightly advanced usage topics.

cPickle (or _pickle) vs pickle

It's almost always preferable to actually use the cPickle module rather than pickle because the former is written in C and is much faster. There are some subtle differences between them, but in most situations they're equivalent and the C version will provide greatly superior performance. Switching to it couldn't be easier, just change the import statement to this:

import cPickle as pickle

In Python 3, cPickle was renamed _pickle, but doing this is no longer necessary since the pickle module now does it automatically—see What difference between pickle and _pickle in python 3?.

The rundown is you could use something like the following to ensure that your code will always use the C version when it's available in both Python 2 and 3:

try:
    import cPickle as pickle
except ModuleNotFoundError:
    import pickle

Data stream formats (protocols)

pickle can read and write files in several different, Python-specific, formats, called protocols as described in the documentation, "Protocol version 0" is ASCII and therefore "human-readable". Versions > 0 are binary and the highest one available depends on what version of Python is being used. The default also depends on Python version. In Python 2 the default was Protocol version 0, but in Python 3.8.1, it's Protocol version 4. In Python 3.x the module had a pickle.DEFAULT_PROTOCOL added to it, but that doesn't exist in Python 2.

Fortunately there's shorthand for writing pickle.HIGHEST_PROTOCOL in every call (assuming that's what you want, and you usually do), just use the literal number -1 — similar to referencing the last element of a sequence via a negative index. So, instead of writing:

pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

You can just write:

pickle.dump(obj, output, -1)

Either way, you'd only have specify the protocol once if you created a Pickler object for use in multiple pickle operations:

pickler = pickle.Pickler(output, -1)
pickler.dump(obj1)
pickler.dump(obj2)
   etc...

Note: If you're in an environment running different versions of Python, then you'll probably want to explicitly use (i.e. hardcode) a specific protocol number that all of them can read (later versions can generally read files produced by earlier ones).

Multiple Objects

While a pickle file can contain any number of pickled objects, as shown in the above samples, when there's an unknown number of them, it's often easier to store them all in some sort of variably-sized container, like a list, tuple, or dict and write them all to the file in a single call:

tech_companies = [
    Company('Apple', 114.18), Company('Google', 908.60), Company('Microsoft', 69.18)
]
save_object(tech_companies, 'tech_companies.pkl')

and restore the list and everything in it later with:

with open('tech_companies.pkl', 'rb') as input:
    tech_companies = pickle.load(input)

The major advantage is you don't need to know how many object instances are saved in order to load them back later (although doing so without that information is possible, it requires some slightly specialized code). See the answers to the related question Saving and loading multiple objects in pickle file? for details on different ways to do this. Personally I like @Lutz Prechelt's answer the best. Here's it adapted to the examples here:

class Company:
    def __init__(self, name, value):
        self.name = name
        self.value = value

def pickled_items(filename):
    """ Unpickle a file of pickled data. """
    with open(filename, "rb") as f:
        while True:
            try:
                yield pickle.load(f)
            except EOFError:
                break

print('Companies in pickle file:')
for company in pickled_items('company_data.pkl'):
    print('  name: {}, value: {}'.format(company.name, company.value))

Determine installed PowerShell version

To check if PowerShell is installed use:

HKLM\Software\Microsoft\PowerShell\1 Install ( = 1 )

To check if RC2 or RTM is installed use:

HKLM\Software\Microsoft\PowerShell\1 PID (=89393-100-0001260-00301) -- For RC2
HKLM\Software\Microsoft\PowerShell\1 PID (=89393-100-0001260-04309) -- For RTM

Source: this website.

Open Sublime Text from Terminal in macOS

In OS X Mavericks running Sublime Text 2 the following worked for me.

sudo ln -s /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl /usr/bin/subl

Its handy to locate the file in the finder and drag and drop that into the terminal window so you can be sure the path is the correct one, I'm not a huge terminal user so this was more comfortable for me. then you can go to the start of the path and start adding in the other parts like the shorthand UNIX commands. Hope this helps

process.env.NODE_ENV is undefined

You can also set it by code, for example:

process.env.NODE_ENV = 'test';

Occurrences of substring in a string

How about using StringUtils.countMatches from Apache Commons Lang?

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

That outputs:

3

Escaping double quotes in JavaScript onClick event handler

Did you try

&quot; or \x22

instead of

\"

?

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

Android disable screen timeout while app is running

procedure SetSleep(aEnable:Boolean);
var
    vFlags: integer;
begin
    vFlags := TJWindowManager_LayoutParams.JavaClass.FLAG_TURN_SCREEN_ON or
        TJWindowManager_LayoutParams.JavaClass.FLAG_DISMISS_KEYGUARD or
        TJWindowManager_LayoutParams.JavaClass.FLAG_SHOW_WHEN_LOCKED or
        TJWindowManager_LayoutParams.JavaClass.FLAG_KEEP_SCREEN_ON;

    if aEnable then
    begin
      CallInUIThread (   // uses FMX.Helpers.Android
      procedure
      begin
        TAndroidHelper.Activity.getWindow.setFlags (vFlags, vFlags);
      end );
    end
    else
      CallInUIThread (
      procedure
      begin
        TAndroidHelper.Activity.getWindow.clearFlags (vFlags);
      end );
end;

Having Django serve downloadable files

It was mentioned above that the mod_xsendfile method does not allow for non-ASCII characters in filenames.

For this reason, I have a patch available for mod_xsendfile that will allow any file to be sent, as long as the name is url encoded, and the additional header:

X-SendFile-Encoding: url

Is sent as well.

http://ben.timby.com/?p=149

How to reduce the image file size using PIL

A built-in parameter for saving JPEGs and PNGs is optimize.

 >>> from PIL import Image
 # My image is a 200x374 jpeg that is 102kb large
 >>> foo = Image.open("path\\to\\image.jpg")
 >>> foo.size
  (200,374)
 # I downsize the image with an ANTIALIAS filter (gives the highest quality)
 >>> foo = foo.resize((160,300),Image.ANTIALIAS)
 >>> foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
 # The saved downsized image size is 24.8kb
 >>> foo.save("path\\to\\save\\image_scaled_opt.jpg",optimize=True,quality=95)
 # The saved downsized image size is 22.9kb

The optimize flag will do an extra pass on the image to find a way to reduce its size as much as possible. 1.9kb might not seem like much, but over hundreds/thousands of pictures, it can add up.

Now to try and get it down to 5kb to 10 kb, you can change the quality value in the save options. Using a quality of 85 instead of 95 in this case would yield: Unoptimized: 15.1kb Optimized : 14.3kb Using a quality of 75 (default if argument is left out) would yield: Unoptimized: 11.8kb Optimized : 11.2kb

I prefer quality 85 with optimize because the quality isn't affected much, and the file size is much smaller.

How do I limit the number of decimals printed for a double?

Formatter class is also a good option. fmt.format("%.2f", variable); 2 here is showing how many decimals you want. You can change it to 4 for example. Don't forget to close the formatter.

 private static int nJars, nCartons, totalOunces, OuncesTolbs, lbs;

 public static void main(String[] args)
  {
   computeShippingCost();
  }

  public static void computeShippingCost()
  {
   System.out.print("Enter a number of jars: ");
   Scanner kboard = new Scanner (System.in);
   nJars = kboard.nextInt();
   int nCartons = (nJars + 11) / 12;
   int totalOunces = (nJars * 21) + (nCartons * 25);
   int lbs = totalOunces / 16;


   double shippingCost =  ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;

     Formatter fmt = new Formatter();
     fmt.format("%.2f", shippingCost);

   System.out.print("$" + fmt);

   fmt.close();

}

How to create a JSON object

You just need another layer in your php array:

$post_data = array(
  'item' => array(
    'item_type_id' => $item_type,
    'string_key' => $string_key,
    'string_value' => $string_value,
    'string_extra' => $string_extra,
    'is_public' => $public,
   'is_public_for_contacts' => $public_contacts
  )
);

echo json_encode($post_data);

How to change a nullable column to not nullable in a Rails migration?

You can't use add_timestamps and null:false if you have existing records, so here is the solution :

def change
  add_timestamps(:buttons, null: true)

  Button.find_each { |b| b.update(created_at: Time.zone.now, updated_at: Time.zone.now) }

  change_column_null(:buttons, :created_at, false)
  change_column_null(:buttons, :updated_at, false)
end

python's re: return True if string contains regex pattern

Match objects are always true, and None is returned if there is no match. Just test for trueness.

Code:

>>> st = 'bar'
>>> m = re.match(r"ba[r|z|d]",st)
>>> if m:
...     m.group(0)
...
'bar'

Output = bar

If you want search functionality

>>> st = "bar"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m is not None:
...     m.group(0)
...
'bar'

and if regexp not found than

>>> st = "hello"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m:
...     m.group(0)
... else:
...   print "no match"
...
no match

As @bukzor mentioned if st = foo bar than match will not work. So, its more appropriate to use re.search.

Convert int to string?

string str = intVar.ToString();

In some conditions, you do not have to use ToString()

string str = "hi " + intVar;

Using dig to search for SPF records

I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:

dig @ns1.nameserver1.com domain.com txt

JSON encode MySQL results

$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

The function json_encode needs PHP >= 5.2 and the php-json package - as mentioned here

NOTE: mysql is deprecated as of PHP 5.5.0, use mysqli extension instead http://php.net/manual/en/migration55.deprecated.php.

Selecting text in an element (akin to highlighting with your mouse)

Tim's method works perfectly for my case - selecting the text in a div for both IE and FF after I replaced the following statement:

range.moveToElementText(text);

with the following:

range.moveToElementText(el);

The text in the div is selected by clicking it with the following jQuery function:

$(function () {
    $("#divFoo").click(function () {
        selectElementText(document.getElementById("divFoo"));
    })
});

Strip HTML from Text JavaScript

I just needed to strip out the <a> tags and replace them with the text of the link.

This seems to work great.

htmlContent= htmlContent.replace(/<a.*href="(.*?)">/g, '');
htmlContent= htmlContent.replace(/<\/a>/g, '');

Fragment onResume() & onPause() is not called on backstack

Here's my more robust version of Gor's answer (using fragments.size()is unreliable due to size not being decremented after fragment is popped)

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if (getFragmentManager() != null) {

                Fragment topFrag = NavigationHelper.getCurrentTopFragment(getFragmentManager());

                if (topFrag != null) {
                    if (topFrag instanceof YourFragment) {
                        //This fragment is being shown. 
                    } else {
                        //Navigating away from this fragment. 
                    }
                }
            }
        }
    });

And the 'getCurrentTopFragment' method:

public static Fragment getCurrentTopFragment(FragmentManager fm) {
    int stackCount = fm.getBackStackEntryCount();

    if (stackCount > 0) {
        FragmentManager.BackStackEntry backEntry = fm.getBackStackEntryAt(stackCount-1);
        return  fm.findFragmentByTag(backEntry.getName());
    } else {
        List<Fragment> fragments = fm.getFragments();
        if (fragments != null && fragments.size()>0) {
            for (Fragment f: fragments) {
                if (f != null && !f.isHidden()) {
                    return f;
                }
            }
        }
    }
    return null;
}

Spring configure @ResponseBody JSON format

AngerClown pointed me to the right direction.

This is what I finally did, just in case anyone find it useful.

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>
        </list>
    </property>
</bean>

<!-- jackson configuration : https://stackoverflow.com/questions/3661769 -->
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="jacksonSerializationConfig" />
    <property name="targetMethod" value="setSerializationInclusion" />
    <property name="arguments">
        <list>
            <value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_DEFAULT</value>
        </list>
    </property>
</bean>

I still have to figure out how to configure the other properties such as:

om.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);

How to copy file from one location to another location?

Use the New Java File classes in Java >=7.

Create the below method and import the necessary libs.

public static void copyFile( File from, File to ) throws IOException {
    Files.copy( from.toPath(), to.toPath() );
} 

Use the created method as below within main:

File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);

try {
        copyFile(dirFrom, dirTo);
} catch (IOException ex) {
        Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
}

NB:- fileFrom is the file that you want to copy to a new file fileTo in a different folder.

Credits - @Scott: Standard concise way to copy a file in Java?

How to make the window full screen with Javascript (stretching all over the screen)

Here is a complete solution to get in and out of full screen mode (aka cancel, exit, escape)

        function cancelFullScreen() {
            var el = document;
            var requestMethod = el.cancelFullScreen||el.webkitCancelFullScreen||el.mozCancelFullScreen||el.exitFullscreen||el.webkitExitFullscreen;
            if (requestMethod) { // cancel full screen.
                requestMethod.call(el);
            } else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
                var wscript = new ActiveXObject("WScript.Shell");
                if (wscript !== null) {
                    wscript.SendKeys("{F11}");
                }
            }
        }

        function requestFullScreen(el) {
            // Supports most browsers and their versions.
            var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreen;

            if (requestMethod) { // Native full screen.
                requestMethod.call(el);
            } else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
                var wscript = new ActiveXObject("WScript.Shell");
                if (wscript !== null) {
                    wscript.SendKeys("{F11}");
                }
            }
            return false
        }

        function toggleFullScreen(el) {
            if (!el) {
                el = document.body; // Make the body go full screen.
            }
            var isInFullScreen = (document.fullScreenElement && document.fullScreenElement !== null) ||  (document.mozFullScreen || document.webkitIsFullScreen);

            if (isInFullScreen) {
                cancelFullScreen();
            } else {
                requestFullScreen(el);
            }
            return false;
        }

How to remove the border highlight on an input text element

Removing all focus styles is bad for accessibility and keyboard users in general. But outlines are ugly and providing a custom focussed style for every single interactive element can be a real pain.

So the best compromise I've found is to show the outline styles only when we detect that the user is using the keyboard to navigate. Basically, if the user presses TAB, we show the outlines and if he uses the mouse, we hide them.

It does not stop you from writing custom focus styles for some elements but at least it provides a good default.

This is how I do it:

_x000D_
_x000D_
// detect keyboard users_x000D_
_x000D_
const keyboardUserCssClass = "keyboardUser";_x000D_
_x000D_
function setIsKeyboardUser(isKeyboard) {_x000D_
  const { body } = document;_x000D_
  if (isKeyboard) {_x000D_
   body.classList.contains(keyboardUserCssClass) || body.classList.add(keyboardUserCssClass);_x000D_
  } else {_x000D_
   body.classList.remove(keyboardUserCssClass);_x000D_
  }_x000D_
}_x000D_
_x000D_
// This is a quick hack to activate focus styles only when the user is_x000D_
// navigating with TAB key. This is the best compromise we've found to_x000D_
// keep nice design without sacrifying accessibility._x000D_
document.addEventListener("keydown", e => {_x000D_
  if (e.key === "Tab") {_x000D_
   setIsKeyboardUser(true);_x000D_
  }_x000D_
});_x000D_
document.addEventListener("click", e => {_x000D_
  // Pressing ENTER on buttons triggers a click event with coordinates to 0_x000D_
  setIsKeyboardUser(!e.screenX && !e.screenY);_x000D_
});_x000D_
_x000D_
document.addEventListener("mousedown", e => {_x000D_
  setIsKeyboardUser(false);_x000D_
});
_x000D_
body:not(.keyboardUser) *:focus {_x000D_
  outline: none;_x000D_
}
_x000D_
<p>By default, you'll see no outline. But press TAB key and you'll see focussed element</p>_x000D_
<button>This is a button</button>_x000D_
<a href="#">This is anchor link</a>_x000D_
<input type="checkbox" />_x000D_
<textarea>textarea</textarea>_x000D_
<select/>
_x000D_
_x000D_
_x000D_

Which exception should I raise on bad/illegal argument combinations in Python?

Agree with Markus' suggestion to roll your own exception, but the text of the exception should clarify that the problem is in the argument list, not the individual argument values. I'd propose:

class BadCallError(ValueError):
    pass

Used when keyword arguments are missing that were required for the specific call, or argument values are individually valid but inconsistent with each other. ValueError would still be right when a specific argument is right type but out of range.

Shouldn't this be a standard exception in Python?

In general, I'd like Python style to be a bit sharper in distinguishing bad inputs to a function (caller's fault) from bad results within the function (my fault). So there might also be a BadArgumentError to distinguish value errors in arguments from value errors in locals.

Matplotlib scatterplot; colour as a function of a third variable

In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'

Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:

from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [str(item/255.) for item in y]

plt.scatter(x, y, s=500, c=color)

plt.show()

enter image description here

ImportError: No module named matplotlib.pyplot

The file permissions on my virtual environment directory and my project directory were not correct and, thus, would not allow me to install the proper packages. I upadated them by running:

sudo chown user:user -R [project folder]
sudo chown user:user -R [environment folder]

In the above your should use your own usernames in place of "user". The -R recurses through all subfolders and files.

How do I check to see if a value is an integer in MySQL?

I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do

select field from table where field REGEXP '^-?[0-9]+$';

this is reasonably fast. If your field is numeric, just test for

ceil(field) = field

instead.

Regex Match all characters between two strings

For example

(?<=This is)(.*)(?=sentence)

Regexr

I used lookbehind (?<=) and look ahead (?=) so that "This is" and "sentence" is not included in the match, but this is up to your use case, you can also simply write This is(.*)sentence.

The important thing here is that you activate the "dotall" mode of your regex engine, so that the . is matching the newline. But how you do this depends on your regex engine.

The next thing is if you use .* or .*?. The first one is greedy and will match till the last "sentence" in your string, the second one is lazy and will match till the next "sentence" in your string.

Update

Regexr

This is(?s)(.*)sentence

Where the (?s) turns on the dotall modifier, making the . matching the newline characters.

Update 2:

(?<=is \()(.*?)(?=\s*\))

is matching your example "This is (a simple) sentence". See here on Regexr

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

If you are using dj-database-url check the schema in your DATABASES

https://github.com/kennethreitz/dj-database-url

MySQL is

'default': dj_database_url.config(default='mysql://USER:PASSWORD@localhost:PORT/NAME') 

It solves the same error even without the PORT

You set the password with:

mysql -u user -p 

Difference between scaling horizontally and vertically for databases

The accepted answer is spot on the basic definition of horizontal vs vertical scaling. But unlike the common belief that horizontal scaling of databases is only possible with Cassandra, MongoDB, etc I would like to add that horizontal scaling is also very much possible with any traditional RDMS; that too without using any third party solutions.

I know of many companies, specially SaaS based companies that do this. This is done using simple application logic. You basically take a set of users and divide them over multiple DB servers. So for example, you would typically have a "meta" database/table that would store clients, DB server/connection strings, etc and a table that stores client/server mapping.

Then simply direct requests from each client to the DB server they are mapped to.

Now some may say this is akin to horizontal partitioning and not "true" horizontal scaling and they will be right in some ways. But the end result is that you have scaled your DB over multiple Db servers.

The only difference between the two approaches to horizontal scaling is that one approach (MongoDB, etc) the scaling is done by the DB software itself. In that sense you are "buying" the scaling. In the other approach (for RDBMS horizontal scaling), the scaling is built by application code/logic.

Buy vs Build

Is it possible to create a File object from InputStream

You need to create new file and copy contents from InputStream to that file:

File file = //...
try(OutputStream outputStream = new FileOutputStream(file)){
    IOUtils.copy(inputStream, outputStream);
} catch (FileNotFoundException e) {
    // handle exception here
} catch (IOException e) {
    // handle exception here
}

I am using convenient IOUtils.copy() to avoid manual copying of streams. Also it has built-in buffering.

Test for multiple cases in a switch, like an OR (||)

You need to make two case labels.

Control will fall through from the first label to the second, so they'll both execute the same code.

How to change the Title of the window in Qt?

system("title WhateverYouWantToNameIt");

Pass an array of integers to ASP.NET Web API?

I originally used the solution that @Mrchief for years (it works great). But when when I added Swagger to my project for API documentation my end point was NOT showing up.

It took me a while, but this is what I came up with. It works with Swagger, and your API method signatures look cleaner:

In the end you can do:

    // GET: /api/values/1,2,3,4 

    [Route("api/values/{ids}")]
    public IHttpActionResult GetIds(int[] ids)
    {
        return Ok(ids);
    }

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Allow WebApi to Use a Custom Parameter Binding
        config.ParameterBindingRules.Add(descriptor => descriptor.ParameterType == typeof(int[]) && descriptor.ActionDescriptor.SupportedHttpMethods.Contains(HttpMethod.Get)
                                                           ? new CommaDelimitedArrayParameterBinder(descriptor)
                                                           : null);

        // Allow ApiExplorer to understand this type (Swagger uses ApiExplorer under the hood)
        TypeDescriptor.AddAttributes(typeof(int[]), new TypeConverterAttribute(typeof(StringToIntArrayConverter)));

        // Any existing Code ..

    }
}

Create a new class: CommaDelimitedArrayParameterBinder.cs

public class CommaDelimitedArrayParameterBinder : HttpParameterBinding, IValueProviderParameterBinding
{
    public CommaDelimitedArrayParameterBinder(HttpParameterDescriptor desc)
        : base(desc)
    {
    }

    /// <summary>
    /// Handles Binding (Converts a comma delimited string into an array of integers)
    /// </summary>
    public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
                                             HttpActionContext actionContext,
                                             CancellationToken cancellationToken)
    {
        var queryString = actionContext.ControllerContext.RouteData.Values[Descriptor.ParameterName] as string;

        var ints = queryString?.Split(',').Select(int.Parse).ToArray();

        SetValue(actionContext, ints);

        return Task.CompletedTask;
    }

    public IEnumerable<ValueProviderFactory> ValueProviderFactories { get; } = new[] { new QueryStringValueProviderFactory() };
}

Create a new class: StringToIntArrayConverter.cs

public class StringToIntArrayConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
    }
}

Notes:

C# windows application Event: CLR20r3 on application start

I encountered the same problem when I built an application on a Windows 7 box that had previously been maintained on an XP machine.

The program ran fine when built for Debug, but failed with this error when built for Release. I found the answer on the project's Properties page. Go to the "Build" tab and try changing the Platform Target from "Any CPU" to "x86".

EF LINQ include multiple and nested entities

In Entity Framework Core (EF.core) you can use .ThenInclude for including next levels.

var blogs = context.Blogs
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
    .ToList();

More information: https://docs.microsoft.com/en-us/ef/core/querying/related-data

Note: Say you need multiple ThenInclude() on blog.Posts, just repeat the Include(blog => blog.Posts) and do another ThenInclude(post => post.Other).

var blogs = context.Blogs
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Other)
 .ToList();

Sibling package imports

I wanted to comment on the solution provided by np8 but I don't have enough reputation so I'll just mention that you can create a setup.py file exactly as they suggested, and then do pipenv install --dev -e . from the project root directory to turn it into an editable dependency. Then your absolute imports will work e.g. from api.api import foo and you don't have to mess around with system-wide installations.

Documentation

Adding iOS UITableView HeaderView (not section header)

You can do it pretty easy in Interface Builder. Just create a view with a table and drop another view onto the table. This will become the table header view. Add your labels and image to that view. See the pic below for the view hierarchy. View Hierarchy in Interface Builder

How to decode a Base64 string?

There are no PowerShell-native commands for Base64 conversion - yet (as of PowerShell [Core] 7.1), but adding dedicated cmdlets has been suggested.
For now, direct use of .NET is needed.

Important:

  • Base64 encoding is an encoding of binary data using bytes whose values are constrained to a well-defined 64-character subrange of the ASCII character set representing printable characters, devised at a time when sending arbitrary bytes was problematic, especially with the high bit set (byte values > 0x7f).

  • Therefore, you must always specify explicitly what character encoding the Base64 bytes do / should represent.

Ergo:

  • on converting TO Base64, you must first obtain a byte representation of the string you're trying to encode using the character encoding the consumer of the Base64 string expects.

  • on converting FROM Base64, you must interpret the resultant array of bytes as a string using the same encoding that was used to create the Base64 representation.

Examples:

Note:

  • The following examples convert to and from UTF-8 encoded strings:

  • To convert to and from UTF-16LE ("Unicode") instead, substitute [Text.Encoding]::Unicode for [Text.Encoding]::UTF8

Convert TO Base64:

PS> [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('Motörhead'))
TW90w7ZyaGVhZA==

Convert FROM Base64:

PS> [Text.Encoding]::Utf8.GetString([Convert]::FromBase64String('TW90w7ZyaGVhZA=='))
Motörhead

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

Run JavaScript in Visual Studio Code

There is no need to set the environment for running the code on javascript,python,etc in visual studio code what you have to do is just install the Code Runner Extension and then just select the part of the code you want to run and hit the run button present on the upper right corner.

Failing to run jar file from command line: “no main manifest attribute”

The -jar option only works if the JAR file is an executable JAR file, which means it must have a manifest file with a Main-Class attribute in it.

If it's not an executable JAR, then you'll need to run the program with something like:

java -cp app.jar com.somepackage.SomeClass

where com.somepackage.SomeClass is the class that contains the main method to run the program.

C++ float array initialization

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

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

Set the dimensions to the View and make sure your Image is styled with height and width set to 'undefined' like the example below :

    <View style={{width: 10, height:10 }} >
      <Image style= {{flex:1 , width: undefined, height: undefined}}    
       source={require('../yourfolder/yourimage')}
        />
    </View>

This will make sure your image scales and fits perfectly into your view.

What is char ** in C?

Technically, the char* is not an array, but a pointer to a char.

Similarly, char** is a pointer to a char*. Making it a pointer to a pointer to a char.

C and C++ both define arrays behind-the-scenes as pointer types, so yes, this structure, in all likelihood, is array of arrays of chars, or an array of strings.

Create Directory When Writing To File In Node.js

I just published this module because I needed this functionality.

https://www.npmjs.org/package/filendir

It works like a wrapper around Node.js fs methods. So you can use it exactly the same way you would with fs.writeFile and fs.writeFileSync (both async and synchronous writes)

Assert an object is a specific type

Solution for JUnit 5 for Kotlin!

Example for Hamcrest:

import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert
import org.junit.jupiter.api.Test

class HamcrestAssertionDemo {

    @Test
    fun assertWithHamcrestMatcher() {
        val subClass = SubClass()
        MatcherAssert.assertThat(subClass, CoreMatchers.instanceOf<Any>(BaseClass::class.java))
    }

}

Example for AssertJ:

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test

class AssertJDemo {

    @Test
    fun assertWithAssertJ() {
        val subClass = SubClass()
        assertThat(subClass).isInstanceOf(BaseClass::class.java)
    }

}

Visually managing MongoDB documents and collections

There is a web-based project for this that is relatively early on called Pongo. It requires installing Python and some dependencies, but it should run on Windows.

Calling a stored procedure in Oracle with IN and OUT parameters

I had the same problem. I used a trigger and in that trigger I called a procedure which computed some values into 2 OUT variables. When I tried to print the result in the trigger body, nothing showed on screen. But then I solved this problem by making 2 local variables in a function, computed what I need with them and finally, copied those variables in your OUT procedure variables. I hope it'll be useful and successful!

How to check whether a string is Base64 encoded or not

Well you can:

  • Check that the length is a multiple of 4 characters
  • Check that every character is in the set A-Z, a-z, 0-9, +, / except for padding at the end which is 0, 1 or 2 '=' characters

If you're expecting that it will be base64, then you can probably just use whatever library is available on your platform to try to decode it to a byte array, throwing an exception if it's not valid base 64. That depends on your platform, of course.

port 8080 is already in use and no process using 8080 has been listed

In windows " wmic process where processid="pid of the process running" get commandline " worked for me. The culprit was wrapper.exe process of webhuddle jboss soft.

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

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

Run again your problem will be solved

Transparent background in JPEG image

JPG does not support a transparent background, you can easily convert it to a PNG which does support a transparent background by opening it in near any photo editor and save it as a.PNG

Javascript to open popup window and disable parent window

To my knowledge, you cannot disable the browser window.

What you can do is create a jQuery (or a similar kind of ) popup and when this popup appears your parent browser will be disabled.

Open your child page in popup.

How do I write to a Python subprocess' stdin?

It might be better to use communicate:

from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]

"Better", because of this warning:

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

How to add text to a WPF Label in code?

I believe you want to set the Content property. This has more information on what is available to a label.

Terminating a script in PowerShell

Write-Error is for non-terminating errors and throw is for terminating errors

The Write-Error cmdlet declares a non-terminating error. By default, errors are sent in the error stream to the host program to be displayed, along with output.

Non-terminating errors write an error to the error stream, but they do not stop command processing. If a non-terminating error is declared on one item in a collection of input items, the command continues to process the other items in the collection.

To declare a terminating error, use the Throw keyword. For more information, see about_Throw (http://go.microsoft.com/fwlink/?LinkID=145153).

How do I send an HTML email?

You can use setText(java.lang.String text, boolean html) from MimeMessageHelper:

MimeMessage mimeMsg = javaMailSender.createMimeMessage();
MimeMessageHelper msgHelper = new MimeMessageHelper(mimeMsg, false, "utf-8");
boolean isHTML = true;
msgHelper.setText("<h1>some html</h1>", isHTML);

But you need to:

mimeMsg.saveChanges();

Before:

javaMailSender.send(mimeMsg);

Generating random integer from a range

Let's split the problem into two parts:

  • Generate a random number n in the range 0 through (max-min).
  • Add min to that number

The first part is obviously the hardest. Let's assume that the return value of rand() is perfectly uniform. Using modulo will add bias to the first (RAND_MAX + 1) % (max-min+1) numbers. So if we could magically change RAND_MAX to RAND_MAX - (RAND_MAX + 1) % (max-min+1), there would no longer be any bias.

It turns out that we can use this intuition if we are willing to allow pseudo-nondeterminism into the running time of our algorithm. Whenever rand() returns a number which is too large, we simply ask for another random number until we get one which is small enough.

The running time is now geometrically distributed, with expected value 1/p where p is the probability of getting a small enough number on the first try. Since RAND_MAX - (RAND_MAX + 1) % (max-min+1) is always less than (RAND_MAX + 1) / 2, we know that p > 1/2, so the expected number of iterations will always be less than two for any range. It should be possible to generate tens of millions of random numbers in less than a second on a standard CPU with this technique.

EDIT:

Although the above is technically correct, DSimon's answer is probably more useful in practice. You shouldn't implement this stuff yourself. I have seen a lot of implementations of rejection sampling and it is often very difficult to see if it's correct or not.

Docker: adding a file from a parent directory

Since -f caused another problem, I developed another solution.

  • Create a base image in the parent folder
  • Added the required files.
  • Used this image as a base image for the project which in a descendant folder.

The -f flag does not solved my problem because my onbuild image looks for a file in a folder and had to call like this:

-f foo/bar/Dockerfile foo/bar

instead of

-f foo/bar/Dockerfile .

Also note that this is only solution for some cases as -f flag

What is the best way to convert an array to a hash in Ruby

Summary & TL;DR:

This answer hopes to be a comprehensive wrap-up of information from other answers.

The very short version, given the data from the question plus a couple extras:

flat_array   = [  apple, 1,   banana, 2  ] # count=4
nested_array = [ [apple, 1], [banana, 2] ] # count=2 of count=2 k,v arrays
incomplete_f = [  apple, 1,   banana     ] # count=3 - missing last value
incomplete_n = [ [apple, 1], [banana   ] ] # count=2 of either k or k,v arrays


# there's one option for flat_array:
h1  = Hash[*flat_array]                     # => {apple=>1, banana=>2}

# two options for nested_array:
h2a = nested_array.to_h # since ruby 2.1.0    => {apple=>1, banana=>2}
h2b = Hash[nested_array]                    # => {apple=>1, banana=>2}

# ok if *only* the last value is missing:
h3  = Hash[incomplete_f.each_slice(2).to_a] # => {apple=>1, banana=>nil}
# always ok for k without v in nested array:
h4  = Hash[incomplete_n] # or .to_h           => {apple=>1, banana=>nil}

# as one might expect:
h1 == h2a # => true
h1 == h2b # => true
h1 == h3  # => false
h3 == h4  # => true

Discussion and details follow.


Setup: variables

In order to show the data we'll be using up front, I'll create some variables to represent various possibilities for the data. They fit into the following categories:

Based on what was directly in the question, as a1 and a2:

(Note: I presume that apple and banana were meant to represent variables. As others have done, I'll be using strings from here on so that input and results can match.)

a1 = [  'apple', 1 ,  'banana', 2  ] # flat input
a2 = [ ['apple', 1], ['banana', 2] ] # key/value paired input

Multi-value keys and/or values, as a3:

In some other answers, another possibility was presented (which I expand on here) – keys and/or values may be arrays on their own:

a3 = [ [ 'apple',                   1   ],
       [ 'banana',                  2   ],
       [ ['orange','seedless'],     3   ],
       [ 'pear',                 [4, 5] ],
     ]

Unbalanced array, as a4:

For good measure, I thought I'd add one for a case where we might have an incomplete input:

a4 = [ [ 'apple',                   1],
       [ 'banana',                  2],
       [ ['orange','seedless'],     3],
       [ 'durian'                    ], # a spiky fruit pricks us: no value!
     ]

Now, to work:

Starting with an initially-flat array, a1:

Some have suggested using #to_h (which showed up in Ruby 2.1.0, and can be backported to earlier versions). For an initially-flat array, this doesn't work:

a1.to_h   # => TypeError: wrong element type String at 0 (expected array)

Using Hash::[] combined with the splat operator does:

Hash[*a1] # => {"apple"=>1, "banana"=>2}

So that's the solution for the simple case represented by a1.

With an array of key/value pair arrays, a2:

With an array of [key,value] type arrays, there are two ways to go.

First, Hash::[] still works (as it did with *a1):

Hash[a2] # => {"apple"=>1, "banana"=>2}

And then also #to_h works now:

a2.to_h  # => {"apple"=>1, "banana"=>2}

So, two easy answers for the simple nested array case.

This remains true even with sub-arrays as keys or values, as with a3:

Hash[a3] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]} 
a3.to_h  # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]}

But durians have spikes (anomalous structures give problems):

If we've gotten input data that's not balanced, we'll run into problems with #to_h:

a4.to_h  # => ArgumentError: wrong array length at 3 (expected 2, was 1)

But Hash::[] still works, just setting nil as the value for durian (and any other array element in a4 that's just a 1-value array):

Hash[a4] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}

Flattening - using new variables a5 and a6

A few other answers mentioned flatten, with or without a 1 argument, so let's create some new variables:

a5 = a4.flatten
# => ["apple", 1, "banana", 2,  "orange", "seedless" , 3, "durian"] 
a6 = a4.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian"] 

I chose to use a4 as the base data because of the balance problem we had, which showed up with a4.to_h. I figure calling flatten might be one approach someone might use to try to solve that, which might look like the following.

flatten without arguments (a5):

Hash[*a5]       # => {"apple"=>1, "banana"=>2, "orange"=>"seedless", 3=>"durian"}
# (This is the same as calling `Hash[*a4.flatten]`.)

At a naïve glance, this appears to work – but it got us off on the wrong foot with the seedless oranges, thus also making 3 a key and durian a value.

And this, as with a1, just doesn't work:

a5.to_h # => TypeError: wrong element type String at 0 (expected array)

So a4.flatten isn't useful to us, we'd just want to use Hash[a4]

The flatten(1) case (a6):

But what about only partially flattening? It's worth noting that calling Hash::[] using splat on the partially-flattened array (a6) is not the same as calling Hash[a4]:

Hash[*a6] # => ArgumentError: odd number of arguments for Hash

Pre-flattened array, still nested (alternate way of getting a6):

But what if this was how we'd gotten the array in the first place? (That is, comparably to a1, it was our input data - just this time some of the data can be arrays or other objects.) We've seen that Hash[*a6] doesn't work, but what if we still wanted to get the behavior where the last element (important! see below) acted as a key for a nil value?

In such a situation, there's still a way to do this, using Enumerable#each_slice to get ourselves back to key/value pairs as elements in the outer array:

a7 = a6.each_slice(2).to_a
# => [["apple", 1], ["banana", 2], [["orange", "seedless"], 3], ["durian"]] 

Note that this ends up getting us a new array that isn't "identical" to a4, but does have the same values:

a4.equal?(a7) # => false
a4 == a7      # => true

And thus we can again use Hash::[]:

Hash[a7] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}
# or Hash[a6.each_slice(2).to_a]

But there's a problem!

It's important to note that the each_slice(2) solution only gets things back to sanity if the last key was the one missing a value. If we later added an extra key/value pair:

a4_plus = a4.dup # just to have a new-but-related variable name
a4_plus.push(['lychee', 4])
# => [["apple",                1],
#     ["banana",               2],
#     [["orange", "seedless"], 3], # multi-value key
#     ["durian"],              # missing value
#     ["lychee", 4]]           # new well-formed item

a6_plus = a4_plus.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian", "lychee", 4]

a7_plus = a6_plus.each_slice(2).to_a
# => [["apple",                1],
#     ["banana",               2],
#     [["orange", "seedless"], 3], # so far so good
#     ["durian",               "lychee"], # oops! key became value!
#     [4]]                     # and we still have a key without a value

a4_plus == a7_plus # => false, unlike a4 == a7

And the two hashes we'd get from this are different in important ways:

ap Hash[a4_plus] # prints:
{
                     "apple" => 1,
                    "banana" => 2,
    [ "orange", "seedless" ] => 3,
                    "durian" => nil, # correct
                    "lychee" => 4    # correct
}

ap Hash[a7_plus] # prints:
{
                     "apple" => 1,
                    "banana" => 2,
    [ "orange", "seedless" ] => 3,
                    "durian" => "lychee", # incorrect
                           4 => nil       # incorrect
}

(Note: I'm using awesome_print's ap just to make it easier to show the structure here; there's no conceptual requirement for this.)

So the each_slice solution to an unbalanced flat input only works if the unbalanced bit is at the very end.


Take-aways:

  1. Whenever possible, set up input to these things as [key, value] pairs (a sub-array for each item in the outer array).
  2. When you can indeed do that, either #to_h or Hash::[] will both work.
  3. If you're unable to, Hash::[] combined with the splat (*) will work, so long as inputs are balanced.
  4. With an unbalanced and flat array as input, the only way this will work at all reasonably is if the last value item is the only one that's missing.

Side-note: I'm posting this answer because I feel there's value to be added – some of the existing answers have incorrect information, and none (that I read) gave as complete an answer as I'm endeavoring to do here. I hope that it's helpful. I nevertheless give thanks to those who came before me, several of whom provided inspiration for portions of this answer.

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

JQuery $.ajax() post - data in a java servlet

Simple method to sending data using java script and ajex call.

First right your form like this

<form id="frm_details" method="post" name="frm_details">
<input  id="email" name="email" placeholder="Your Email id" type="text" />
    <button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form> 

javascript logic target on form id #frm_details after sumbit

$(function(){
        $("#frm_details").on("submit", function(event) {
            event.preventDefault();

            var formData = {
                'email': $('input[name=email]').val() //for get email 
            };
            console.log(formData);

            $.ajax({
                url: "/tsmisc/api/subscribe-newsletter",
                type: "post",
                data: formData,
                success: function(d) {
                    alert(d);
                }
            });
        });
    }) 





General 
Request URL:https://test.abc
Request Method:POST
Status Code:200 
Remote Address:13.76.33.57:443

From Data
email:[email protected]

How to check if an app is installed from a web-page on an iPhone?

Didn't read all of these but may be use an iframe and adding the source to, "my app://whatever".

Then check regularly on set interval of the page is 404or not.

You could also use Ajax call. If 404 response then app is not installed.

Docker CE on RHEL - Requires: container-selinux >= 2.9

Docker CE is not supported on RHEL. Any way you are trying to get around that is not a supported way. You can see the supported platforms in the Docker Documentation. I suggest you either use a supported OS, or switch to Enterprise Edition.

Class is not abstract and does not override abstract method

Both classes Rectangle and Ellipse need to override both of the abstract methods.

To work around this, you have 3 options:

  • Add the two methods
  • Make each class that extends Shape abstract
  • Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:

    abstract class Shape {
        // ...
        void draw(Graphics g);
    }
    

And

    class Rectangle extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

Finally

    class Ellipse extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

And you can switch in between them, like so:

    Shape shape = new Ellipse();
    shape.draw(/* ... */);

    shape = new Rectangle();
    shape.draw(/* ... */);

Again, just an example.

axios post request to send form data

The above method worked for me but since it was something I needed often, I used a basic method for flat object. Note, I was also using Vue and not REACT

packageData: (data) => {
  const form = new FormData()
  for ( const key in data ) {
    form.append(key, data[key]);
  }
  return form
}

Which worked for me until I ran into more complex data structures with nested objects and files which then let to the following

packageData: (obj, form, namespace) => {
  for(const property in obj) {
    // if form is passed in through recursion assign otherwise create new
    const formData = form || new FormData()
    let formKey

    if(obj.hasOwnProperty(property)) {
      if(namespace) {
        formKey = namespace + '[' + property + ']';
      } else {
        formKey = property;
      }

      // if the property is an object, but not a File, use recursion.
      if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
        packageData(obj[property], formData, property);
      } else {
        // if it's a string or a File
      formData.append(formKey, obj[property]);
      }
    }
  }
  return formData;
}

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

I followed Mingcai SHEN's method.

But in my case, I changed the connector to

connector = C:\Program Files\MySQL\MySQL Connector.C 6.1

And the library_dirs is changed to

library_dirs = [ os.path.join(connector, r'lib\vs10') ]

because I don't have a vs9 directory. It works, but I don't know why.

I have vs2012 installed, and the lib directory of the connector only has vs10 and vs11, in which vs11 doesn't work. The VCForPyhton27.mis I installed seems to support vs9.

Anyway, this works. And if you want to risk it, you can try.

Commenting out a set of lines in a shell script

The most versatile and safe method is putting the comment into a void quoted here-document, like this:

<<"COMMENT"
    This long comment text includes ${parameter:=expansion}
    `command substitution` and $((arithmetic++ + --expansion)).
COMMENT

Quoting the COMMENT delimiter above is necessary to prevent parameter expansion, command substitution and arithmetic expansion, which would happen otherwise, as Bash manual states and POSIX shell standard specifies.

In the case above, not quoting COMMENT would result in variable parameter being assigned text expansion, if it was empty or unset, executing command command substitution, incrementing variable arithmetic and decrementing variable expansion.

Comparing other solutions to this:

Using if false; then comment text fi requires the comment text to be syntactically correct Bash code whereas natural comments are often not, if only for possible unbalanced apostrophes. The same goes for : || { comment text } construct.

Putting comments into a single-quoted void command argument, as in :'comment text', has the drawback of inability to include apostrophes. Double-quoted arguments, as in :"comment text", are still subject to parameter expansion, command substitution and arithmetic expansion, the same as unquoted here-document contents and can lead to the side-effects described above.

Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.

Reference member variables as class members

Is there a name to describe this idiom?

In UML it is called aggregation. It differs from composition in that the member object is not owned by the referring class. In C++ you can implement aggregation in two different ways, through references or pointers.

I am assuming it is to prevent the possibly large overhead of copying a big complex object?

No, that would be a really bad reason to use this. The main reason for aggregation is that the contained object is not owned by the containing object and thus their lifetimes are not bound. In particular the referenced object lifetime must outlive the referring one. It might have been created much earlier and might live beyond the end of the lifetime of the container. Besides that, the state of the referenced object is not controlled by the class, but can change externally. If the reference is not const, then the class can change the state of an object that lives outside of it.

Is this generally good practice? Are there any pitfalls to this approach?

It is a design tool. In some cases it will be a good idea, in some it won't. The most common pitfall is that the lifetime of the object holding the reference must never exceed the lifetime of the referenced object. If the enclosing object uses the reference after the referenced object was destroyed, you will have undefined behavior. In general it is better to prefer composition to aggregation, but if you need it, it is as good a tool as any other.

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

How to use export with Python on Linux

Kind of a hack because it's not really python doing anything special here, but if you run the export command in the same sub-shell, you will probably get the result you want.

import os

cmd = "export MY_DATA='1234'; echo $MY_DATA" # or whatever command
os.system(cmd)

Are there any log file about Windows Services Status?

Take a look at the System log in Windows EventViewer (eventvwr from the command line).
You should see entries with source as 'Service Control Manager'. e.g. on my WinXP machine,

Event Type: Information
Event Source:   Service Control Manager
Event Category: None
Event ID:   7036
Date:       7/1/2009
Time:       12:09:43 PM
User:       N/A
Computer:   MyMachine
Description:
The Background Intelligent Transfer Service service entered the running state.

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

Gradle should be updated already, you just need to let your previous projects know gradle has been updated.

Source

Edit your build.gradle file to show this:

dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}

This should only be required for projects created with the previous version of Android Studio. New projects you create will have that by default.

How to read a CSV file into a .NET Datatable

this is the code i use it but your apps must run with net version 3.5

private void txtRead_Click(object sender, EventArgs e)
        {
           // var filename = @"d:\shiptest.txt";

            openFileDialog1.InitialDirectory = "d:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                if (openFileDialog1.FileName != "")
                {
                    var reader = ReadAsLines(openFileDialog1.FileName);

                    var data = new DataTable();

                    //this assume the first record is filled with the column names
                    var headers = reader.First().Split(',');
                    foreach (var header in headers)
                    {
                        data.Columns.Add(header);
                    }

                    var records = reader.Skip(1);
                    foreach (var record in records)
                    {
                        data.Rows.Add(record.Split(','));
                    }

                    dgList.DataSource = data;
                }
            }
        }

        static IEnumerable<string> ReadAsLines(string filename)
        {
            using (StreamReader reader = new StreamReader(filename))
                while (!reader.EndOfStream)
                    yield return reader.ReadLine();
        }

How can I generate a list or array of sequential integers in Java?

With Java 8 it is so simple so it doesn't even need separate method anymore:

List<Integer> range = IntStream.rangeClosed(start, end)
    .boxed().collect(Collectors.toList());

Load HTML file into WebView

The easiest way would probably be to put your web resources into the assets folder then call:

webView.loadUrl("file:///android_asset/filename.html");

For Complete Communication between Java and Webview See This

Update: The assets folder is usually the following folder: <project>/src/main/assets This can be changed in the asset folder configuration setting in your <app>.iml file as:

<option name=”ASSETS_FOLDER_RELATIVE_PATH” value=”/src/main/assets” /> See Article Where to place the assets folder in Android Studio

Disable EditText blinking cursor

Perfect Solution that goes further to the goal

Goal: Disable the blinking curser when EditText is not in focus, and enable the blinking curser when EditText is in focus. Below also opens keyboard when EditText is clicked, and hides it when you press done in the keyboard.

1) Set in your xml under your EditText:

android:cursorVisible="false"

2) Set onClickListener:

iEditText.setOnClickListener(editTextClickListener);

OnClickListener editTextClickListener = new OnClickListener() 

{

    public void onClick(View v) 
    {
         if (v.getId() == iEditText.getId()) 
        {
            iEditText.setCursorVisible(true);
        }

    }
};

3) then onCreate, capture the event when done is pressed using OnEditorActionListener to your EditText, and then setCursorVisible(false).

//onCreate...

iEditText.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                    KeyEvent event) {
                    iEditText.setCursorVisible(false);
                if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    in.hideSoftInputFromWindow(iEditText.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return false;
            }
        });

UIButton: set image for selected-highlighted state

Swift 3

// Default state (previously `.Normal`)
button.setImage(UIImage(named: "image1"), for: [])

// Highlighted
button.setImage(UIImage(named: "image2"), for: .highlighted)

// Selected
button.setImage(UIImage(named: "image3"), for: .selected)

// Selected + Highlighted
button.setImage(UIImage(named: "image4"), for: [.selected, .highlighted])

To set the background image we can use setBackgroundImage(_:for:)

Swift 2.x

// Normal
button.setImage(UIImage(named: "image1"), forState: .Normal)

// Highlighted
button.setImage(UIImage(named: "image2"), forState: .Highlighted)

// Selected
button.setImage(UIImage(named: "image3"), forState: .Selected)

// Selected + Highlighted
button.setImage(UIImage(named: "image4"), forState: [.Selected, .Highlighted])

How to close jQuery Dialog within the dialog?

$(this).parents(".ui-dialog-content").dialog('close')

Simple, I like to make sure I don't:

  1. hardcode dialog #id values.
  2. Close all dialogs.

Run command on the Ansible host

you can try this way

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

Easy way to fill the missing values:-

filling string columns: when string columns have missing values and NaN values.

df['string column name'].fillna(df['string column name'].mode().values[0], inplace = True)

filling numeric columns: when the numeric columns have missing values and NaN values.

df['numeric column name'].fillna(df['numeric column name'].mean(), inplace = True)

filling NaN with zero:

df['column name'].fillna(0, inplace = True)

Setting CSS pseudo-class rules from JavaScript

here is a solution including two functions: addCSSclass adds a new css class to the document, and toggleClass turns it on

The example shows adding a custom scrollbar to a div

_x000D_
_x000D_
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass_x000D_
function toggleClass(elem, theClass, newState) {_x000D_
  var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');_x000D_
  var add = (arguments.length > 2 ? newState : (elem.className.match(matchRegExp) === null));_x000D_
_x000D_
  elem.className = elem.className.replace(matchRegExp, ''); // clear all_x000D_
  if (add) elem.className += ' ' + theClass;_x000D_
}_x000D_
_x000D_
function addCSSclass(rules) {_x000D_
  var style = document.createElement("style");_x000D_
  style.appendChild(document.createTextNode("")); // WebKit hack :(_x000D_
  document.head.appendChild(style);_x000D_
  var sheet = style.sheet;_x000D_
_x000D_
  rules.forEach((rule, index) => {_x000D_
    try {_x000D_
      if ("insertRule" in sheet) {_x000D_
        sheet.insertRule(rule.selector + "{" + rule.rule + "}", index);_x000D_
      } else if ("addRule" in sheet) {_x000D_
        sheet.addRule(rule.selector, rule.rule, index);_x000D_
      }_x000D_
    } catch (e) {_x000D_
      // firefox can break here          _x000D_
    }_x000D_
    _x000D_
  })_x000D_
}_x000D_
_x000D_
let div = document.getElementById('mydiv');_x000D_
addCSSclass([{_x000D_
    selector: '.narrowScrollbar::-webkit-scrollbar',_x000D_
    rule: 'width: 5px'_x000D_
  },_x000D_
  {_x000D_
    selector: '.narrowScrollbar::-webkit-scrollbar-thumb',_x000D_
    rule: 'background-color:#808080;border-radius:100px'_x000D_
  }_x000D_
]);_x000D_
toggleClass(div, 'narrowScrollbar', true);
_x000D_
<div id="mydiv" style="height:300px;width:300px;border:solid;overflow-y:scroll">_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a eros metus. Nunc dui felis, accumsan nec aliquam quis, fringilla quis tellus. Nulla cursus mauris nibh, at faucibus justo tincidunt eget. Sed sodales eget erat consectetur consectetur. Vivamus_x000D_
  a diam volutpat, ullamcorper justo eu, dignissim ante. Aenean turpis tortor, fringilla quis efficitur eleifend, iaculis id quam. Quisque non turpis in lacus finibus auctor. Morbi ullamcorper felis ut nulla venenatis fringilla. Praesent imperdiet velit_x000D_
  nec sodales sodales. Etiam eget dui sollicitudin, tempus tortor non, porta nibh. Quisque eu efficitur velit. Nulla facilisi. Sed varius a erat ac volutpat. Sed accumsan maximus feugiat. Mauris id malesuada dui. Lorem ipsum dolor sit amet, consectetur_x000D_
  adipiscing elit. Sed a eros metus. Nunc dui felis, accumsan nec aliquam quis, fringilla quis tellus. Nulla cursus mauris nibh, at faucibus justo tincidunt eget. Sed sodales eget erat consectetur consectetur. Vivamus a diam volutpat, ullamcorper justo_x000D_
  eu, dignissim ante. Aenean turpis tortor, fringilla quis efficitur eleifend, iaculis id quam. Quisque non turpis in lacus finibus auctor. Morbi ullamcorper felis ut nulla venenatis fringilla. Praesent imperdiet velit nec sodales sodales. Etiam eget_x000D_
  dui sollicitudin, tempus tortor non, porta nibh. Quisque eu efficitur velit. Nulla facilisi. Sed varius a erat ac volutpat. Sed accumsan maximus feugiat. Mauris id malesuada dui._x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the easiest way to install BLAS and LAPACK for scipy?

For windows: Best is to use pre-compiled package available from this site: http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#scipy

The name 'InitializeComponent' does not exist in the current context

yeap, so many things can be... I would add this one... make sure the App.xaml points to your Namespace (where your app file is) + .App eg. x:Class="DX.App" <=== make sure this is App and not the Main Page name

Hope this works for you too.

Center content in responsive bootstrap navbar

I think this is what you are looking for. You need to remove the float: left from the inner nav to center it and make it a inline-block.

.navbar .navbar-nav {
  display: inline-block;
  float: none;
  vertical-align: top;
}

.navbar .navbar-collapse {
  text-align: center;
}

http://jsfiddle.net/bdd9U/2/

Edit: if you only want this effect to happen when the nav isn't collapsed surround it in the appropriate media query.

@media (min-width: 768px) {
    .navbar .navbar-nav {
        display: inline-block;
        float: none;
        vertical-align: top;
    }

    .navbar .navbar-collapse {
        text-align: center;
    }
}

http://jsfiddle.net/bdd9U/3/

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

  • try to do the Telnet to see any firewall issue
  • perform tracert/traceroute to find number of hops

Javascript - get array of dates between 2 dates

var boxingDay = new Date("12/26/2010");
var nextWeek  = boxingDay*1 + 7*24*3600*1000;

function getDates( d1, d2 ){
  var oneDay = 24*3600*1000;
  for (var d=[],ms=d1*1,last=d2*1;ms<last;ms+=oneDay){
    d.push( new Date(ms) );
  }
  return d;
}

getDates( boxingDay, nextWeek ).join("\n");
// Sun Dec 26 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Mon Dec 27 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Tue Dec 28 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Wed Dec 29 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Thu Dec 30 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Fri Dec 31 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Sat Jan 01 2011 00:00:00 GMT-0700 (Mountain Standard Time)

Loop in Jade (currently known as "Pug") template engine

Pug (renamed from 'Jade') is a templating engine for full stack web app development. It provides a neat and clean syntax for writing HTML and maintains strict whitespace indentation (like Python). It has been implemented with JavaScript APIs. The language mainly supports two iteration constructs: each and while. 'for' can be used instead 'each'. Kindly consult the language reference here:

https://pugjs.org/language/iteration.html

Here is one of my snippets: each/for iteration in pug_screenshot

Use jQuery to get the file input's selected filename without the path

How about something like this?

var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);

base64 encoded images in email signatures

Important

My answer below shows how to embed images using data URIs. This is useful for the web, but will not work reliably for most email clients. For email purposes be sure to read Shadow2531's answer.


Base-64 data is legal in an img tag and I believe your question is how to properly insert such an image tag.

You can use an online tool or a few lines of code to generate the base 64 string.

The syntax to source the image from inline data is:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

http://en.wikipedia.org/wiki/Data_URI_scheme

Java: Date from unix timestamp

Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());

Maven dependencies are failing with a 501 error

I hit this problem with the latest version (August 2020) (after not using Maven on this machine for ages) and was scratching my head as to why it could still be an issue after reading these answers.

Turns out I had an old settings.xml sitting in the .m2/ folder in my home directory with some customisations from years ago.

However, even deleting that file didn't fix it for me. I ended up deleting the entire .m2 folder.
I don't think there was anything else in it except for downloaded resources. Maybe just deleting folders like repository/org/apache/maven/archetype would have been sufficient.

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

Simple insecure two-way data "obfuscation"?

I know you said you don't care about how secure it is, but if you chose DES you might as well take AES it is the more up-to-date encryption method.

Reading json files in C++

Here is another easier possibility to read in a json file:

#include "json/json.h"

std::ifstream file_input("input.json");
Json::Reader reader;
Json::Value root;
reader.parse(file_input, root);
cout << root;

You can then get the values like this:

cout << root["key"]

WebSockets vs. Server-Sent events/EventSource

According to caniuse.com:

You can use a client-only polyfill to extend support of SSE to many other browsers. This is less likely with WebSockets. Some EventSource polyfills:

If you need to support all the browsers, consider using a library like web-socket-js, SignalR or socket.io which support multiple transports such as WebSockets, SSE, Forever Frame and AJAX long polling. These often require modifications to the server side as well.

Learn more about SSE from:

Learn more about WebSockets from:

Other differences:

  • WebSockets supports arbitrary binary data, SSE only uses UTF-8

Pass C# ASP.NET array to Javascript array

You can use ClientScript.RegisterStartUpScript to inject javascript into the page on Page_Load.

Here's a link to MSDN reference: http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

Here's the code in Page_Load:

  List<string> tempString = new List<string>();
  tempString.Add("Hello");
  tempString.Add("World");

  StringBuilder sb = new StringBuilder();
  sb.Append("<script>");
  sb.Append("var testArray = new Array;");
  foreach(string str in tempString)
  {
    sb.Append("testArray.push('" + str + "');");
  }
  sb.Append("</script>");

  ClientScript.RegisterStartupScript(this.GetType(), "TestArrayScript", sb.ToString());

Notes: Use StringBuilder to build the script string as it will probably be long.

And here's the Javascript that checks for the injected array "testArray" before you can work with it:

if (testArray)
{
  // do something with testArray
}

There's 2 problems here:

  1. Some consider this intrusive for C# to inject Javascript

  2. We'll have to declare the array at a global context

If you can't live with that, another way would be to have the C# code save the Array into View State, then have the JavaScript use PageMethods (or web services) to call back to the server to get that View State object as an array. But I think that may be overkill for something like this.