Programs & Examples On #Embedded jetty

Jetty is a widely used web container (server) written in Java and produced by Eclipse.

How does OkHttp get Json string?

As I observed in my code. If once the value is fetched of body from Response, its become blank.

String str = response.body().string();  // {response:[]}

String str1  = response.body().string();  // BLANK

So I believe after fetching once the value from body, it become empty.

Suggestion : Store it in String, that can be used many time.

How do I check if a string is a number (float)?

In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the isdigit() function for string objects.

>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False

String Methods - isdigit(): Python2, Python3

There's also something on Unicode strings, which I'm not too familiar with Unicode - Is decimal/decimal

How to install xgboost in Anaconda Python (Windows platform)?

I'm able to install using the following commands (in Windows 10) :

conda install -c mikesilva xgboost

conda install -c conda-forge xgboost

When to use EntityManager.find() vs EntityManager.getReference() with JPA

I disagree with the selected answer, and as davidxxx correctly pointed out, getReference does not provide such behaviour of dynamic updations without select. I asked a question concerning the validity of this answer, see here - cannot update without issuing select on using setter after getReference() of hibernate JPA.

I quite honestly haven't seen anybody who's actually used that functionality. ANYWHERE. And i don't understand why it's so upvoted.

Now first of all, no matter what you call on a hibernate proxy object, a setter or a getter, an SQL is fired and the object is loaded.

But then i thought, so what if JPA getReference() proxy doesn't provide that functionality. I can just write my own proxy.

Now, we can all argue that selects on primary keys are as fast as a query can get and it's not really something to go to great lengths to avoid. But for those of us who can't handle it due to one reason or another, below is an implementation of such a proxy. But before i you see the implementation, see it's usage and how simple it is to use.

USAGE

Order example = ProxyHandler.getReference(Order.class, 3);
example.setType("ABCD");
example.setCost(10);
PersistenceService.save(example);

And this would fire the following query -

UPDATE Order SET type = 'ABCD' and cost = 10 WHERE id = 3;

and even if you want to insert, you can still do PersistenceService.save(new Order("a", 2)); and it would fire an insert as it should.

IMPLEMENTATION

Add this to your pom.xml -

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.10</version>
</dependency>

Make this class to create dynamic proxy -

@SuppressWarnings("unchecked")
public class ProxyHandler {

public static <T> T getReference(Class<T> classType, Object id) {
    if (!classType.isAnnotationPresent(Entity.class)) {
        throw new ProxyInstantiationException("This is not an entity!");
    }

    try {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(classType);
        enhancer.setCallback(new ProxyMethodInterceptor(classType, id));
        enhancer.setInterfaces((new Class<?>[]{EnhancedProxy.class}));
        return (T) enhancer.create();
    } catch (Exception e) {
        throw new ProxyInstantiationException("Error creating proxy, cause :" + e.getCause());
    }
}

Make an interface with all the methods -

public interface EnhancedProxy {
    public String getJPQLUpdate();
    public HashMap<String, Object> getModifiedFields();
}

Now, make an interceptor which will allow you to implement these methods on your proxy -

import com.anil.app.exception.ProxyInstantiationException;
import javafx.util.Pair;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.persistence.Id;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Anil Kumar
*/
public class ProxyMethodInterceptor implements MethodInterceptor, EnhancedProxy {

private Object target;
private Object proxy;
private Class classType;
private Pair<String, Object> primaryKey;
private static HashSet<String> enhancedMethods;

ProxyMethodInterceptor(Class classType, Object id) throws IllegalAccessException, InstantiationException {
    this.classType = classType;
    this.target = classType.newInstance();
    this.primaryKey = new Pair<>(getPrimaryKeyField().getName(), id);
}

static {
    enhancedMethods = new HashSet<>();
    for (Method method : EnhancedProxy.class.getDeclaredMethods()) {
        enhancedMethods.add(method.getName());
    }
}

@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    //intercept enhanced methods
    if (enhancedMethods.contains(method.getName())) {
        this.proxy = obj;
        return method.invoke(this, args);
    }
    //else invoke super class method
    else
        return proxy.invokeSuper(obj, args);
}

@Override
public HashMap<String, Object> getModifiedFields() {
    HashMap<String, Object> modifiedFields = new HashMap<>();
    try {
        for (Field field : classType.getDeclaredFields()) {

            field.setAccessible(true);

            Object initialValue = field.get(target);
            Object finalValue = field.get(proxy);

            //put if modified
            if (!Objects.equals(initialValue, finalValue)) {
                modifiedFields.put(field.getName(), finalValue);
            }
        }
    } catch (Exception e) {
        return null;
    }
    return modifiedFields;
}

@Override
public String getJPQLUpdate() {
    HashMap<String, Object> modifiedFields = getModifiedFields();
    if (modifiedFields == null || modifiedFields.isEmpty()) {
        return null;
    }
    StringBuilder fieldsToSet = new StringBuilder();
    for (String field : modifiedFields.keySet()) {
        fieldsToSet.append(field).append(" = :").append(field).append(" and ");
    }
    fieldsToSet.setLength(fieldsToSet.length() - 4);
    return "UPDATE "
            + classType.getSimpleName()
            + " SET "
            + fieldsToSet
            + "WHERE "
            + primaryKey.getKey() + " = " + primaryKey.getValue();
}

private Field getPrimaryKeyField() throws ProxyInstantiationException {
    for (Field field : classType.getDeclaredFields()) {
        field.setAccessible(true);
        if (field.isAnnotationPresent(Id.class))
            return field;
    }
    throw new ProxyInstantiationException("Entity class doesn't have a primary key!");
}
}

And the exception class -

public class ProxyInstantiationException extends RuntimeException {
public ProxyInstantiationException(String message) {
    super(message);
}

A service to save using this proxy -

@Service
public class PersistenceService {

@PersistenceContext
private EntityManager em;

@Transactional
private void save(Object entity) {
    // update entity for proxies
    if (entity instanceof EnhancedProxy) {
        EnhancedProxy proxy = (EnhancedProxy) entity;
        Query updateQuery = em.createQuery(proxy.getJPQLUpdate());
        for (Entry<String, Object> entry : proxy.getModifiedFields().entrySet()) {
            updateQuery.setParameter(entry.getKey(), entry.getValue());
        }
        updateQuery.executeUpdate();
    // insert otherwise
    } else {
        em.persist(entity);
    }

}
}

Flutter does not find android sdk

export ANDROID_HOME=/usr/local/share/android-sdk/tools/bin
export PATH=$PATH:/usr/local/share/android-sdk/tools/bin

Converting an integer to a hexadecimal string in Ruby

How about using %/sprintf:

i = 20
"%x" % i  #=> "14"

OR condition in Regex

Try

\d \w |\d

or add a positive lookahead if you don't want to include the trailing space in the match

\d \w(?= )|\d

When you have two alternatives where one is an extension of the other, put the longer one first, otherwise it will have no opportunity to be matched.

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Sometimes this option throws NullPointerException

ActionBar actionbar = getActionBar(); actionbar.setBackgroundDrawable(new ColorDrawable("color"));

But this option is worked for me. So you can try this.

getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFFFF")));

Happy Coding

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

Capturing count from an SQL query

int count = 0;    
using (new SqlConnection connection = new SqlConnection("connectionString"))
{
    sqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection);
    connection.Open();
    count = (int32)cmd.ExecuteScalar();
}

Mockito How to mock and assert a thrown exception?

Use Mockito's doThrow and then catch the desired exception to assert it was thrown later.

@Test
public void fooShouldThrowMyException() {
    // given
    val myClass = new MyClass();
    val arg = mock(MyArgument.class);
    doThrow(MyException.class).when(arg).argMethod(any());
    Exception exception = null;

    // when
    try {
        myClass.foo(arg);
    } catch (MyException t) {
        exception = t;
    }

    // then
    assertNotNull(exception);
}

Text Progress Bar in the Console

https://pypi.python.org/pypi/progressbar2/3.30.2

Progressbar2 is a good library for ascii base progressbar for the command line import time import progressbar

bar = progressbar.ProgressBar()
for i in bar(range(100)):
    time.sleep(0.02)
bar.finish()

https://pypi.python.org/pypi/tqdm

tqdm is a alternative of progressbar2 and i think it use in pip3 but i am not sure of that

from tqdm import tqdm
for i in tqdm(range(10000)):
...

JavaScript equivalent to printf/String.Format

Current JavaScript

From ES6 on you could use template strings:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!

See Kim's answer below for details.


Older answer

Try sprintf() for JavaScript.


If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.

Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

"{0}{1}".format("{1}", "{0}")

Normally you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneously replacement instead like in fearphage’s suggestion.

How do I set a program to launch at startup

Add an app to run automatically at startup in Windows 10

Step 1: Select the Windows Start button and scroll to find the app you want to run at startup.

Step 2: Right-click the app, select More, and then select Open file location. This opens the location where the shortcut to the app is saved. If there isn't an option for Open file location, it means the app can't run at startup.

Step 3: With the file location open, press the Windows logo key + R, type shell:startup, then select OK. This opens the Startup folder.

Step 4: Copy and paste the shortcut to the app from the file location to the Startup folder.

CSS change button style after click

An easy way of doing this is to use JavaScript like so:

element.addEventListener('click', (e => {
    e.preventDefault();

    element.style = '<insert CSS here as you would in a style attribute>';
}));

How do I see which version of Swift I'm using?

By just entering swift command in the terminal, it will show the version, while logging to Swift console.(something like below)

System-IOSs-MacBook-Air:~ system$ swift
Welcome to Apple Swift version 5.1 (swiftlang-1100.0.270.13 clang-1100.0.33.7).
Type :help for assistance.

How to remove a variable from a PHP session array

Simply use this method.

<?php
    $_SESSION['foo'] = 'bar'; // set session 
    print $_SESSION['foo']; //print it
    unset($_SESSION['foo']); //unset session 
?>

Removing page title and date when printing web page (with CSS?)

Try this;

@media print{ @page { margin-top: 30px; margin-bottom: 30px;}}

grep exclude multiple strings

Another option is to create a exclude list, this is particulary usefull when you have a long list of things to exclude.

vi /root/scripts/exclude_list.txt

Now add what you would like to exclude

Nopaging the limit is
keyword to remove is

Now use grep to remove lines from your file log file and view information not excluded.

grep -v -f /root/scripts/exclude_list.txt /var/log/admin.log

Send POST request using NSURLSession

You could try using a NSDictionary for the params. The following will send the parameters correctly to a JSON server.

NSError *error;

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
                     @"IOS TYPE", @"typemap",
                     nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];


NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

}];

[postDataTask resume];

Hope this helps (I'm trying to sort a CSRF authenticity issue with the above - but it does send the params in the NSDictionary).

passing form data to another HTML page

You need the get the values from the query string (since you dont have a method set, your using GET by default)

use the following tutorial.

http://papermashup.com/read-url-get-variables-withjavascript/

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

jQuery equivalent to Prototype array.last()

For arrays, you could simply retrieve the last element position with array.length - 1:

var a = [1,2,3,4];

var lastEl = a[a.length-1]; // 4

In jQuery you have the :last selector, but this won't help you on plain arrays.

How to change the JDK for a Jenkins job?

If you have a multi-config (matrix) job, you do not have a JDK dropdown but need to configure the jdk as build axis.

Set the intervals of x-axis using r

You can use axis:

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

That is, something like this:

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

How to fire an event when v-model changes?

Just to add to the correct answer above, in Vue.JS v1.0 you can write

<a v-on:click="doSomething">

So in this example it would be

 v-on:change="foo"

See: http://v1.vuejs.org/guide/syntax.html#Arguments

On Selenium WebDriver how to get Text from Span Tag

Pythonic way to get text from Span tags:

driver.find_element_by_xpath("//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel clear')]").text

Angular2 Routing with Hashtag to page anchor

if it does not matter to have those element ids appended to the url, you should consider taking a look at this link:

Angular 2 - Anchor Links to Element on Current Page

_x000D_
_x000D_
// html_x000D_
// add (click) event on element_x000D_
<a (click)="scroll({{any-element-id}})">Scroll</a>_x000D_
_x000D_
// in ts file, do this_x000D_
scroll(sectionId) {_x000D_
let element = document.getElementById(sectionId);_x000D_
_x000D_
  if(element) {_x000D_
    element.scrollIntoView(); // scroll to a particular element_x000D_
  }_x000D_
 }
_x000D_
_x000D_
_x000D_

A weighted version of random.choice

If you have a weighted dictionary instead of a list you can write this

items = { "a": 10, "b": 5, "c": 1 } 
random.choice([k for k in items for dummy in range(items[k])])

Note that [k for k in items for dummy in range(items[k])] produces this list ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'b', 'b', 'b', 'b', 'b']

What is Node.js' Connect, Express and "middleware"?

[Update: As of its 4.0 release, Express no longer uses Connect. However, Express is still compatible with middleware written for Connect. My original answer is below.]

I'm glad you asked about this, because it's definitely a common point of confusion for folks looking at Node.js. Here's my best shot at explaining it:

  • Node.js itself offers an http module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.

  • Connect also offers a createServer method, which returns an object that inherits an extended version of http.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.

  • Express does to Connect what Connect does to the http module: It offers a createServer method that extends Connect's Server prototype. So all of the functionality of Connect is there, plus view rendering and a handy DSL for describing routes. Ruby's Sinatra is a good analogy.

  • Then there are other frameworks that go even further and extend Express! Zappa, for instance, which integrates support for CoffeeScript, server-side jQuery, and testing.

Here's a concrete example of what's meant by "middleware": Out of the box, none of the above serves static files for you. But just throw in connect.static (a middleware that comes with Connect), configured to point to a directory, and your server will provide access to the files in that directory. Note that Express provides Connect's middlewares also; express.static is the same as connect.static. (Both were known as staticProvider until recently.)

My impression is that most "real" Node.js apps are being developed with Express these days; the features it adds are extremely useful, and all of the lower-level functionality is still there if you want it.

How can I label points in this scatterplot?

I have tried directlabels package for putting text labels. In the case of scatter plots it's not still perfect, but much better than manually adjusting the positions, specially in the cases that you are preparing the draft plots and not the final one - so you need to change and make plot again and again -.

Merging two images in C#/.NET

basically i use this in one of our apps: we want to overlay a playicon over a frame of a video:

Image playbutton;
try
{
    playbutton = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

Image frame;
try
{
    frame = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

using (frame)
{
    using (var bitmap = new Bitmap(width, height))
    {
        using (var canvas = Graphics.FromImage(bitmap))
        {
            canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            canvas.DrawImage(frame,
                             new Rectangle(0,
                                           0,
                                           width,
                                           height),
                             new Rectangle(0,
                                           0,
                                           frame.Width,
                                           frame.Height),
                             GraphicsUnit.Pixel);
            canvas.DrawImage(playbutton,
                             (bitmap.Width / 2) - (playbutton.Width / 2),
                             (bitmap.Height / 2) - (playbutton.Height / 2));
            canvas.Save();
        }
        try
        {
            bitmap.Save(/*somekindofpath*/,
                        System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception ex) { }
    }
}

JavaScript Array splice vs slice

splice() changes the original array whereas slice() doesn't but both of them returns array object.

See the examples below:

var array=[1,2,3,4,5];
console.log(array.splice(2));

This will return [3,4,5]. The original array is affected resulting in array being [1,2].

var array=[1,2,3,4,5]
console.log(array.slice(2));

This will return [3,4,5]. The original array is NOT affected with resulting in array being [1,2,3,4,5].

Below is simple fiddle which confirms this:

_x000D_
_x000D_
//splice_x000D_
var array=[1,2,3,4,5];_x000D_
console.log(array.splice(2));_x000D_
_x000D_
//slice_x000D_
var array2=[1,2,3,4,5]_x000D_
console.log(array2.slice(2));_x000D_
_x000D_
_x000D_
console.log("----after-----");_x000D_
console.log(array);_x000D_
console.log(array2);
_x000D_
_x000D_
_x000D_

justify-content property isn't working

justify-content only has an effect if there's space left over after your flex items have flexed to absorb the free space. In most/many cases, there won't be any free space left, and indeed justify-content will do nothing.

Some examples where it would have an effect:

  • if your flex items are all inflexible (flex: none or flex: 0 0 auto), and smaller than the container.

  • if your flex items are flexible, BUT can't grow to absorb all the free space, due to a max-width on each of the flexible items.

In both of those cases, justify-content would be in charge of distributing the excess space.

In your example, though, you have flex items that have flex: 1 or flex: 6 with no max-width limitation. Your flexible items will grow to absorb all of the free space, and there will be no space left for justify-content to do anything with.

Converting xml to string using C#

There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

Convert from ASCII string encoded in Hex to plain ASCII?

Tested in Python 3.3.2 There are many ways to accomplish this, here's one of the shortest, using only python-provided stuff:

import base64
hex_data ='57696C6C20796F7520636F6E76657274207468697320484558205468696E6720696E746F20415343494920666F72206D653F2E202E202E202E506C656565656173652E2E2E212121'
ascii_string = str(base64.b16decode(hex_data))[2:-1]
print (ascii_string)

Of course, if you don't want to import anything, you can always write your own code. Something very basic like this:

ascii_string = ''
x = 0
y = 2
l = len(hex_data)
while y <= l:
    ascii_string += chr(int(hex_data[x:y], 16))
    x += 2
    y += 2
print (ascii_string)

Remove the last three characters from a string

I read through all these, but wanted something a bit more elegant. Just to remove a certain number of characters from the end of a string:

string.Concat("hello".Reverse().Skip(3).Reverse());

output:

"he"

Datatable to html Table

The first answer is correct, but if you have a large amount of data (in my project I had 8.000 rows * 8 columns) is tragically slow.... Having a string that becomes that large in c# is why that solution is forbiden

Instead using a large string I used a string array that I join at the end in order to return the string of the html table. Moreover, I used a linq expression ((from o in row.ItemArray select o.ToString()).ToArray()) in order to join each DataRow of the table, instead of looping again, in order to save as much time as possible.

This is my sample code:

private string MakeHtmlTable(DataTable data)
{
            string[] table = new string[data.Rows.Count] ;
            long counter = 1;
            foreach (DataRow row in data.Rows)
            {
                table[counter-1] = "<tr><td>" + String.Join("</td><td>", (from o in row.ItemArray select o.ToString()).ToArray()) + "</td></tr>";

                counter+=1;
            }

            return "</br><table>" + String.Join("", table) + "</table>";
}

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

Getting time span between two times in C#?

string startTime = "7:00 AM";
string endTime = "2:00 PM";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Will output: 07:00:00.

It also works if the user input military time:

string startTime = "7:00";
string endTime = "14:00";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Outputs: 07:00:00.

To change the format: duration.ToString(@"hh\:mm")

More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx

Addendum:

Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".

Get DataKey values in GridView RowCommand

I usually pass the RowIndex via CommandArgument and use it to retrieve the DataKey value I want.

On the Button:

CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'

On the Server Event

int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["myKey"];

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

You can use javax.xml.bind.DatatypeConverter class

DatatypeConverter.printDateTime & DatatypeConverter.parseDateTime

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

I had this error when I tried to update npm, but had a really old version (1.3.6 !) installed from yum in AWS Linux. I was able to manually install a newer npm version and everything was remedied.

How to remove and clear all localStorage data

If you want to remove/clean all the values from local storage than use

localStorage.clear();

And if you want to remove the specific item from local storage than use the following code

localStorage.removeItem(key);

Force drop mysql bypassing foreign key constraint

If you are using phpmyadmin then this feature is already there.

  • Select the tables you want to drop
  • From the dropdown at the bottom of tables list, select drop
  • A new page will be opened having checkbox at the bottom saying "Foreign key check", uncheck it.
  • Confirm the deletion by accepting "yes".

Set background image in CSS using jquery

You have to remove the semicolon in the css rule string:

$(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");

Assigning strings to arrays of characters

There is no such thing as a "string" in C. In C, strings are one-dimensional array of char, terminated by a null character \0. Since you can't assign arrays in C, you can't assign strings either. The literal "hello" is syntactic sugar for const char x[] = {'h','e','l','l','o','\0'};

The correct way would be:

char s[100];
strncpy(s, "hello", 100);

or better yet:

#define STRMAX 100
char    s[STRMAX];
size_t  len;
len = strncpy(s, "hello", STRMAX);

How to dynamically load a Python class

Here is to share something I found on __import__ and importlib while trying to solve this problem.

I am using Python 3.7.3.

When I try to get to the class d in module a.b.c,

mod = __import__('a.b.c')

The mod variable refer to the top namespace a.

So to get to the class d, I need to

mod = getattr(mod, 'b') #mod is now module b
mod = getattr(mod, 'c') #mod is now module c
mod = getattr(mod, 'd') #mod is now class d

If we try to do

mod = __import__('a.b.c')
d = getattr(mod, 'd')

we are actually trying to look for a.d.

When using importlib, I suppose the library has done the recursive getattr for us. So, when we use importlib.import_module, we actually get a handle on the deepest module.

mod = importlib.import_module('a.b.c') #mod is module c
d = getattr(mod, 'd') #this is a.b.c.d

Add item to array in VBScript

For your copy and paste ease

' add item to array
Function AddItem(arr, val)
    ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr)) = val
    AddItem = arr
End Function

Used like so

a = Array()
a = AddItem(a, 5)
a = AddItem(a, "foo")

Android device does not show up in adb list

In your windows configuration, go to device management. Check if you see your device and if the drivers are installed. You probably do not have the correct drivers installed for your device.

ImportError: DLL load failed: %1 is not a valid Win32 application

You could try installing the 32 bit version of opencv

Forcing a postback

Here the solution from http://forums.asp.net/t/928411.aspx/1 as mentioned by mamoo - just in case the website goes offline. Worked well for me.

StringBuilder sbScript = new StringBuilder();

sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
sbScript.Append("<!--\n");
sbScript.Append(this.GetPostBackEventReference(this, "PBArg") + ";\n");
sbScript.Append("// -->\n");
sbScript.Append("</script>\n");

this.RegisterStartupScript("AutoPostBackScript", sbScript.ToString());

JQuery Number Formatting

I wrote a JavaScript analogue of a PHP function number_format on a base of Abe Miessler addCommas function. Could be usefull.

number_format = function (number, decimals, dec_point, thousands_sep) {
        number = number.toFixed(decimals);

        var nstr = number.toString();
        nstr += '';
        x = nstr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? dec_point + x[1] : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

        return x1 + x2;
    }

For example:

var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

I won't stress much on the difference as it is already covered, but notice the below:

  • android:backgroundTint android:backgroundTintMode are only available at API 21
  • If you have a widget that has a png/vector drawable background set by android:background, and you want to change its default color, then you can use android:backgroundTint to add a shade to it.

example

<Button
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:background="@android:drawable/ic_dialog_email" />

enter image description here

<Button
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:background="@android:drawable/ic_dialog_email"
    android:backgroundTint="@color/colorAccent" />

enter image description here

Another example

If you try to change the accent color of the FloatingActionButton using android:background you won't notice a change, that is because it's already utilizes app:srcCompat, so in order to do that you can use android:backgroundTint instead

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

Wait for shell command to complete

Add the following Sub:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
VBA.CreateObject("WScript.Shell").Run Cmd, WindowStyle, True
End Sub

If you add a reference to C:\Windows\system32\wshom.ocx you can also use:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
Static wsh As New WshShell
wsh.Run Cmd, WindowStyle, True
End Sub

This version should be more efficient.

How to create circular ProgressBar in android?

It's easy to create this yourself

In your layout include the following ProgressBar with a specific drawable (note you should get the width from dimensions instead). The max value is important here:

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:max="500"
    android:progress="0"
    android:progressDrawable="@drawable/circular" />

Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius instead of innerRadiusRatio) and thickness values.

circular (Pre Lollipop OR API Level < 21)

   <shape
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
   </shape>

circular ( >= Lollipop OR API Level >= 21)

    <shape
        android:useLevel="true"
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
     </shape>

useLevel is "false" by default in API Level 21 (Lollipop) .

Start Animation

Next in your code use an ObjectAnimator to animate the progress field of the ProgessBar of your layout.

ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();

Stop Animation

progressBar.clearAnimation();

P.S. unlike examples above, it give smooth animation.

Getting files by creation date in .NET

@jing: "The DirectoryInfo solution is much faster then this (especially for network path)"

I cant confirm this. It seems as if Directory.GetFiles triggers a filesystem or network cache. The first request takes a while, but the following requests are much faster, even if new files were added. In my test I did a Directory.getfiles and a info.GetFiles with the same patterns and both run equally

GetFiles  done 437834 in00:00:20.4812480
process files  done 437834 in00:00:00.9300573
GetFiles by Dirinfo(2)  done 437834 in00:00:20.7412646

How can I explicitly free memory in Python?

As other answers already say, Python can keep from releasing memory to the OS even if it's no longer in use by Python code (so gc.collect() doesn't free anything) especially in a long-running program. Anyway if you're on Linux you can try to release memory by invoking directly the libc function malloc_trim (man page). Something like:

import ctypes
libc = ctypes.CDLL("libc.so.6")
libc.malloc_trim(0)

Load HTML File Contents to Div [without the use of iframes]

Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.

var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState!==4) return;
    if (this.status!==200) return; // or whatever error handling you want
    document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();

If you need IE<8 compatibility, do this first to bring those browsers up to speed:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    };
}

Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.

How to include !important in jquery

If you really need to override css that has !important rules in it, for instance, in a case I ran into recently, overriding a wordpress theme required !important scss rules to break the theme, but since I was transpiling my code with webpack and (I assume this is why --)my css came along in the chain after the transpiled javascript, you can add a separate class rule in your stylesheet that overrides the first !important rule in the cascade, and toggle the heavier-weighted class rather than adjusting css dynamically. Just a thought.

How to make the Facebook Like Box responsive?

Colin's example for me clashed with the like button. So I adapted it to only target the Like Box.

.fb-like-box, .fb-like-box span, .fb-like-box span iframe[style] { width: 100% !important; }

Tested in most modern browsers.

How to read an http input stream

a complete code for reading from a webservice in two ways

public void buttonclick(View view) {
    // the name of your webservice where reactance is your method
    new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance");
}

public class GetMethodDemo extends AsyncTask<String, Void, String> {
    //see also: 
    // https://developer.android.com/reference/java/net/HttpURLConnection.html
    //writing to see:    https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
    String server_response;
    @Override
    protected String doInBackground(String... strings) {
        URL url;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
            in.close();
            Log.v("bufferv ", server_response);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.e("Response", "" + server_response);
   //assume there is a field with id editText
        EditText editText = (EditText) findViewById(R.id.editText);
        editText.setText(server_response);
    }
}

What are access specifiers? Should I inherit with private, protected or public?

what are Access Specifiers?

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

int main()
{
    MyClass obj;
    obj.a = 10;     //Allowed
    obj.b = 20;     //Not Allowed, gives compiler error
    obj.c = 30;     //Not Allowed, gives compiler error
}

Inheritance and Access Specifiers

Inheritance in C++ can be one of the following types:

  • Private Inheritance
  • Public Inheritance
  • Protected inheritance

Here are the member access rules with respect to each of these:

First and most important rule Private members of a class are never accessible from anywhere except the members of the same class.

Public Inheritance:

All Public members of the Base Class become Public Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.

Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:public Base
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Allowed
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Private Inheritance:

All Public members of the Base Class become Private Members of the Derived class &
All Protected members of the Base Class become Private Members of the Derived Class.

An code Example:

Class Base
{
    public:
      int a;
    protected:
      int b;
    private:
      int c;
};

class Derived:private Base   //Not mentioning private is OK because for classes it  defaults to private 
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Not Allowed, Compiler Error, a is private member of Derived now
        b = 20;  //Not Allowed, Compiler Error, b is private member of Derived now
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Protected Inheritance:

All Public members of the Base Class become Protected Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

A Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:protected Base  
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
        b = 20;  //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error
}

Remember the same access rules apply to the classes and members down the inheritance hierarchy.


Important points to note:

- Access Specification is per-Class not per-Object

Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.

- A Derived class can only access members of its own Base class

Consider the following code example:

class Myclass
{ 
    protected: 
       int x; 
}; 

class derived : public Myclass
{
    public: 
        void f( Myclass& obj ) 
        { 
            obj.x = 5; 
        } 
};

int main()
{
    return 0;
}

It gives an compilation error:

prog.cpp:4: error: ‘int Myclass::x’ is protected

Because the derived class can only access members of its own Base Class. Note that the object obj being passed here is no way related to the derived class function in which it is being accessed, it is an altogether different object and hence derived member function cannot access its members.


What is a friend? How does friend affect access specification rules?

You can declare a function or class as friend of another class. When you do so the access specification rules do not apply to the friended class/function. The class or function can access all the members of that particular class.

So do friends break Encapsulation?

No they don't, On the contrary they enhance Encapsulation!

friendship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friendship.

Redirect to Action in another controller

This should work

return RedirectToAction("actionName", "controllerName", null);

Can I recover a branch after its deletion in Git?

I rebased a branch from remote to try to clear a few commits I didn't want and was going to cherrypick the right ones that I wanted. Of course I wrote the SHAs wrong...

Here is how I found them (mostly an easier interface/interaction from things on answers here):

First, generate a list of loose commits in your log. Do this as soon as possible and stop working, as those may be dumped by the garbage collector.

git fsck --full --no-reflogs --unreachable --lost-found > lost

This creates a lost file with all the commits you will have to look at. To simplify our life, let's cut only the SHA from it:

cat lost | cut -d\  -f3 > commits

Now you have a commits file with all the commits you have to look.

Assuming you are using Bash, the final step:

for c in `cat commits`; do  git show $c; read; done

This will show you the diff and commit information for each of them. And wait for you to press Enter. Now write down all the ones you want, and then cherry-pick them in. After you are done, just Ctrl-C it.

Set a button background image iPhone programmatically

In one line we can set image with this code

[buttonName setBackgroundImage:[UIImage imageNamed:@"imageName"] forState:UIControlStateNormal];

How to copy and paste worksheets between Excel workbooks?

You can also do this without any code at all. If you right-click on the little sheet tab at the bottom of the sheet, and select "Move or Copy", you will get a dialog box that lets you choose which open workbook to transfer the sheet to.

See this link for more detailed instructions and screenshots.

How do I center content in a div using CSS?

To align horizontally it's pretty straight forward:

    <style type="text/css"> 
body  {
    margin: 0; 
    padding: 0;
    text-align: center;
}
.bodyclass #container { 
    width: ???px; /*SET your width here*/
    margin: 0 auto;
    text-align: left;
} 
</style>
<body class="bodyclass ">
<div id="container">type your content here</div>
</body>

and for vertical align, it's a bit tricky: here's the source

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>Universal vertical center with CSS</title>
  <style>
    .greenBorder {border: 1px solid green;} /* just borders to see it */
  </style>
</head>

<body>
  <div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;">
    <div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
      <div class="greenBorder" style=" #position: relative; #top: -50%">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
      </div>
    </div>
  </div>
</body>
</html>

Java: Converting String to and from ByteBuffer and associated problems

Unless things have changed, you're better off with

public static ByteBuffer str_to_bb(String msg, Charset charset){
    return ByteBuffer.wrap(msg.getBytes(charset));
}

public static String bb_to_str(ByteBuffer buffer, Charset charset){
    byte[] bytes;
    if(buffer.hasArray()) {
        bytes = buffer.array();
    } else {
        bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
    }
    return new String(bytes, charset);
}

Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.

What's the best UI for entering date of birth?

I would suggest using a drop down menu for each field, making sure to label each as day, month and year. A date picker might also help, but if the user doesn't have JavaScript enabled, it won't work.

Missing .map resource?

jQuery recently started using source maps.

For example, let's look at the minified jQuery 2.0.3 file's first few lines.

/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/

Excerpt from Introduction to JavaScript Source Maps:

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.

emphasis mine

It's incredibly useful, and will only download if the user opens dev tools.

Solution

Remove the source mapping line, or do nothing. It isn't really a problem.


Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

Moving Average Pandas

To get the moving average in pandas we can use cum_sum and then divide by count.

Here is the working example:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': range(5),
                   'value': range(100,600,100)})

# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']

# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()

print(df)

output

   id  value  cum_sum  count  mov_avg     rolling_mean2
0   0    100      100      1    100.0           NaN
1   1    200      300      2    150.0           150.0
2   2    300      600      3    200.0           250.0
3   3    400     1000      4    250.0           350.0
4   4    500     1500      5    300.0           450.0

GetType used in PowerShell, difference between variables

Select-Object returns a custom PSObject with just the properties specified. Even with a single property, you don't get the ACTUAL variable; it is wrapped inside the PSObject.

Instead, do:

Get-Date | Select-Object -ExpandProperty DayOfWeek

That will get you the same result as:

(Get-Date).DayOfWeek

The difference is that if Get-Date returns multiple objects, the pipeline way works better than the parenthetical way as (Get-ChildItem), for example, is an array of items. This has changed in PowerShell v3 and (Get-ChildItem).FullPath works as expected and returns an array of just the full paths.

Accessing Imap in C#

I haven't tried it myself, but this is a free library you could try (I not so sure about the SSL part on this one):

http://www.codeproject.com/KB/IP/imaplibrary.aspx

Also, there is xemail, which has parameters for SSL:

http://xemail-net.sourceforge.net/

[EDIT] If you (or the client) have the money for a professional mail-client, this thread has some good recommendations:

Recommendations for a .NET component to access an email inbox

Turn a simple socket into an SSL socket

There are several steps when using OpenSSL. You must have an SSL certificate made which can contain the certificate with the private key be sure to specify the exact location of the certificate (this example has it in the root). There are a lot of good tutorials out there.

Some includes:

#include <openssl/applink.c>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

You will need to initialize OpenSSL:

void InitializeSSL()
{
    SSL_load_error_strings();
    SSL_library_init();
    OpenSSL_add_all_algorithms();
}

void DestroySSL()
{
    ERR_free_strings();
    EVP_cleanup();
}

void ShutdownSSL()
{
    SSL_shutdown(cSSL);
    SSL_free(cSSL);
}

Now for the bulk of the functionality. You may want to add a while loop on connections.

int sockfd, newsockfd;
SSL_CTX *sslctx;
SSL *cSSL;

InitializeSSL();
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd< 0)
{
    //Log and Error
    return;
}
struct sockaddr_in saiServerAddress;
bzero((char *) &saiServerAddress, sizeof(saiServerAddress));
saiServerAddress.sin_family = AF_INET;
saiServerAddress.sin_addr.s_addr = serv_addr;
saiServerAddress.sin_port = htons(aPortNumber);

bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

listen(sockfd,5);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

sslctx = SSL_CTX_new( SSLv23_server_method());
SSL_CTX_set_options(sslctx, SSL_OP_SINGLE_DH_USE);
int use_cert = SSL_CTX_use_certificate_file(sslctx, "/serverCertificate.pem" , SSL_FILETYPE_PEM);

int use_prv = SSL_CTX_use_PrivateKey_file(sslctx, "/serverCertificate.pem", SSL_FILETYPE_PEM);

cSSL = SSL_new(sslctx);
SSL_set_fd(cSSL, newsockfd );
//Here is the SSL Accept portion.  Now all reads and writes must use SSL
ssl_err = SSL_accept(cSSL);
if(ssl_err <= 0)
{
    //Error occurred, log and close down ssl
    ShutdownSSL();
}

You are then able read or write using:

SSL_read(cSSL, (char *)charBuffer, nBytesToRead);
SSL_write(cSSL, "Hi :3\n", 6);

Update The SSL_CTX_new should be called with the TLS method that best fits your needs in order to support the newer versions of security, instead of SSLv23_server_method(). See: OpenSSL SSL_CTX_new description

TLS_method(), TLS_server_method(), TLS_client_method(). These are the general-purpose version-flexible SSL/TLS methods. The actual protocol version used will be negotiated to the highest version mutually supported by the client and the server. The supported protocols are SSLv3, TLSv1, TLSv1.1, TLSv1.2 and TLSv1.3.

What's the regular expression that matches a square bracket?

If you want to match an expression starting with [ and ending with ], use \[[^\]]*\].

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

If you don't want any decimals when the resulting decimals are all zeroes, something like this would work:

String fixedDecimals(double d, int decimals, {bool removeZeroDecimals = true}){
  double mod = pow(10.0, decimals);
  double result = ((d * mod).round().toDouble() / mod);
  if( removeZeroDecimals && result - (result.truncate()) == 0.0 ) decimals = 0;
  return result.toStringAsFixed(decimals);
}

This will simply output 9 instead of 9.00 if the input is 9.004 and you want 2 decimals.

Difference between checkout and export in SVN

Any chance the build process is looking into the subdirectories and including something it shouldn't? BTW, you can do a legal checkout, then remove the .svn and all it contains. That should give you the same as an export. Try compiling that, before and after removing the metadata, as it were.

Concatenating Column Values into a Comma-Separated List

If you are running on SQL Server 2017 or Azure SQL Database you do something like this :

 SELECT STRING_AGG(CarName,',') as CarNames
 FROM CARS 

Android Studio not showing modules in project structure

Here's what I did to solve this problem

  • Close Android Studio
  • Quick Start -> Check out from Version Control

How to use confirm using sweet alert?

100% working

Do some little trick using attribute. In your form add an attribute like data-flag in your form, assign "0" as false.

<form id="from1" data-flag="0">
    //your inputs
</form>

In your javascript:

document.querySelector('#from1').onsubmit = function(e){

    $flag = $(this).attr('data-flag');

    if($flag==0){
        e.preventDefault(); //to prevent submitting

        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: '#DD6B55',
            confirmButtonText: 'Yes, I am sure!',
            cancelButtonText: "No, cancel it!",
            closeOnConfirm: false,
            closeOnCancel: false
         },
         function(isConfirm){

           if (isConfirm){
                swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

                //update the data-flag to 1 (as true), to submit
                $('#from1').attr('data-flag', '1');
                $('#from1').submit();
            } else {
                swal("Cancelled", "Your imaginary file is safe :)", "error"); 
            }
         });
    }

    return true;
});

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

  1. Using html5 doctype at the beginning of the page.

    <!DOCTYPE html>

  2. Force IE to use the latest render mode

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

  3. If your target browser is ie8, then check your compatible settings in IE8

I blog this in details

How to implement __iter__(self) for a container object (Python)

Another option is to inherit from the appropriate abstract base class from the `collections module as documented here.

In case the container is its own iterator, you can inherit from collections.Iterator. You only need to implement the next method then.

An example is:

>>> from collections import Iterator
>>> class MyContainer(Iterator):
...     def __init__(self, *data):
...         self.data = list(data)
...     def next(self):
...         if not self.data:
...             raise StopIteration
...         return self.data.pop()
...         
...     
... 
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
...     print i
...     
... 
4.0
3
two
1

While you are looking at the collections module, consider inheriting from Sequence, Mapping or another abstract base class if that is more appropriate. Here is an example for a Sequence subclass:

>>> from collections import Sequence
>>> class MyContainer(Sequence):
...     def __init__(self, *data):
...         self.data = list(data)
...     def __getitem__(self, index):
...         return self.data[index]
...     def __len__(self):
...         return len(self.data)
...         
...     
... 
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
...     print i
...     
... 
1
two
3
4.0

NB: Thanks to Glenn Maynard for drawing my attention to the need to clarify the difference between iterators on the one hand and containers that are iterables rather than iterators on the other.

Python - OpenCV - imread - Displaying Image

This can help you

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image );                   // Show our image inside it.

How to find length of digits in an integer?

Without conversion to string

import math
digits = int(math.log10(n))+1

To also handle zero and negative numbers

import math
if n > 0:
    digits = int(math.log10(n))+1
elif n == 0:
    digits = 1
else:
    digits = int(math.log10(-n))+2 # +1 if you don't count the '-' 

You'd probably want to put that in a function :)

Here are some benchmarks. The len(str()) is already behind for even quite small numbers

timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop

timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
 timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop

timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop

VBA - Select columns using numbers?

In this way, you can start to select data even behind column "Z" and select a lot of columns.

Sub SelectColumNums()
    Dim xCol1 As Integer, xNumOfCols as integer
    xCol1 = 26
    xNumOfCols = 17
    Range(Columns(xCol1), Columns(xCol1 + xNumOfCols)).Select
End Sub

Converting a string to a date in DB2

You can use:

select VARCHAR_FORMAT(creationdate, 'MM/DD/YYYY') from table name

Using multiple delimiters in awk

I see many perfect answers are up on the board, but still would like to upload my piece of code too,

awk -F"/" '{print $3 " " $5 " " $7}' sam | sed 's/ cat.* =//g'

Make a div fill up the remaining width

Flex-boxes are the solution - and they're fantastic. I've been wanting something like this out of css for a decade. All you need is to add display: flex to your style for "Main" and flex-grow: 100 (where 100 is arbitrary - its not important that it be exactly 100). Try adding this style (colors added to make the effect visible):

<style>
    #Main {
        background-color: lightgray;
        display: flex;
    }

    #div1 {
        border: 1px solid green;   
        height: 50px; 
        display: inline-flex; 
    }
    #div2 {
        border: 1px solid blue;    
        height: 50px;
        display: inline-flex;
        flex-grow: 100;
    }
    #div3 {
        border: 1px solid orange;        
        height: 50px;
        display: inline-flex;
    }
</style>

More info about flex boxes here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Disable arrow key scrolling in users browser

For maintainability, I would attach the "blocking" handler on the element itself (in your case, the canvas).

theCanvas.onkeydown = function (e) {
    if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
        e.view.event.preventDefault();
    }
}

Why not simply do window.event.preventDefault()? MDN states:

window.event is a proprietary Microsoft Internet Explorer property which is only available while a DOM event handler is being called. Its value is the Event object currently being handled.

Further readings:

How to save a Seaborn plot into a file

The suggested solutions are incompatible with Seaborn 0.8.1

giving the following errors because the Seaborn interface has changed:

AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure

AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function

The following calls allow you to access the figure (Seaborn 0.8.1 compatible):

swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig(...) 

as seen previously in this answer.

UPDATE: I have recently used PairGrid object from seaborn to generate a plot similar to the one in this example. In this case, since GridPlot is not a plot object like, for example, sns.swarmplot, it has no get_figure() function. It is possible to directly access the matplotlib figure by

fig = myGridPlotObject.fig

Like previously suggested in other posts in this thread.

Best way to pretty print a hash

Here's another approach using json and rouge:

require 'json'
require 'rouge'

formatter = Rouge::Formatters::Terminal256.new
json_lexer = Rouge::Lexers::JSON.new

puts formatter.format(json_lexer.lex(JSON.pretty_generate(JSON.parse(response))))

(parses response from e.g. RestClient)

How to Increase Import Size Limit in phpMyAdmin

If you are using WHM/Cpanel then in order to change that "Max: 50MiB" limit in the import section of phpmyadmin, you will have to change two values in WHM (Web Host Manager).

Step 1) Go to Tweak settings, find the "cPanel PHP Max upload size" change it according to your needs. Save changes.

Step 2) Go to Tweak settings, find the "cPanel PHP Max POST size" change it according to your needs. Save changes.

Go back to your phpMyadmin. The value should have changed.

enter image description here

enter image description here

enter image description here

How to reduce the image size without losing quality in PHP

If you are looking to reduce the size using coding itself, you can follow this code in php.

<?php 
function compress($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);

    return $destination;
}

$source_img = 'source.jpg';
$destination_img = 'destination .jpg';

$d = compress($source_img, $destination_img, 90);
?>

$d = compress($source_img, $destination_img, 90);

This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).

$info = getimagesize($source);

The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.

How to test if parameters exist in rails

if params[:one] && params[:two]
 ... do something ...
elsif params[:one]
 ... do something ...
end

'python' is not recognized as an internal or external command

I have met same issue when I install Python, and it is resolved when I set a PATH in system, here are the steps.

  • Navigate to "Control Panel" -> "System"
  • Click "Advanced system settings" on the left
  • Click "Environment Variables"
  • Search and click "Path" variable
  • Click "Edit"
  • Add "C:\"to the environment variables field, if you are using Windows7, then separate it by a semicolon from the existing entry. If you are using Windows10, just simply click "New" to add.
  • Reopen the Command Prompt and try enter image description here

Is Visual Studio Community a 30 day trial?

For my case the problem was in fact that i broke machine.config and looks like VS couldn't have a connection I've added the following lines to my machine.config

<!--
<system.net>
 <defaultProxy>
  <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
 </defaultProxy>
</system.net>
<!--
-->

After replacing the previous section to:

<!--
<system.net>
 <defaultProxy>
  <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
 </defaultProxy>
</system.net>
-->

VS started to work.

How do I replace text inside a div element?


function showPanel(fieldName) {
  var fieldNameElement = document.getElementById("field_name");
  while(fieldNameElement.childNodes.length >= 1) {
    fieldNameElement.removeChild(fieldNameElement.firstChild);
  }
  fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName));
}

The advantages of doing it this way:

  1. It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML
  2. fieldName might contain HTML, which could be an attempted XSS attack. If we know it's just text, we should be creating a text node, instead of having the browser parse it for HTML

If I were going to use a javascript library, I'd use jQuery, and do this:


  $("div#field_name").text(fieldName);

Note that @AnthonyWJones' comment is correct: "field_name" isn't a particularly descriptive id or variable name.

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

open your web.xml file. (if you don't know where is it, then just google it.) it is like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
.
.
.
.
</web-app>

just below the <?xml version="1.0" encoding="UTF-8"?> line, add a tag <element> and close it in the very bottom with </element> tag. Done.

Use superscripts in R axis labels

@The Thunder Chimp You can split text in such a way that some sections are affected by super(or sub) script and others aren't through the use of *. For your example, with splitting the word "moment" from "4th" -

plot(rnorm(30), xlab = expression('4'^th*'moment'))

Chrome extension: accessing localStorage in content script

Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:

  • store information from your content script without the need for message passing between content script and extension;
  • store your data as JavaScript objects without serializing them to JSON (localStorage only stores strings).

Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.

content_script.js

(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();

popup.js

(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.

Remember to declare storage permission in manifest.json.

manifest.json

...
"permissions": [
    "storage"
 ],
...

encapsulation vs abstraction real world example

Encapsulation is hiding information.

Abstraction is hiding the functionality details.

Encapsulation is performed by constructing the class. Abstraction is achieved by creating either Abstract Classes or Interfaces on top of your class.

In the example given in the question, we are using the class for its functionality and we don't care about how the device achieves that. So we can say the details of the phone are "abstracted" from us.

Encapsulation is hiding WHAT THE PHONE USES to achieve whatever it does; Abstraction is hiding HOW IT DOES it.-

How can I set a custom baud rate on Linux?

You can set a custom baud rate using the stty command on Linux. For example, to set a custom baud rate of 567890 on your serial port /dev/ttyX0, use the command:

stty -F /dev/ttyX0 567890

How to count items in JSON data

You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':

len(data['result'][0]['run'])

How to terminate a process in vbscript

Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("Notepad") : wscript.sleep 4000 : Rt.Terminate

Run the process with .Exec.

Then wait for 4 seconds.

After that kill this process.

ImportError: No module named _ssl

I am writing this solution for those who are still facing such issue and cant find the solution.

in my case, I am using

shared hosting (Cpanel Access) Linux CentOS.

I was facing this issue

No module named '_ssl'

I tried for all possible solutions but as you know sometimes things don't work for you and in hosting you don't have access to fully root and run queries. even my hosting provider did for me.. but NO GOOD RESULT.

so how I solved if you are using shared hosting and you have deployed your Django App using

Setup Python App

You only have to downgrade your Python Version, I downgraded from

Python 3.7.3

(As Python 3.7 does not have SSL module in it) To

Python 3.6.8

through Setup Python App.

Hope it will be helpful for someone with the same issue,

Image style height and width not taken in outlook mails

I have same problem for image which is not showing correctly in outlook.and I am using px and % for applying height and width for image. but when i removed px and % and using only just whatever the value in html it is worked for me. For example i was using : width="800px" now I'm using widht="800" and problem is resolved for me.

Editor does not contain a main type

File >> Import >> Existing Projects into Workspace >> Select Archive Filed >> Browse and locate file >> Finish. If its already imported some other way delete it and try it that way. I was having the same problem until i tried that.

Show special characters in Unix while using 'less' Command

In the same spirit as https://stackoverflow.com/a/6943976/7154924:

cat -A

-A, --show-all
       equivalent to -vET
-v, --show-nonprinting
       use ^ and M- notation, except for LFD and TAB
-E, --show-ends
       display $ at end of each line
-T, --show-tabs
       display TAB characters as ^I

Alternatively, or at the same time, you can pipe to tr to substitute arbitrary characters to the desired ones for display, before piping to a pager like less if desired.

Rounding integer division (instead of truncating)

int a, b;
int c = a / b;
if(a % b) { c++; }

Checking if there is a remainder allows you to manually roundup the quotient of integer division.

How to move a file?

Although os.rename() and shutil.move() will both rename files, the command that is closest to the Unix mv command is shutil.move(). The difference is that os.rename() doesn't work if the source and destination are on different disks, while shutil.move() doesn't care what disk the files are on.

Array of arrays (Python/NumPy)

You'll have problems creating lists without commas. It shouldn't be too hard to transform your data so that it uses commas as separating character.

Once you have commas in there, it's a relatively simple list creation operations:

array1 = [1,2,3]
array2 = [4,5,6]

array3 = [array1, array2]

array4 = [7,8,9]
array5 = [10,11,12]

array3 = [array3, [array4, array5]]

When testing we get:

print(array3)

[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:

array3[0][1]
[4, 5, 6]

array3[1][1]
[10, 11, 12]

Hope that helps.

How to change border color of textarea on :focus

you need just in scss varible

$input-btn-focus-width:       .05rem !default;

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

Force file download with php using header()

the htaccess solution

<filesmatch "\.(?i:doc|odf|pdf|cer|txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

you can read this page: https://www.techmesto.com/force-files-to-download-using-htaccess/

LPCSTR, LPCTSTR and LPTSTR

Adding to John and Tim's answer.

Unless you are coding for Win98, there are only two of the 6+ string types you should be using in your application

  • LPWSTR
  • LPCWSTR

The rest are meant to support ANSI platforms or dual compilations. Those are not as relevant today as they used to be.

Is it possible to run an .exe or .bat file on 'onclick' in HTML

You can do it on Internet explorer with OCX component and on chrome browser using a chrome extension chrome document in any case need additional settings on the client system!

Important part of chrome extension source:

var port = chrome.runtime.connectNative("your.app.id"); 
      port.onMessage.addListener(onNativeMessage); 
      port.onDisconnect.addListener(onDisconnected);
      port.postMessage("send some data to STDIO");

permission file:

{
      "name": "your.app.id",
      "description": "Name of your extension",
      "path": "myapp.exe",
      "type": "stdio",
      "allowed_origins": [
            "chrome-extension://IDOFYOUREXTENSION_lokldaeplkmh/"
      ]
}

and windows registry settings:

HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\your.app.id
REG_EXPAND_SZ : c:\permissionsettings.json

How to extend / inherit components?

update

Component inheritance is supported since 2.3.0-rc.0

original

So far, the most convenient for me is to keep template & styles into separate *html & *.css files and specify those through templateUrl and styleUrls, so it's easy reusable.

@Component {
    selector: 'my-panel',
    templateUrl: 'app/components/panel.html', 
    styleUrls: ['app/components/panel.css']
}
export class MyPanelComponent extends BasePanelComponent

Why does Vim save files with a ~ extension?

You're correct that the .swp file is used by vim for locking and as a recovery file.

Try putting set nobackup in your vimrc if you don't want these files. See the Vim docs for various backup related options if you want the whole scoop, or want to have .bak files instead...

Fork() function in C

I think every process you make start executing the line you create so something like this...

pid=fork() at line 6. fork function returns 2 values 
you have 2 pids, first pid=0 for child and pid>0 for parent 
so you can use if to separate

.

/*
    sleep(int time) to see clearly
    <0 fail 
    =0 child
    >0 parent
*/
int main(int argc, char** argv) {
    pid_t childpid1, childpid2;
    printf("pid = process identification\n");
    printf("ppid = parent process identification\n");
    childpid1 = fork();
    if (childpid1 == -1) {
        printf("Fork error !\n");
    }
    if (childpid1 == 0) {
        sleep(1);
        printf("child[1] --> pid = %d and  ppid = %d\n",
                getpid(), getppid());
    } else {
        childpid2 = fork();
        if (childpid2 == 0) {
            sleep(2);
            printf("child[2] --> pid = %d and ppid = %d\n",
                    getpid(), getppid());
        } else {
            sleep(3);
            printf("parent --> pid = %d\n", getpid());
        }
    }
    return 0;
}

//pid = process identification
//ppid = parent process identification
//child[1] --> pid = 2399 and  ppid = 2398
//child[2] --> pid = 2400 and ppid = 2398
//parent --> pid = 2398

linux.die.net

some uni stuff

How to download a branch with git?

For any Git newbies like me, here are some steps you could follow to download a remote repository, and then switch to the branch that you want to view. They probably abuse Git in some way, but it did the job for me! :-)

Clone the repository you want to download the code for (in this example I've picked the LRResty project on Github):

$ git clone https://github.com/lukeredpath/LRResty.git
$ cd LRResty

Check what branch you are using at this point (it should be the master branch):

$ git branch    
* master

Check out the branch you want, in my case it is called 'arcified':

 $ git checkout -b arcified origin/arcified
 Branch arcified set up to track remote branch arcified from origin.
 Switched to a new branch 'arcified'

Confirm you are now using the branch you wanted:

$ git branch    
* arcified
  master

If you want to update the code again later, run git pull:

$ git pull
Already up-to-date.

Iterating over every two elements in a list

I hope this will be even more elegant way of doing it.

a = [1,2,3,4,5,6]
zip(a[::2], a[1::2])

[(1, 2), (3, 4), (5, 6)]

Sass calculate percent minus px

IF you know the width of the container, you could do like this:

#container
  width: #{200}px
  #element
    width: #{(0.25 * 200) - 5}px

I'm aware that in many cases #container could have a relative width. Then this wouldn't work.

How might I schedule a C# Windows Service to perform a task daily?

Check out Quartz.NET. You can use it within a Windows service. It allows you to run a job based on a configured schedule, and it even supports a simple "cron job" syntax. I've had a lot of success with it.

Here's a quick example of its usage:

// Instantiate the Quartz.NET scheduler
var schedulerFactory = new StdSchedulerFactory();
var scheduler = schedulerFactory.GetScheduler();

// Instantiate the JobDetail object passing in the type of your
// custom job class. Your class merely needs to implement a simple
// interface with a single method called "Execute".
var job = new JobDetail("job1", "group1", typeof(MyJobClass));

// Instantiate a trigger using the basic cron syntax.
// This tells it to run at 1AM every Monday - Friday.
var trigger = new CronTrigger(
    "trigger1", "group1", "job1", "group1", "0 0 1 ? * MON-FRI");

// Add the job to the scheduler
scheduler.AddJob(job, true);
scheduler.ScheduleJob(trigger);

How to apply two CSS classes to a single element

This is very clear that to add two classes in single div, first you have to generate the classes and then combine them. This process is used to make changes and reduce the no. of classes. Those who make the website from scratch mostly used this type of methods. they make two classes first class is for color and second class is for setting width, height, font-style, etc. When we combine both the classes then the first class and second class both are in effect.

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

Read next word in java

you're better off reading a line and then doing a split.

File file = new File("path/to/file");
String words[]; // I miss C
String line;
HashMap<String, String> hm = new HashMap<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")))
{
    while((line = br.readLine() != null)){
        words = line.split("\\s");
        if (hm.containsKey(words[0])){
                System.out.println("Found duplicate ... handle logic");
        }
        hm.put(words[0],words[1]); //if index==0 is ur key
    }

} catch (FileNotFoundException e) {
        e.printStackTrace();
} catch (IOException e) {
        e.printStackTrace();
}

Cannot install Aptana Studio 3.6 on Windows

It seems having msysgit (Git for Windows) installed is causing the problem.

In most cases you'll have a pretty recent version of Git for Windows installed. Cited from https://code.google.com/p/tortoisegit/:

There was a security issue in Git, see here. Git for Windows < 1.9.5 is affected - so you should update, TortoiseGit itself is not affected (using the default configuration; only if libgit2 is manually enabled for checkout/fetching). TortoiseGit 1.8.13.0 includes all fixes.

But it seems Aptana Studio Installer won't accept any pre-installed version of Git for Windows!

What you need to do:

  1. Uninstall Git for Windows.
  2. Install Aptana Studio.
    Apanta Studio 3.6.1 will install Git for Windows 1.8.4-preview20130916.
  3. Download latest version of Git for Windows from http://msysgit.github.io/.
  4. Install latest version of Git for Windows.
    The outdated Git for Windows 1.8.4-preview20130916 will be updated to recent version.

That's it !!!

How to change indentation in Visual Studio Code?

You might also want to set the editor.detectIndentation to false, in addition to Elliot-J's answer.

VSCode will overwrite your editor.tabSize and editor.insertSpaces settings per file if it detects that a file has a different tab or spaces indentation pattern. You can run into this issue if you add existing files to your project, or if you add files using code generators like Angular Cli. The above setting prevents VSCode from doing this.

What should a JSON service return on failure / error

Yes, you should use HTTP status codes. And also preferably return error descriptions in a somewhat standardized JSON format, like Nottingham’s proposal, see apigility Error Reporting:

The payload of an API Problem has the following structure:

  • type: a URL to a document describing the error condition (optional, and "about:blank" is assumed if none is provided; should resolve to a human-readable document; Apigility always provides this).
  • title: a brief title for the error condition (required; and should be the same for every problem of the same type; Apigility always provides this).
  • status: the HTTP status code for the current request (optional; Apigility always provides this).
  • detail: error details specific to this request (optional; Apigility requires it for each problem).
  • instance: URI identifying the specific instance of this problem (optional; Apigility currently does not provide this).

Should I use pt or px?

A pt is 1/72th of an inch and is a useless measure for anything that is rendered on a device which doesn't calculate the DPI correctly. This makes it a reasonable choice for printing and a dreadful choice for use on screen.

A px is a pixel, which will map on to a screen pixel in most cases.

CSS provides a bunch of other units, and which one you should choose depends on what you are setting the size of.

A pixel is great if you need to size something to match an image, or if you want a thin border.

Percentages are great for font sizes as, if you use them consistently, you get font sizes proportional to the user's preference.

Ems are great when you want an element to size itself based on the font size (so a paragraph might get wider if the font size is larger)

… and so on.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Deleting full .m2/repository local repository solved my problem.

Or else you need to know what plugins are you using exactly with their dependencies as one of the plugin suffered a problem while downloading.

Appending to an empty DataFrame in Pandas?

You can concat the data in this way:

InfoDF = pd.DataFrame()
tempDF = pd.DataFrame(rows,columns=['id','min_date'])

InfoDF = pd.concat([InfoDF,tempDF])

Short IF - ELSE statement

I'm a little late to the party but for future readers.

From what i can tell, you're just wanting to toggle the visibility state right? Why not just use the ! operator?

jxPanel6.setVisible(!jxPanel6.isVisible);

It's not an if statement but I prefer this method for code related to your example.

Replace text in HTML page with jQuery

Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.

Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:

  $('body :not(script)').contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
      return this.nodeValue.replace('-9o0-9909','The new string');
  });

this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.

How to use bootstrap-theme.css with bootstrap 3?

I know this post is kinda old but...

  As 'witttness' pointed out.

About Your Own Custom Theme You might choose to modify bootstrap-theme.css when creating your own theme. Doing so may make it easier to make styling changes without accidentally breaking any of that built-in Bootstrap goodness.

  I see it as Bootstrap has seen over the years that everyone wants something a bit different than the core styles. While you could modify bootstrap.css it might break things and it could make updating to a newer version a real pain and time consuming. Downloading from a 'theme' site means you have to wait on if that creator updates that theme, big if sometimes, right?

  Some build their own 'custom.css' file and that's ok, but if you use 'bootstrap-theme.css' a lot of stuff is already built and this allows you to roll your own theme faster 'without' disrupting the core of bootstrap.css. I for one don't like the 3D buttons and gradients most of the time, so change them using bootstrap-theme.css. Add margins or padding, change the radius to your buttons, and so on...

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

How can I mix LaTeX in with Markdown?

yes, but you'll have to hack it a little yourself. I've written a filter that replaces latex tags $\some\inline\latex$ or $$\some\equation$$ with appropriate image tags to a mimetex.cgi script. It took all of 5 minutes.

Warning: spectacularly ugly...

#!/usr/bin/env python
import sys, markdown,re

MIMETEX_LOC="http://some.server.com/cgi-bin/mimetex.cgi"

def sanitizeLatex(text):
    return re.sub(r"\\",r"%5C", text)

def wrapLatexBlock(text):
    return '<img alt="equation" class="block" src="%s?%s"></img>'%(MIMETEX_LOC,text)

def wrapLatexInline(text):
    return '<img alt="equation" class="inline" src="%s?%s"></img>'%(MIMETEX_LOC,text)

def prepLatexBlock(matchobj):
    return wrapLatexBlock(sanitizeLatex(matchobj.group()[2:-2]))

def prepLatexInline(matchobj):
    return wrapLatexInline(sanitizeLatex(matchobj.group()[1:-1]))


if __name__ == "__main__":
    # initialise markdown
    md=markdown.Markdown()
    raw_md=open(sys.argv[1],"r").read()

    ##
    # deal with embedded latex
    ##
    raw_md=re.sub(r'\$\$(.*?)\$\$',prepLatexBlock, raw_md)
    raw_md=re.sub(r'\$(.*?)\$',prepLatexInline, raw_md)

    ##
    # once latex is parsed, convert md to html
    ##
    main_html=md.convert(raw_md)

    # hey presto!
    print(main_html)

Of course, you have to define the appropriate css yourself for .block and .inline images...

Set width of a "Position: fixed" div relative to parent div

This solution meets the following criteria

  1. Percentage width is allowed on parent
  2. Works after window resize
  3. Content underneath header is never inaccessible

As far as I'm aware, this criteria cannot be met without Javascript (unfortunately).

This solution uses jQuery, but could also be easily converted to vanilla JS:

_x000D_
_x000D_
function fixedHeader(){_x000D_
  $(this).width($("#wrapper").width());_x000D_
  $("#header-filler").height($("#header-fixed").outerHeight());_x000D_
}_x000D_
_x000D_
$(window).resize(function() {_x000D_
  fixedHeader();_x000D_
});_x000D_
_x000D_
fixedHeader();
_x000D_
#header-fixed{_x000D_
  position: fixed;_x000D_
  background-color: white;_x000D_
  top: 0;_x000D_
}_x000D_
#header-filler{_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="wrapper">_x000D_
<div id="header-fixed">_x000D_
  This is a nifty header! works even when resizing the window causing a line break_x000D_
</div>_x000D_
<div id="header-filler"></div>_x000D_
_x000D_
[start fluff]<br>_x000D_
a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>_x000D_
a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>_x000D_
a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>_x000D_
[end fluff]_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

C# - Multiple generic types in one list

public abstract class Metadata
{
}

// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
    private DataType mDataType;
}

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

Access is denied when attaching a database

I attached the mdf file by right clicking the database and removing the log file AdventureWorks2012_Data_log.ldf in the wizard . The mdf file was placed in the following location

    C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA

The above method helped me to resolve the issue .

How to update parent's state in React?

so, if you want to update parent component,

 class ParentComponent extends React.Component {
        constructor(props){
            super(props);
            this.state = {
               page:0
            }
        }

        handler(val){
            console.log(val) // 1
        }

        render(){
          return (
              <ChildComponent onChange={this.handler} />
           )
       }
   }


class ChildComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
             page:1
        };
    }

    someMethod = (page) => {
        this.setState({ page: page });
        this.props.onChange(page)
    }

    render() {
        return (
       <Button
            onClick={() => this.someMethod()} 
       > Click
        </Button>
      )
   }
}

Here onChange is an attribute with "handler" method bound to it's instance. we passed the method handler to the Child class component, to receive via onChange property in its props argument.

The attribute onChange will be set in a props object like this:

props ={
onChange : this.handler
}

and passed to the child component

So the Child component can access the value of name in the props object like this props.onChange

Its done through the use of render props.

Now the Child component has a button “Click” with an onclick event set to call the handler method passed to it via onChnge in its props argument object. So now this.props.onChange in Child holds the output method in the Parent class Reference and credits: Bits and Pieces

How to change line width in IntelliJ (from 120 character)

I didn't understand why my this didn't work but I found out that this setting is now also under the programming language itself at:

'Editor' | 'Code Style' | < your language > | 'Wrapping and Braces' | 'Right margin (columns)'

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

How to open local file on Jupyter?

I would suggest you to test it firstly: copy this train.csv to the same directory as this jupyter script in and then change the path to train.csv to test whether this can be loaded successfully.

If yes, that means the previous path input is a problem

If not, that means the file it self denied your access to it, or its real filename can be something else like: train.csv.<hidden extension>

How to make a checkbox checked with jQuery?

from jQuery v1.6 use prop

to check that is checkd or not

$('input:radio').prop('checked') // will return true or false

and to make it checkd use

$("input").prop("checked", true);

C# string reference type?

I believe your code is analogous to the following, and you should not have expected the value to have changed for the same reason it wouldn't here:

 public static void Main()
 {
     StringWrapper testVariable = new StringWrapper("before passing");
     Console.WriteLine(testVariable);
     TestI(testVariable);
     Console.WriteLine(testVariable);
 }

 public static void TestI(StringWrapper testParameter)
 {
     testParameter = new StringWrapper("after passing");

     // this will change the object that testParameter is pointing/referring
     // to but it doesn't change testVariable unless you use a reference
     // parameter as indicated in other answers
 }

Could not create the Java virtual machine

Just be careful. You will get this message if you try to enter a command that doesn't exist like this

/usr/bin/java -v

Launch an event when checking a checkbox in Angular2

You can use ngModel like

<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>

To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.

'Missing contentDescription attribute on image' in XML

If you don't care at all do this:

    android:contentDescription="@null"

Although I would advise the accepted solutions, this is a hack :D

$(...).datepicker is not a function - JQuery - Bootstrap

I had similiar problem. The quick fix I found is to change:

<div class="input-group datepicker" data-provide="datepicker">

to

<div class="input-group date" data-provide="datepicker">

Android custom dropdown/popup menu

Update: To create a popup menu in android with Kotlin refer my answer here.

To create a popup menu in android with Java:

Create a layout file activity_main.xml under res/layout directory which contains only one button.

Filename: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:paddingBottom="@dimen/activity_vertical_margin"  
    android:paddingLeft="@dimen/activity_horizontal_margin"  
    android:paddingRight="@dimen/activity_horizontal_margin"  
    android:paddingTop="@dimen/activity_vertical_margin"  
    tools:context=".MainActivity" >  

    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginLeft="62dp"  
        android:layout_marginTop="50dp"  
        android:text="Show Popup" />  

</RelativeLayout>  

Create a file popup_menu.xml under res/menu directory

It contains three items as shown below.

Filename: poupup_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >  

    <item  
        android:id="@+id/one"  
        android:title="One"/>  

    <item  
        android:id="@+id/two"  
        android:title="Two"/>  

    <item  
        android:id="@+id/three"  
        android:title="Three"/>  

</menu>  

MainActivity class which displays the popup menu on button click.

Filename: MainActivity.java

public class MainActivity extends Activity {  
    private Button button1;  

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //Creating the instance of PopupMenu
                PopupMenu popup = new PopupMenu(MainActivity.this, button1);
                //Inflating the Popup using xml file
                popup.getMenuInflater()
                    .inflate(R.menu.popup_menu, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(
                            MainActivity.this,
                            "You Clicked : " + item.getTitle(),
                            Toast.LENGTH_SHORT
                        ).show();
                        return true;
                    }
                });

                popup.show(); //showing popup menu
            }
        }); //closing the setOnClickListener method
    }
}

To add programmatically:

PopupMenu menu = new PopupMenu(this, view);

menu.getMenu().add("One");
menu.getMenu().add("Two");
menu.getMenu().add("Three");

menu.show();

Follow this link for creating menu programmatically.

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

@Cacheable key on multiple method arguments

Update: Current Spring cache implementation uses all method parameters as the cache key if not specified otherwise. If you want to use selected keys, refer to Arjan's answer which uses SpEL list {#isbn, #includeUsed} which is the simplest way to create unique keys.

From Spring Documentation

The default key generation strategy changed with the release of Spring 4.0. Earlier versions of Spring used a key generation strategy that, for multiple key parameters, only considered the hashCode() of parameters and not equals(); this could cause unexpected key collisions (see SPR-10237 for background). The new 'SimpleKeyGenerator' uses a compound key for such scenarios.

Before Spring 4.0

I suggest you to concat the values of the parameters in Spel expression with something like key="#checkWarehouse.toString() + #isbn.toString()"), I believe this should work as org.springframework.cache.interceptor.ExpressionEvaluator returns Object, which is later used as the key so you don't have to provide an int in your SPEL expression.

As for the hash code with a high collision probability - you can't use it as the key.

Someone in this thread has suggested to use T(java.util.Objects).hash(#p0,#p1, #p2) but it WILL NOT WORK and this approach is easy to break, for example I've used the data from SPR-9377 :

    System.out.println( Objects.hash("someisbn", new Integer(109), new Integer(434)));
    System.out.println( Objects.hash("someisbn", new Integer(110), new Integer(403)));

Both lines print -636517714 on my environment.

P.S. Actually in the reference documentation we have

@Cacheable(value="books", key="T(someType).hash(#isbn)") 
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

I think that this example is WRONG and misleading and should be removed from the documentation, as the keys should be unique.

P.P.S. also see https://jira.springsource.org/browse/SPR-9036 for some interesting ideas regarding the default key generation.

I'd like to add for the sake of correctness and as an entertaining mathematical/computer science fact that unlike built-in hash, using a secure cryptographic hash function like MD5 or SHA256, due to the properties of such function IS absolutely possible for this task, but to compute it every time may be too expensive, checkout for example Dan Boneh cryptography course to learn more.

Java: Get month Integer from Date

tl;dr

myUtilDate.toInstant()                          // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
          .atZone(                              // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object. 
              ZoneId.of( "America/Montreal" )   // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
          )                                     // Returns a `ZonedDateTime` object.
          .getMonthValue()                      // Extract a month number. Returns a `int` number.

java.time Details

The Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.

I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.

Using java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.

The Month class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.

To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.

ZoneId zoneId = ZoneId.of( "America/Montreal" );  // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth(); 
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Any tools to generate an XSD schema from an XML instance document?

If all you want is XSD, LiquidXML has a free version that does XSDs, and its got a GUI to it so you can tweak the XSD if you like. Anyways nowadays I write my own XSDs by hand, but its all thanks to this app.

http://www.liquid-technologies.com/

Creating columns in listView and add items

I didn't see anyone answer this correctly. So I'm posting it here. In order to get columns to show up you need to specify the following line.

lvRegAnimals.View = View.Details;

And then add your columns after that.

lvRegAnimals.Columns.Add("Id", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);

Hope this helps anyone else looking for this answer in the future.

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

Check if file is already open

Using the Apache Commons IO library...

boolean isFileUnlocked = false;
try {
    org.apache.commons.io.FileUtils.touch(yourFile);
    isFileUnlocked = true;
} catch (IOException e) {
    isFileUnlocked = false;
}

if(isFileUnlocked){
    // Do stuff you need to do with a file that is NOT locked.
} else {
    // Do stuff you need to do with a file that IS locked
}

How to view the SQL queries issued by JPA?

There's a file called persistence.xml Press Ctrl+Shift+R and find it, then, there's a place written something like showSQL.

Just put it as true

I'm not sure if the server must be started as Debug mode. Check the SQLs created on console.

How do you install an APK file in the Android emulator?

From Windows 7 Onwards ,

Shift + Right click in your apk file folder.

Select Open Command Window Here

Type & Hit "adb install AppName.apk"

adb command for getting ip address assigned by operator

adb shell ip addr > ippdetails.txt This will get all list of ip's assigned to devices.

Ruby on Rails: Where to define global constants?

Another option, if you want to define your constants in one place:

module DSL
  module Constants
    MY_CONSTANT = 1
  end
end

But still make them globally visible without having to access them in fully qualified way:

DSL::Constants::MY_CONSTANT # => 1
MY_CONSTANT # => NameError: uninitialized constant MY_CONSTANT
Object.instance_eval { include DSL::Constants }
MY_CONSTANT # => 1

How to avoid Number Format Exception in java?

As always, the Jakarta Commons have at least part of the answer :

NumberUtils.isNumber()

This can be used to check most whether a given String is a number. You still have to choose what to do in case your String isnt a number ...

Rock, Paper, Scissors Game Java

Why not check for what the user entered and then ask the user to enter correct input again?

eg:

//Get player's play from input-- note that this is 
// stored as a string 
System.out.println("Enter your play: "); 
response = scan.next();
if(response=="R"||response=="P"||response=="S"){
  personPlay = response;
}else{
  System.out.println("Invaild Input")
}

for the other modifications, please check my total code at pastebin

How do I return the SQL data types from my query?

select COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH 
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME='yourTable';

Repository Pattern Step by Step Explanation

This is a nice example: The Repository Pattern Example in C#

Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:

  • for reading, it creates the query satisfying the supplied criteria and returns the result set
  • for writing, it issues the commands necessary to make the underlying persistence engine (e.g. an SQL database) save the data

Implicit function declarations in C

An implicitly declared function is one that has neither a prototype nor a definition, but is called somewhere in the code. Because of that, the compiler cannot verify that this is the intended usage of the function (whether the count and the type of the arguments match). Resolving the references to it is done after compilation, at link-time (as with all other global symbols), so technically it is not a problem to skip the prototype.

It is assumed that the programmer knows what he is doing and this is the premise under which the formal contract of providing a prototype is omitted.

Nasty bugs can happen if calling the function with arguments of a wrong type or count. The most likely manifestation of this is a corruption of the stack.

Nowadays this feature might seem as an obscure oddity, but in the old days it was a way to reduce the number of header files included, hence faster compilation.

How to set a string's color

for linux (bash) following code works for me:

System.out.print("\033[31mERROR  \033[0m");

the \033[31m will switch the color to red and \033[0m will switch it back to normal.

embedding image in html email

I don't find any of the answers here useful, so I am providing my solution.

  1. The problem is that you are using multipart/related as the content type which is not good in this case. I am using multipart/mixed and inside it multipart/alternative (it works on most clients).

  2. The message structure should be as follows:

    [Headers]
    Content-type:multipart/mixed; boundary="boundary1"
    --boundary1
    Content-type:multipart/alternative; boundary="boundary2"
    --boundary2
    Content-Type: text/html; charset=ISO-8859-15
    Content-Transfer-Encoding: 7bit
    [HTML code with a href="cid:..."]
    
    --boundary2
    Content-Type: image/png;
    name="moz-screenshot.png"
    Content-Transfer-Encoding: base64
    Content-ID: <part1.06090408.01060107>
    Content-Disposition: inline; filename="moz-screenshot.png"
    [base64 image data here]
    
    --boundary2--
    --boundary1--
    

Then it will work

How to consume a SOAP web service in Java

I will use CXF also you can think of AXIS 2 .

The best way to do it may be using JAX RS Refer this example

Example:

wsimport -p stockquote http://stockquote.xyz/quote?wsdl

This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.

I

How to do a newline in output

Actually you don't even need the block:

  Dir.chdir 'C:/Users/name/Music'
  music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
  puts 'what would you like to call the playlist?'
  playlist_name = gets.chomp + '.m3u'

  File.open(playlist_name, 'w').puts(music)

How do I detach objects in Entity Framework Code First?

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

Line Break in XML?

If you are using CSS to style (Not recommended.) you can use display:block;, however, this will only give you line breaks before and after the styled element.

C# Listbox Item Double Click Event

I know this question is quite old, but I was looking for a solution to this problem too. The accepted solution is for WinForms not WPF which I think many who come here are looking for.

For anyone looking for a WPF solution, here is a great approach (via Oskar's answer here):

private void myListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject obj = (DependencyObject)e.OriginalSource;

    while (obj != null && obj != myListBox)
    {
        if (obj.GetType() == typeof(ListBoxItem))
        {
             // Do something
             break;
         }
         obj = VisualTreeHelper.GetParent(obj);
    }
}

Basically, you walk up the VisualTree until you've either found a parent item that is a ListBoxItem, or you ascend up to the actual ListBox (and therefore did not click a ListBoxItem).

Unable to create Genymotion Virtual Device

I also had the issue. Had to delete Genymotion cached files/devices then redownload devices and reinstall.

Get sum of MySQL column in PHP

$row['Value'] is probably a string. Try using intval($row['Value']).

Also, make sure you set $sum = 0 before the loop.

Or, better yet, add SUM(Value) AS Val_Sum to your SQL query.

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

I feel the performance characteristics change from one DBMS to another. It's all on how they choose to implement it. Since I have worked extensively on Oracle, I'll tell from that perspective.

COUNT(*) - Fetches entire row into result set before passing on to the count function, count function will aggregate 1 if the row is not null

COUNT(1) - Will not fetch any row, instead count is called with a constant value of 1 for each row in the table when the WHERE matches.

COUNT(PK) - The PK in Oracle is indexed. This means Oracle has to read only the index. Normally one row in the index B+ tree is many times smaller than the actual row. So considering the disk IOPS rate, Oracle can fetch many times more rows from Index with a single block transfer as compared to entire row. This leads to higher throughput of the query.

From this you can see the first count is the slowest and the last count is the fastest in Oracle.

How to run a python script from IDLE interactive shell?

There is one more alternative (for windows) -

    import os
    os.system('py "<path of program with extension>"')

WPF Binding StringFormat Short Date String

If you want add a string with the value use this:

<TextBlock Text="{Binding Date, StringFormat= 'Date : {0:d}'}" />

Programmatically add custom event in the iPhone Calendar

Remember to set the endDate to the created event, it is mandatory.

Otherwise it will fail (almost silently) with this error:

"Error Domain=EKErrorDomain Code=3 "No end date has been set." UserInfo={NSLocalizedDescription=No end date has been set.}"

The complete working code for me is:

EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
    if (!granted) { return; }
    EKEvent *calendarEvent = [EKEvent eventWithEventStore:store];
    calendarEvent.title = [NSString stringWithFormat:@"CEmprendedor: %@", _event.name];
    calendarEvent.startDate = _event.date;
    // 5 hours of duration, we must add the duration of the event to the API
    NSDate *endDate = [_event.date dateByAddingTimeInterval:60*60*5];
    calendarEvent.endDate = endDate;
    calendarEvent.calendar = [store defaultCalendarForNewEvents];
    NSError *err = nil;
    [store saveEvent:calendarEvent span:EKSpanThisEvent commit:YES error:&err];
    self.savedEventId = calendarEvent.eventIdentifier;  //saving the calendar event id to possibly deleted them
}];

Windows Forms ProgressBar: Easiest way to start/stop marquee?

This code is a part of a login form where the users wait for the authentication server to respond.

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace LoginWithProgressBar
{
    public partial class TheForm : Form
    {
        // BackgroundWorker object deals with the long running task
        private readonly BackgroundWorker _bw = new BackgroundWorker();

        public TheForm()
        {
            InitializeComponent();

            // set MarqueeAnimationSpeed
            progressBar.MarqueeAnimationSpeed = 30;

            // set Visible false before you start long running task
            progressBar.Visible = false;

            _bw.DoWork += Login;
            _bw.RunWorkerCompleted += BwRunWorkerCompleted;
        }

        private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // hide the progress bar when the long running process finishes
            progressBar.Hide();
        }

        private static void Login(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            // emulate long (3 seconds) running task
            Thread.Sleep(3000);
        }

        private void ButtonLoginClick(object sender, EventArgs e)
        {
            // show the progress bar when the associated event fires (here, a button click)
            progressBar.Show();

            // start the long running task async
            _bw.RunWorkerAsync();
        }
    }
}    

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Your syntax is pretty screwy.

Change this:

input:not(disabled)not:[type="submit"]:focus{

to:

input:not(:disabled):not([type="submit"]):focus{

Seems that many people don't realize :enabled and :disabled are valid CSS selectors...

Unit tests vs Functional tests

very simply we can say:

  • black box: user interface test like functional test
  • white box: code test like unit test

read more here.

href overrides ng-click in Angular.js

This worked for me in IE 9 and AngularJS v1.0.7:

<a href="javascript:void(0)" ng-click="logout()">Logout</a>

Thanks to duckeggs' comment for the working solution!

How to specify a min but no max decimal using the range data annotation attribute?

It seems there's no choice but to put in the max value manually. I was hoping there was some type of overload where you didn't need to specify one.

[Range(typeof(decimal), "0", "79228162514264337593543950335")]
public decimal Price { get; set; }

java.io.IOException: Broken pipe

You may have not set the output file.

optional parameters in SQL Server stored proc?

You can declare like this

CREATE PROCEDURE MyProcName
    @Parameter1 INT = 1,
    @Parameter2 VARCHAR (100) = 'StringValue',
    @Parameter3 VARCHAR (100) = NULL
AS

/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
    /* whatever code you desire for a missing parameter*/
    INSERT INTO ........
END

/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter

Check if PHP-page is accessed from an iOS device

function user_agent(){
    $iPod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");
    $iPhone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $iPad = strpos($_SERVER['HTTP_USER_AGENT'],"iPad");
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    file_put_contents('./public/upload/install_log/agent',$_SERVER['HTTP_USER_AGENT']);
    if($iPad||$iPhone||$iPod){
        return 'ios';
    }else if($android){
        return 'android';
    }else{
        return 'pc';
    }
}

How to remove all elements in String array in java?

Just Re-Initialize the array

example = new String[size]

or If it is inside a running loop,Just Re-declare it again,

**for(int i=1;i<=100;i++) { String example = new String[size] //Your code goes here`` }**

Could not find module FindOpenCV.cmake ( Error in configuration process)

Another possibility is to denote where you can find OpenCV_DIR in the CMakeLists.txt file. For example, the following cmake scripts work for me:

cmake_minimum_required(VERSION 2.8)

project(performance_test)

set(OpenCV_STATIC ON)
set(OpenCV_CUDA OFF)
set(OpenCV_DIR "${CMAKE_SOURCE_DIR}/../install")

find_package(OpenCV REQUIRED)

include_directories(${OpenCV_INCLUDE_DIRS})

link_directories(${OpenCV_LIB_DIR})

file(GLOB my_source_files ./src/*)

add_executable( performance_test ${my_source_files})

target_link_libraries(performance_test ${OpenCV_LIBS})

Just to remind that you should set OpenCV_STATIC and OpenCV_CUDA as well before you invoke OpenCVConfig.cmake. In my case the built library is static library that does not use CUDA.

Unable to launch the IIS Express Web server

I had the same problem but the solution that worked for me was different.

  1. In VS2013 Opened Debug > {YourWebsiteName} Properties
  2. Select the "Web" tab.
  3. Under "Servers" I found "Override application root URL" was checked. I unchecked it and saved.

That was all I needed to get things running.

PIG how to count a number of rows in alias

Be careful, with COUNT your first item in the bag must not be null. Else you can use the function COUNT_STAR to count all rows.

Loop through properties in JavaScript object with Lodash

In ES6, it is also possible to iterate over the values of an object using the for..of loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:

  • The for..of loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.
  • The iterator object is obtained by invoking the function defined in the @@iterator property, or Symbol.iterator property, of obj1. This is the function you must define yourself, and it should return an iterator object

Here is an example:

const obj1 = {
  a: 5,
  b: "hello",
  [Symbol.iterator]: function() {
    const thisObj = this;
    let index = 0;
    return {
      next() {
        let keys = Object.keys(thisObj);
        return {
          value: thisObj[keys[index++]],
          done: (index > keys.length)
        };
      }
    };
  }
};

Now we can use the for..of loop:

for (val of obj1) {
  console.log(val);
}    // 5 hello

Getting index value on razor foreach

I prefer to use this extension method:

public static class Extensions
{
    public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self)
        => self.Select((item, index) => (item, index));
}

Source:

https://stackoverflow.com/a/39997157/3850405

Razor:

@using Project.Shared.Helpers 

@foreach (var (item, index) in collection.WithIndex())
{
<p>
    Name: @item.Name Index: @index
</p>
}