# Programs & Examples On #Activesync

ActiveSync is a mobile data synchronization technology and protocol developed by Microsoft

### Powershell send-mailmessage - email to multiple recipients

That's right, each address needs to be quoted. If you have multiple addresses listed on the command line, the Send-MailMessage likes it if you specify both the human friendly and the email address parts.

### How to write a function that takes a positive integer N and returns a list of the first N natural numbers

There are two problems with your attempt.

First, you've used `n+1` instead of `i+1`, so you're going to return something like `[5, 5, 5, 5]` instead of `[1, 2, 3, 4]`.

Second, you can't `for`-loop over a number like `n`, you need to loop over some kind of sequence, like `range(n)`.

So:

``````def naturalNumbers(n):
return [i+1 for i in range(n)]
``````

But if you already have the `range` function, you don't need this at all; you can just `return range(1, n+1)`, as arshaji showed.

So, how would you build this yourself? You don't have a sequence to loop over, so instead of `for`, you have to build it yourself with `while`:

``````def naturalNumbers(n):
results = []
i = 1
while i <= n:
results.append(i)
i += 1
return results
``````

Of course in real-life code, you should always use `for` with a `range`, instead of doing things manually. In fact, even for this exercise, it might be better to write your own `range` function first, just to use it for `naturalNumbers`. (It's already pretty close.)

There is one more option, if you want to get clever.

If you have a list, you can slice it. For example, the first 5 elements of `my_list` are `my_list[:5]`. So, if you had an infinitely-long list starting with `1`, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using `count` or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with `islice`. So:

``````from itertools import count, islice
def naturalNumbers(n):
return list(islice(count(1), n))
``````

### How to make an Android device vibrate? with different frequency?

I use the following utils method:

``````public static final void vibratePhone(Context context, short vibrateMilliSeconds) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(vibrateMilliSeconds);
}
``````

Add the following permission to the AndroidManifest file

``````<uses-permission android:name="android.permission.VIBRATE"/>
``````

You can use overloaded methods in case if you wish to use different types of vibrations (patterns / indefinite) as suggested above.

### How do I get the serial key for Visual Studio Express?

The question is about VS 2008 Express.

Microsoft's web page for registering Visual Studio 2008 Express has been dead (404) for some time, so registering it is not possible.

Instead, as a workaround, you can temporarily remove the requirement to register VS2008Exp by deleting (or renaming) the registry key:

``````HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration
``````

To ensure that this is working beforehand, click Help -> register product within VS2008.

You should see text like

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 10 more days before you will be required to register it."

Close the application, delete that key, reopen, click help->register product.

The text should now say

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 30 more days before you will be required to register it."

So you have two options - delete that key manually every 30 days, or run it from a batch file that also contains a line like:

``````reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f
``````

[Edit: User @i486 confirms on testing that this workaround works even after the expiration period has expired]

[Edit2: User @Wyatt8740 has a much more elegant way to prevent the value from reappearing.]

### Second line in li starts under the bullet after CSS-reset

Here is a good example -

``````ul li{
list-style-type: disc;
list-style-position: inside;
text-indent: -1em;
}
``````

Working Demo: http://jsfiddle.net/d9VNk/

### Superscript in Python plots

Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:

``````ax1.set_ylabel('Rate (min?¹)')
``````

### Finding an item in a List<> using C#

``````item = objects.Find(obj => obj.property==myValue);
``````

### Is there an eval() function in Java?

You can use the `ScriptEngine` class and evaluate it as a Javascript string.

``````ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("4*5");
``````

There may be a better way, but this one works.

### Insert null/empty value in sql datetime column by default

I was having the same issue this morning. It appears that for a DATE or DATETIME field, an empty value cannot be inserted. I got around this by first checking for an empty value (mydate = "") and if it was empty setting mydate = "NULL" before insert.

The DATE and DATETIME fields don't behave in the same way as VARCHAR fields.

### How to extract public key using OpenSSL?

For AWS importing an existing public key,

1. Export from the .pem doing this... (on linux)

``````openssl rsa -in ./AWSGeneratedKey.pem -pubout -out PublicKey.pub
``````

This will produce a file which if you open in a text editor looking something like this...

``````-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn/8y3uYCQxSXZ58OYceG
A4uPdGHZXDYOQR11xcHTrH13jJEzdkYZG8irtyG+m3Jb6f9F8WkmTZxl+4YtkJdN
eEKyFujH5bUTGX87nULRfg67tmtxBlT8WWWtFe2O/wedBTGGQxXMpwh4ObjLl3Qh
bfwxlBbh2N4471TyrErv04lbNecGaQqYxGrY8Ot3l2V2fXCzghAQg26Hc4dR2wyA
PPgWq78db+gU3QsePeo2Ki5sonkcyQQQlCkL35Asbv8khvk90gist4kijPnVBCuv
cwIDAQAB
-----END PUBLIC KEY-----
``````
1. However AWS will NOT accept this file.

You have to strip off the `-----BEGIN PUBLIC KEY-----` and `-----END PUBLIC KEY-----` from the file. Save it and import and it should work in AWS.

### How to get base url in CodeIgniter 2.*

``````\$autoload['helper'] = array('form', 'url', 'file', 'html'); <-- Like This
``````

Then you can use base_url or any kind of url.

### Get array of object's keys

Of course, `Object.keys()` is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike `Object.keys()`'s behaviour).

``````var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
``````

...could be modified. You can do the assignment right in the variable part.

``````var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [], i = 0;
for (keys[i++] in foo) {}
``````

Of course, this behaviour is different to what `Object.keys()` actually does (jsFiddle). You could simply use the shim on the MDN documentation.

### How to give a pattern for new line in grep?

just found

``````grep \$'\r'
``````

It's using `\$'\r'` for c-style escape in Bash.

### How to delete a localStorage item when the browser window/tab is closed?

you can try following code to delete local storage:

``````delete localStorage.myPageDataArr;
``````

### How to detect a docker daemon port

There are 2 ways in configuring the docker daemon port

1) Configuring at /etc/default/docker file:

``````DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock"
``````

2) Configuring at /etc/docker/daemon.json:

``````{
"debug": true,
"hosts": ["tcp://127.0.0.1:5000", "unix:///var/run/docker.sock"]
}
``````

If the docker default socket is not configured Docker will wait for infinite period.i.e

``````Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
``````

NOTE : BUT DON'T CONFIGURE IN BOTH THE CONFIGURATION FILES, the following error may occur :

``````Waiting for /var/run/docker.sock
unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [tcp://127.0.0.1:5000 unix:///var/run/docker.sock], from file: tcp://127.0.0.1:5000)
``````

The reason for adding both the user port[ tcp://127.0.0.1:5000] and default docker socket[unix:///var/run/docker.sock] is that the user port enables the access to the docker APIs whereas the default socket enables the CLI. In case the default port[unix:///var/run/docker.sock] is not mentioned in /etc/default/docker file the following error may occur:

``````# docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
``````

This error is not because that the docker is not running, but because of default docker socket is not enabled.

Once the configuration is enabled restart the docker service and verify the docker port is enabled or not:

``````# netstat -tunlp | grep -i 5000
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      31661/dockerd
``````

Applicable for Docker Version 17.04, may vary with different versions of docker.

### What is the meaning of ToString("X2")?

It formats the string as two uppercase hexadecimal characters.

In more depth, the argument `"X2"` is a "format string" that tells the `ToString()` method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.

`byte.ToString()` without any arguments returns the number in its natural decimal representation, with no padding.

Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' `ToString()` methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with `DateTime.ToString()`.

### Get div tag scroll position using JavaScript

``````<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title></title>
<script type="text/javascript">
function scollPos() {
var div = document.getElementById("myDiv").scrollTop;
document.getElementById("pos").innerHTML = div;
}
</script>
<body>
<form id="form1">
<div id="pos">
</div>
<div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
Place some large content here
</div>
</form>
</body>
</html>
``````

### Should I call Close() or Dispose() for stream objects?

For what it's worth, the source code for `Stream.Close` explains why there are two methods:

``````// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable.  However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern.  We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup now.
``````

In short, `Close` is only there because it predates `Dispose`, and it can't be deleted for compatibility reasons.

### -didSelectRowAtIndexPath: not being called

In my case the problem was I had a `UITableViewCell` subclass and I'd implemented these two methods: `touchesBegan:withEvent:` & `touchesEnded:withEvent` to handle a fancy animation on touch. But I'd forgotten to add the `[super touchesBegan:touches withEvent:event];` method ad `[super touchesEnded:touches withEvent:event];` to also inform the parent of cell of the touch.

So changing the code to following solved my problem:

``````-(void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
[super touchesBegan:touches withEvent:event];
//blah blah blah
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesEnded:touches withEvent:event];
//rest of the code
}
``````

### setValue:forUndefinedKey: this class is not key value coding-compliant for the key

I had a similar problem, but I was using `initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil` explicitly using the name of the class as the string passed (yes bad form!).

I ended up deleting and re-creating the view controller using a slightly different name but neglected to change the string specified in the method, thus my old version was still used - even though it was in the trash!

I will likely use this structure going forward as suggested in: Is passing two nil paramters to initWithNibName:bundle: method bad practice (i.e. unsafe or slower)?

``````- (id)init
{
[super initWithNibName:@"MyNib" bundle:nil];
... typical initialization ...
return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
return [self init];
}
``````

Hopefully this helps someone!

### How to download a file using a Java REST service and a data stream

"How can I directly (without saving the file on 2nd server) download the file from 1st server to client's machine?"

Just use the `Client` API and get the `InputStream` from the response

``````Client client = ClientBuilder.newClient();
String url = "...";
final InputStream responseStream = client.target(url).request().get(InputStream.class);
``````

There are two flavors to get the `InputStream`. You can also use

``````Response response = client.target(url).request().get();
InputStream is = (InputStream)response.getEntity();
``````

Which one is the more efficient? I'm not sure, but the returned `InputStream`s are different classes, so you may want to look into that if you care to.

From 2nd server I can get a ByteArrayOutputStream to get the file from 1st server, can I pass this stream further to the client using the REST service?

So most of the answers you'll see in the link provided by @GradyGCooper seem to favor the use of `StreamingOutput`. An example implementation might be something like

``````final InputStream responseStream = client.target(url).request().get(InputStream.class);
System.out.println(responseStream.getClass());
StreamingOutput output = new StreamingOutput() {
@Override
public void write(OutputStream out) throws IOException, WebApplicationException {
int length;
byte[] buffer = new byte[1024];
while((length = responseStream.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
out.flush();
responseStream.close();
}
};
"Content-Disposition", "attachment, filename=\"...\"").build();
``````

But if we look at the source code for StreamingOutputProvider, you'll see in the `writeTo`, that it simply writes the data from one stream to another. So with our implementation above, we have to write twice.

How can we get only one write? Simple return the `InputStream` as the `Response`

``````final InputStream responseStream = client.target(url).request().get(InputStream.class);
"Content-Disposition", "attachment, filename=\"...\"").build();
``````

If we look at the source code for InputStreamProvider, it simply delegates to `ReadWriter.writeTo(in, out)`, which simply does what we did above in the `StreamingOutput` implementation

`````` public static void writeTo(InputStream in, OutputStream out) throws IOException {
final byte[] data = new byte[BUFFER_SIZE];
}
}
``````

Asides:

• `Client` objects are expensive resources. You may want to reuse the same `Client` for request. You can extract a `WebTarget` from the client for each request.

``````WebTarget target = client.target(url);
InputStream is = target.request().get(InputStream.class);
``````

I think the `WebTarget` can even be shared. I can't find anything in the Jersey 2.x documentation (only because it is a larger document, and I'm too lazy to scan through it right now :-), but in the Jersey 1.x documentation, it says the `Client` and `WebResource` (which is equivalent to `WebTarget` in 2.x) can be shared between threads. So I'm guessing Jersey 2.x would be the same. but you may want to confirm for yourself.

• You don't have to make use of the `Client` API. A download can be easily achieved with the `java.net` package APIs. But since you're already using Jersey, it doesn't hurt to use its APIs

• The above is assuming Jersey 2.x. For Jersey 1.x, a simple Google search should get you a bunch of hits for working with the API (or the documentation I linked to above)

# UPDATE

I'm such a dufus. While the OP and I are contemplating ways to turn a `ByteArrayOutputStream` to an `InputStream`, I missed the simplest solution, which is simply to write a `MessageBodyWriter` for the `ByteArrayOutputStream`

``````import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

@Provider
public class OutputStreamWriter implements MessageBodyWriter<ByteArrayOutputStream> {

@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return ByteArrayOutputStream.class == type;
}

@Override
public long getSize(ByteArrayOutputStream t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}

@Override
public void writeTo(ByteArrayOutputStream t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
throws IOException, WebApplicationException {
t.writeTo(entityStream);
}
}
``````

Then we can simply return the `ByteArrayOutputStream` in the response

``````return Response.ok(baos).build();
``````

D'OH!

#### UPDATE 2

Here are the tests I used (

Resource class

``````@Path("test")
public class TestResource {

final String path = "some_150_mb_file";

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response doTest() throws Exception {
InputStream is = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[4096];
while ((len = is.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, len);
}
System.out.println("Server size: " + baos.size());
return Response.ok(baos).build();
}
}
``````

Client test

``````public class Main {
public static void main(String[] args) throws Exception {
Client client = ClientBuilder.newClient();
String url = "http://localhost:8080/api/test";
Response response = client.target(url).request().get();
String location = "some_location";
FileOutputStream out = new FileOutputStream(location);
InputStream is = (InputStream)response.getEntity();
int len = 0;
byte[] buffer = new byte[4096];
while((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
out.close();
is.close();
}
}
``````

#### UPDATE 3

So the final solution for this particular use case was for the OP to simply pass the `OutputStream` from the `StreamingOutput`'s `write` method. Seems the third-party API, required a `OutputStream` as an argument.

``````StreamingOutput output = new StreamingOutput() {
@Override
public void write(OutputStream out) {
}
}
return Response.ok(output).build();
``````

Not quite sure, but seems the reading/writing within the resource method, using ByteArrayOutputStream`, realized something into memory.

The point of the `downloadFile` method accepting an `OutputStream` is so that it can write the result directly to the `OutputStream` provided. For instance a `FileOutputStream`, if you wrote it to file, while the download is coming in, it would get directly streamed to the file.

It's not meant for us to keep a reference to the `OutputStream`, as you were trying to do with the `baos`, which is where the memory realization comes in.

So with the way that works, we are writing directly to the response stream provided for us. The method `write` doesn't actually get called until the `writeTo` method (in the `MessageBodyWriter`), where the `OutputStream` is passed to it.

You can get a better picture looking at the `MessageBodyWriter` I wrote. Basically in the `writeTo` method, replace the `ByteArrayOutputStream` with `StreamingOutput`, then inside the method, call `streamingOutput.write(entityStream)`. You can see the link I provided in the earlier part of the answer, where I link to the `StreamingOutputProvider`. This is exactly what happens

### What is SYSNAME data type in SQL Server?

`sysname` is used by `sp_send_dbmail`, a stored procedure that "Sends an e-mail message to the specified recipients" and located in the msdb database.

According to Microsoft,

``````[ @profile_name = ] 'profile_name'
``````

Is the name of the profile to send the message from. The profile_name is of type sysname, with a default of NULL. The profile_name must be the name of an existing Database Mail profile. When no profile_name is specified, sp_send_dbmail uses the default private profile for the current user. If the user does not have a default private profile, sp_send_dbmail uses the default public profile for the msdb database. If the user does not have a default private profile and there is no default public profile for the database, @profile_name must be specified.

### Eloquent get only one column as an array

I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().

``````// <= Laravel 5.1
Word_relation::where('word_one', \$word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', \$word_id)->pluck('word_one')->toArray();
``````

These methods can also be called on a Collection for example

``````// <= Laravel 5.1
\$collection = Word_relation::where('word_one', \$word_id)->get();
\$array = \$collection->lists('word_one');

// >= Laravel 5.2
\$collection = Word_relation::where('word_one', \$word_id)->get();
\$array = \$collection->pluck('word_one');
``````

### typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Core-js did not work for me as it caused other issues, however, simply installing the latest version of `npm i @types/es6-promise --save-dev` got rid of the issues. The issues for me stemmed from compiling an sdk that was using rxjs. Here is the error I was getting:

```````node_modules/rxjs/Observable.d.ts(59,60): error TS2693: Promise only refers to a type, but is being used as a value here.`
``````

### Check existence of input argument in a Bash shell script

In my case the only working solution to check if last arguments exists is:

``````if [[ "\$7" == '' ]] ; then
echo "error"
exit
fi
``````

### I do not understand how execlp() works in Linux

this prototype:

``````  int execlp(const char *file, const char *arg, ...);
``````

Says that execlp ìs a variable argument function. It takes 2 `const char *`. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also `char *` - all these are C strings (and the last argument must be a NULL pointer)

So, the `file` argument is the path name of an executable file to be executed. `arg` is the string we want to appear as `argv[0]` in the executable. By convention, `argv[0]` is just the file name of the executable, normally it's set to the same as `file`.

The `...` are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

``````\$ ls
``````

That'd be `execlp("ls", "ls", (char *)NULL);` Or if you run

``````\$ ls -l /
``````

That'd be `execlp("ls", "ls", "-l", "/", (char *)NULL);`

So on to `execlp("/bin/sh", ..., "ls -l /bin/??", ...);`

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

`````` \$ ls -l /bin/??
``````

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

``````\$ /bin/sh -c "ls -l /bin/??"
``````

This becomes

``````  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);
``````

Side note: The `/bin/??` is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

``````  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);
``````

Probably nothing would happen (unless there's a file actually named `/bin/??`) as there's no shell that interprets and expands /bin/??

### How do I perform an insert and return inserted identity with Dapper?

If you're using Dapper.SimpleSave:

`````` //no safety checks
public static int Create<T>(object param)
{
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
conn.Create<T>((T)param);
return (int) (((T)param).GetType().GetProperties().Where(
x => x.CustomAttributes.Where(
y=>y.AttributeType.GetType() == typeof(Dapper.SimpleSave.PrimaryKeyAttribute).GetType()).Count()==1).First().GetValue(param));
}
}
``````

### Dropdown using javascript onchange

easy

``````<script>
\$('#hide').css('display','none');
\$('#plano').change(function(){

if(document.getElementById('plano').value == 1){
\$('#hide').show('slow');

}else
if(document.getElementById('plano').value == 0){

\$('#hide').hide('slow');
}else
if(document.getElementById('plano').value == 0){
\$('#hide').css('display','none');

}

});
\$('#plano').change();
});
</script>
``````

this example shows and hides the div if selected in combobox some specific value

### Add/remove HTML inside div using JavaScript

To my most biggest surprise I present to you a DOM method I've never used before googeling this question and finding ancient `insertAdjacentHTML` on MDN (see CanIUse?insertAdjacentHTML for a pretty green compatibility table).

So using it you would write

_x000D_
_x000D_
``````function addRow () {_x000D_
'afterbegin',_x000D_
`<div class="row">_x000D_
<input type="text" name="name" value="" />_x000D_
<input type="text" name="value" value="" />_x000D_
<label><input type="checkbox" name="check" value="1" />Checked?</label>_x000D_
<input type="button" value="-" onclick="removeRow(this)">_x000D_
</div>`      _x000D_
)_x000D_
}_x000D_
_x000D_
function removeRow (input) {_x000D_
input.parentNode.remove()_x000D_
}``````
_x000D_
``````<input type="button" value="+" onclick="addRow()">_x000D_
_x000D_
<div id="content">_x000D_
</div>``````
_x000D_
_x000D_
_x000D_

### How to create a new schema/new user in Oracle Database 11g?

Generally speaking a schema in oracle is the same as an user. Oracle Database automatically creates a schema when you create a user. A file with the DDL file extension is an SQL Data Definition Language file.

Creating new user (using SQL Plus)

Basic SQL Plus commands:

``````  - connect: connects to a database
- disconnect: logs off but does not exit
- exit: exists
``````

Open SQL Plus and log:

``````/ as sysdba
``````

The sysdba is a role and is like "root" on unix or "Administrator" on Windows. It sees all, can do all. Internally, if you connect as sysdba, your schema name will appear to be SYS.

Create an user:

``````SQL> create user johny identified by 1234;
``````

View all users and check if the user johny is there:

``````SQL> select username from dba_users;
``````

If you try to login as johny now you would get an error:

``````ERROR:
ORA-01045: user JOHNY lacks CREATE SESSION privilege; logon denied
``````

The user to login needs at least create session priviledge so we have to grant this privileges to the user:

``````SQL> grant create session to johny;
``````

Now you are able to connect as the user johny:

``````username: johny
``````

To get rid of the user you can drop it:

``````SQL> drop user johny;
``````

That was basic example to show how to create an user. It might be more complex. Above we created an user whose objects are stored in the database default tablespace. To have database tidy we should place users objects to his own space (tablespace is an allocation of space in the database that can contain schema objects).

``````SQL> select tablespace_name from dba_tablespaces;
``````

Create tablespace:

``````SQL> create tablespace johny_tabspace
2  datafile 'johny_tabspace.dat'
3  size 10M autoextend on;
``````

Create temporary tablespace (Temporaty tablespace is an allocation of space in the database that can contain transient data that persists only for the duration of a session. This transient data cannot be recovered after process or instance failure.):

``````SQL> create temporary tablespace johny_tabspace_temp
2  tempfile 'johny_tabspace_temp.dat'
3  size 5M autoextend on;
``````

Create the user:

``````SQL> create user johny
2  identified by 1234
3  default tablespace johny_tabspace
4  temporary tablespace johny_tabspace_temp;
``````

Grant some privileges:

``````SQL> grant create session to johny;
SQL> grant create table to johny;
SQL> grant unlimited tablespace to johny;
``````

Login as johny and check what privileges he has:

``````SQL> select * from session_privs;

PRIVILEGE
----------------------------------------
CREATE SESSION
UNLIMITED TABLESPACE
CREATE TABLE
``````

With create table privilege the user can create tables:

``````SQL> create table johny_table
2  (
3     id int not null,
4     text varchar2(1000),
5     primary key (id)
6  );
``````

Insert data:

``````SQL> insert into johny_table (id, text)
2  values (1, 'This is some text.');
``````

Select:

``````SQL> select * from johny_table;

ID  TEXT
--------------------------
1   This is some text.
``````

To get DDL data you can use DBMS_METADATA package that "provides a way for you to retrieve metadata from the database dictionary as XML or creation DDL and to submit the XML to re-create the object.". (with help from http://www.dba-oracle.com/oracle_tips_dbms_metadata.htm)

For table:

``````SQL> set pagesize 0
SQL> set long 90000
SQL> set feedback off
SQL> set echo off
SQL> SELECT DBMS_METADATA.GET_DDL('TABLE',u.table_name) FROM USER_TABLES u;
``````

Result:

``````  CREATE TABLE "JOHNY"."JOHNY_TABLE"
(    "ID" NUMBER(*,0) NOT NULL ENABLE,
"TEXT" VARCHAR2(1000),
PRIMARY KEY ("ID")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE"  ENABLE
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE"
``````

For index:

``````SQL> set pagesize 0
SQL> set long 90000
SQL> set feedback off
SQL> set echo off
SQL> SELECT DBMS_METADATA.GET_DDL('INDEX',u.index_name) FROM USER_INDEXES u;
``````

Result:

``````  CREATE UNIQUE INDEX "JOHNY"."SYS_C0013353" ON "JOHNY"."JOHNY_TABLE" ("ID")
PCTFREE 10 INITRANS 2 MAXTRANS 255
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE"
``````

DDL

Schema objects

Differences between schema and user

Privileges

Creating user/schema

Creating tablespace

SQL Plus commands

### How do I print a double value without scientific notation using Java?

This will work as long as your number is a whole number:

``````double dnexp = 12345678;
System.out.println("dexp: " + (long)dexp);
``````

If the double variable has precision after the decimal point it will truncate it.

### Write a file in external storage in Android

Even though above answers are correct, I wanna add a notice to distinguish types of storage:

• Internal storage: It should say 'private storage' because it belongs to the app and cannot be shared. Where it's saved is based on where the app installed. If the app was installed on an SD card (I mean the external storage card you put more into a cell phone for more space to store images, videos, ...), your file will belong to the app means your file will be in an SD card. And if the app was installed on an Internal card (I mean the onboard storage card coming with your cell phone), your file will be in an Internal card.
• External storage: It should say 'public storage' because it can be shared. And this mode divides into 2 groups: private external storage and public external storage. Basically, they are nearly the same, you can consult more from this site: https://developer.android.com/training/data-storage/files
• A real SD card (I mean the external storage card you put more into a cell phone for more space to store images, videos, ...): this was not stated clearly on Android docs, so many people might be confused with how to save files in this card.

Here is the link to source code for cases I mentioned above: https://github.com/mttdat/utils/blob/master/utils/src/main/java/mttdat/utils/FileUtils.java

### Float vs Decimal in ActiveRecord

In Rails 3.2.18, :decimal turns into :integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue for us.

The lesson learned is "always use homogeneous development and deployment databases!"

### getting error while updating Composer

After installing packages from given answers, i still get some errors then i install following package and it works fine:

• php-xml

for specific version:

• php7.0-xml

command for php 7.0

``````sudo apt-get install php7.0-xml
``````

in some cases you also needs a package php7.0-common . install it same as above command.

### How to store NULL values in datetime fields in MySQL?

For what it is worth: I was experiencing a similar issue trying to update a MySQL table via Perl. The update would fail when an empty string value (translated from a null value from a read from another platform) was passed to the date column ('dtcol' in the code sample below). I was finally successful getting the data updated by using an IF statement embedded in my update statement:

``````    ...
my \$stmnt='update tbl set colA=?,dtcol=if(?="",null,?) where colC=?';
my \$status=\$dbh->do(\$stmt,undef,\$iref[1],\$iref[2],\$iref[2],\$ref[0]);
...
``````

### Standard Android Button with a different color

An easy way is to just define a custom Button class which accepts all the properties that you desire like radius, gradient, pressed color, normal color etc. and then just use that in your XML layouts instead of setting up the background using XML. A sample is here

This is extremely useful if you have a lot of buttons with same properties like radius, selected color etc. You can customize your inherited button to handle these additional properties.

Result (No Background selector was used).

Normal Button

Pressed Button

### Compare two List<T> objects for equality, ignoring order

This is a slightly difficult problem, which I think reduces to: "Test if two lists are permutations of each other."

I believe the solutions provided by others only indicate whether the 2 lists contain the same unique elements. This is a necessary but insufficient test, for example `{1, 1, 2, 3}` is not a permutation of `{3, 3, 1, 2}` although their counts are equal and they contain the same distinct elements.

I believe this should work though, although it's not the most efficient:

``````static bool ArePermutations<T>(IList<T> list1, IList<T> list2)
{
if(list1.Count != list2.Count)
return false;

var l1 = list1.ToLookup(t => t);
var l2 = list2.ToLookup(t => t);

return l1.Count == l2.Count
&& l1.All(group => l2.Contains(group.Key) && l2[group.Key].Count() == group.Count());
}
``````

### MySQL IF ELSEIF in select query

``````SELECT id,
IF(qty_1 <= '23', price,
IF(('23' > qty_1 && qty_2 <= '23'), price_2,
IF(('23' > qty_2 && qty_3 <= '23'), price_3,
IF(('23' > qty_2 && qty_3<='23'), price_3,
IF('23' > qty_3, price_4, 1))))) as total
FROM product;
``````

You can use the `if - else` control structure or the `IF` function in MySQL.

### Position an element relative to its container

You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:

``````div.parent{
position: relative;
left: 0px;  /* stick it wherever it was positioned by default */
top: 0px;
}

div.child{
position: absolute;
left: 10px;
top: 10px;
}
``````

### UIView Hide/Show with animation

Swift 4

``````extension UIView {

func fadeIn(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in }) {
self.alpha = 0.0

UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.isHidden = false
self.alpha = 1.0
}, completion: completion)
}

func fadeOut(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in }) {
self.alpha = 1.0

UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.alpha = 0.0
}) { (completed) in
self.isHidden = true
completion(true)
}
}
}
``````

And to use use it, simple call these functions like:

``````yourView.fadeOut() // this will hide your view with animation
``````

### How can I make Bootstrap 4 columns all the same height?

You just have to use `class="row-eq-height"` with your `class="row"` to get equal height columns for previous bootstrap versions.

but with bootstrap 4 this comes natively.

### Ruby: How to get the first character of a string

``````"Smith"[0..0]
``````

works in both ruby 1.8 and ruby 1.9.

### Split code over multiple lines in an R script

You are not breaking code over multiple lines, but rather a single identifier. There is a difference.

``````R> setwd(paste("~/a/very/long/path/here",
"/and/then/some/more",
"/and/then/some/more",
"/and/then/some/more", sep=""))
``````

which also illustrates that it is perfectly fine to break code across multiple lines.

### javax.faces.application.ViewExpiredException: View could not be restored

When our page is idle for x amount of time the view will expire and throw javax.faces.application.ViewExpiredException to prevent this from happening one solution is to create CustomViewHandler that extends ViewHandler and override restoreView method all the other methods are being delegated to the Parent

``````import java.io.IOException;
import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

public class CustomViewHandler extends ViewHandler {
private ViewHandler parent;

public CustomViewHandler(ViewHandler parent) {
//System.out.println("CustomViewHandler.CustomViewHandler():Parent View Handler:"+parent.getClass());
this.parent = parent;
}

@Override
public UIViewRoot restoreView(FacesContext facesContext, String viewId) {
/**
* {@link javax.faces.application.ViewExpiredException}. This happens only  when we try to logout from timed out pages.
*/
UIViewRoot root = null;
root = parent.restoreView(facesContext, viewId);
if(root == null) {
root = createView(facesContext, viewId);
}
return root;
}

@Override
public Locale calculateLocale(FacesContext facesContext) {
return parent.calculateLocale(facesContext);
}

@Override
public String calculateRenderKitId(FacesContext facesContext) {
String renderKitId = parent.calculateRenderKitId(facesContext);
//System.out.println("CustomViewHandler.calculateRenderKitId():RenderKitId: "+renderKitId);
return renderKitId;
}

@Override
public UIViewRoot createView(FacesContext facesContext, String viewId) {
return parent.createView(facesContext, viewId);
}

@Override
public String getActionURL(FacesContext facesContext, String actionId) {
return parent.getActionURL(facesContext, actionId);
}

@Override
public String getResourceURL(FacesContext facesContext, String resId) {
return parent.getResourceURL(facesContext, resId);
}

@Override
public void renderView(FacesContext facesContext, UIViewRoot viewId) throws IOException, FacesException {
parent.renderView(facesContext, viewId);
}

@Override
public void writeState(FacesContext facesContext) throws IOException {
parent.writeState(facesContext);
}

public ViewHandler getParent() {
return parent;
}

}
``````

``````<application>
<view-handler>com.demo.CustomViewHandler</view-handler>
</application>
``````

### How to install grunt and how to build script with it

You should be installing grunt-cli to the devDependencies of the project and then running it via a script in your package.json. This way other developers that work on the project will all be using the same version of grunt and don't also have to install globally as part of the setup.

Install grunt-cli with `npm i -D grunt-cli` instead of installing it globally with `-g`.

``````//package.json

...

"scripts": {
"build": "grunt"
}
``````

Then use `npm run build` to fire off grunt.

Now the answer for your question is yes, it will just work by copying the standard snippet. According to documentation, now the standard snippet has automatic cookie domain configuration: `ga('create', 'UA-XXXXX-Y', 'auto');` where cookie domain is automatically determined.

In addition, if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'.

### Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe `x` is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper `dataframe` out of x by doing

``````x = x.copy()
``````

This will remove the warning, but it is not the proper way

You should be using the `DataFrame.loc` method, as the warning suggests, like this:

``````x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
``````

### Is there a cross-domain iframe height auto-resizer that works?

I got the solution for setting the height of the iframe dynamically based on it's content. This works for the cross domain content. There are some steps to follow to achieve this.

1. Suppose you have added iframe in "abc.com/page" web page

```<div> <iframe id="IframeId" src="http://xyz.pqr/contactpage" style="width:100%;" onload="setIframeHeight(this)"></iframe> </div>```

2. Next you have to bind windows "message" event under web page "abc.com/page"

``````window.addEventListener('message', function (event) {
//Here We have to check content of the message event  for safety purpose
//event data contains message sent from page added in iframe as shown in step 3
if (event.data.hasOwnProperty("FrameHeight")) {
//Set height of the Iframe
\$("#IframeId").css("height", event.data.FrameHeight);
}
});
``````

On iframe load you have to send message to iframe window content with "FrameHeight" message:

``````function setIframeHeight(ifrm) {
var height = ifrm.contentWindow.postMessage("FrameHeight", "*");
}
``````
1. On main page that added under iframe here "xyz.pqr/contactpage" you have to bind windows "message" event where all messages are going to receive from parent window of "abc.com/page"
``````window.addEventListener('message', function (event) {

// Need to check for safety as we are going to process only our messages
// So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
if (event.data == "FrameHeight") {

//event.source contains parent page window object
//which we are going to use to send message back to main page here "abc.com/page"

//parentSourceWindow = event.source;

//Calculate the maximum height of the page
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);

// Send height back to parent page "abc.com/page"
event.source.postMessage({ "FrameHeight": height }, "*");
}
});
``````

### How to create PDF files in Python

rinohtype supports embedding PDF, PNG and JPEG images (natively) and other bitmap formats (when Pillow is installed).

(Full disclosure: I am the author of rinohtype)

### What's the PowerShell syntax for multiple values in a switch statement?

Supports entering y|ye|yes and case insensitive.

``````switch -regex (\$someString.ToLower()) {
"^y(es?)?\$" {
"You entered Yes."
}
default { "You entered No." }
}
``````

### Why does javascript replace only first instance when using replace?

Unlike the C#/.NET class library (and most other sensible languages), when you pass a `String` in as the string-to-match argument to the `string.replace` method, it doesn't do a string replace. It converts the string to a `RegExp` and does a regex substitution. As Gumbo explains, a regex substitution requires the `g`?lobal flag, which is not on by default, to replace all matches in one go.

If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:

``````var id= 'c_'+date.split('/').join('');
``````

### What is the right way to treat argparse.Namespace() as a dictionary?

If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, `vars()`:

``````>>> parser = argparse.ArgumentParser()
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}
``````

— The Python Standard Library, 16.4.4.6. The Namespace object

### MVC 4 Data Annotations "Display" Attribute

If two different views are sharing the same model (for instance, maybe one is for mobile output and one is regular), it could be nice to have the string reside in a single place: as metadata on the ViewModel.

Additionally, if you had an inherited version of the model that necessitated a different display, it could be useful. For instance:

``````public class BaseViewModel
{
[Display(Name = "Basic Name")]
public virtual string Name { get; set; }
}

public class OtherViewModel : BaseViewModel
{
[Display(Name = "Customized Inherited Name")]
public override string Name { get; set; }
}
``````

I'll admit that that example is pretty contrived...

Those are the best arguments in favor of using the attribute that I can come up with. My personal opinion is that, for the most part, that sort of thing is best left to the markup.

### Can the Android drawable directory contain subdirectories?

``````#!/usr/bin/env ruby

# current dir should be drawable-hdpi/ etc

Dir.foreach('.') {|f|
}

# symlink all resources renaming with underscores
Dir.glob("**/*.png") {|f|
system "ln -s #{f} #{f.gsub('/', '_')}" if f.include?("/")
}
``````

You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.

### Array vs ArrayList in performance

I agree with somebody's recently deleted post that the differences in performance are so small that, with very very few exceptions, (he got dinged for saying never) you should not make your design decision based upon that.

In your example, where the elements are Objects, the performance difference should be minimal.

If you are dealing with a large number of primitives, an array will offer significantly better performance, both in memory and time.

### In Python, what does dict.pop(a,b) mean?

The `pop` method of dicts (like `self.data`, i.e. `{'a':'aaa','b':'bbb','c':'ccc'}`, here) takes two arguments -- see the docs

The second argument, `default`, is what `pop` returns if the first argument, `key`, is absent. (If you call `pop` with just one argument, `key`, it raises an exception if that key's absent).

In your example, `print b.pop('a',{'b':'bbb'})`, this is irrelevant because `'a'` is a key in `b.data`. But if you repeat that line...:

``````b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data
``````

you'll see it makes a difference: the first `pop` removes the `'a'` key, so in the second `pop` the `default` argument is actually returned (since `'a'` is now absent from `b.data`).

### Add missing dates to pandas dataframe

Here's a nice method to fill in missing dates into a dataframe, with your choice of `fill_value`, `days_back` to fill in, and sort order (`date_order`) by which to sort the dataframe:

``````def fill_in_missing_dates(df, date_col_name = 'date',date_order = 'asc', fill_value = 0, days_back = 30):

df.set_index(date_col_name,drop=True,inplace=True)
df.index = pd.DatetimeIndex(df.index)
d = datetime.now().date()
d2 = d - timedelta(days = days_back)
idx = pd.date_range(d2, d, freq = "D")
df = df.reindex(idx,fill_value=fill_value)
df[date_col_name] = pd.DatetimeIndex(df.index)

return df
``````

### How to make HTML table cell editable?

This is the essential point although you don't need to make the code this messy. Instead you could just iterate through all the `<td>` and add the `<input>` with the attributes and finally put in the values.

_x000D_
_x000D_
``````function edit(el) {_x000D_
el.childNodes[0].removeAttribute("disabled");_x000D_
el.childNodes[0].focus();_x000D_
window.getSelection().removeAllRanges();_x000D_
}_x000D_
function disable(el) {_x000D_
el.setAttribute("disabled","");_x000D_
}``````
_x000D_
``````<table border>_x000D_
<tr>_x000D_
<td ondblclick="edit(this)"><input value="cell1" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="cell2" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="cell3" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="so forth..." disabled onblur="disable(this)">_x000D_
</td>_x000D_
</tr>_x000D_
</table>``````
_x000D_
_x000D_
_x000D_

### Create a .csv file with values from a Python list

For those looking for less complicated solution. I actually find this one more simplisitic solution that will do similar job:

``````import pandas as pd
a = ['a','b','c']
df = pd.DataFrame({'a': a})
df= df.set_index('a').T
df.to_csv('list_a.csv', index=False)
``````

Hope this helps as well.

### How to stop mysqld

On OSX 10.8 and on, the control for MySQL is available from the System Configs. Open System Preferences, click on Mysql (usually on the very bottom) and start/stop the service from that pane. https://dev.mysql.com/doc/refman/5.6/en/osx-installation-launchd.html

The plist file is now under /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

### What is the "right" JSON date format?

"2014-01-01T23:28:56.782Z"

The date is represented in a standard and sortable format that represents a UTC time (indicated by the Z). ISO 8601 also supports time zones by replacing the Z with + or – value for the timezone offset:

"2014-02-01T09:28:56.321-10:00"

There are other variations of the timezone encoding in the ISO 8601 spec, but the –10:00 format is the only TZ format that current JSON parsers support. In general it’s best to use the UTC based format (Z) unless you have a specific need for figuring out the time zone in which the date was produced (possible only in server side generation).

NB:

``````    var date = new Date();
console.log(date); // Wed Jan 01 2014 13:28:56 GMT-
1000 (Hawaiian Standard Time)

var json = JSON.stringify(date);
console.log(json);  // "2014-01-01T23:28:56.782Z"
``````

To tell you that's the preferred way even though JavaScript doesn't have a standard format for it

``````// JSON encoded date
var json = "\"2014-01-01T23:28:56.782Z\"";

var dateStr = JSON.parse(json);
console.log(dateStr); // 2014-01-01T23:28:56.782Z
``````

### New to unit testing, how to write great tests?

Unit testing is about the output you get from a function/method/application. It does not matter at all how the result is produced, it just matters that it is correct. Therefore, your approach of counting calls to inner methods and such is wrong. What I tend to do is sit down and write what a method should return given certain input values or a certain environment, then write a test which compares the actual value returned with what I came up with.

### PHP Parse error: syntax error, unexpected T_PUBLIC

The `public` keyword is used only when declaring a class method.

Since you're declaring a simple function and not a class you need to remove `public` from your code.

### JQuery: if div is visible

You can use `.is(':visible')`

Selects all elements that are visible.

For example:

``````if(\$('#selectDiv').is(':visible')){
``````

Also, you can get the div which is visible by:

``````\$('div:visible').callYourFunction();
``````

Live example:

_x000D_
_x000D_
``````console.log(\$('#selectDiv').is(':visible'));_x000D_
console.log(\$('#visibleDiv').is(':visible'));``````
_x000D_
``````#selectDiv {_x000D_
display: none;  _x000D_
}``````
_x000D_
``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>``````
_x000D_
_x000D_
_x000D_

### Vertically align text within a div

Add a vertical align to the CSS content `#column-content strong` too:

``````#column-content strong {
...
vertical-align: middle;
}
``````

=== UPDATE ===

With a span around the other text and another vertical align:

HTML:

``````... <span>yet another text content that should be centered vertically</span> ...
``````

CSS:

``````#column-content span {
vertical-align: middle;
}
``````

Also see the next example.

### simple vba code gives me run time error 91 object variable or with block not set

You need Set with objects:

`````` Set rng = Sheet8.Range("A12")
``````

Sheet8 is fine.

`````` Sheet1.[a1]
``````

### Pandas: Subtracting two date columns and the result being an integer

I feel that the overall answer does not handle if the dates 'wrap' around a year. This would be useful in understanding proximity to a date being accurate by day of year. In order to do these row operations, I did the following. (I had this used in a business setting in renewing customer subscriptions).

``````def get_date_difference(row, x, y):
try:
# Calcuating the smallest date difference between the start and the close date
# There's some tricky logic in here to calculate for determining date difference
# the other way around (Dec -> Jan is 1 month rather than 11)

sub_start_date = int(row[x].strftime('%j')) # day of year (1-366)
close_date = int(row[y].strftime('%j')) # day of year (1-366)

later_date_of_year = max(sub_start_date, close_date)
earlier_date_of_year = min(sub_start_date, close_date)
days_diff = later_date_of_year - earlier_date_of_year

# Calculates the difference going across the next year (December -> Jan)
days_diff_reversed = (365 - later_date_of_year) + earlier_date_of_year
return min(days_diff, days_diff_reversed)

except ValueError:
return None
``````

Then the function could be:

``````dfAC_Renew['date_difference'] = dfAC_Renew.apply(get_date_difference, x = 'customer_since_date', y = 'renewal_date', axis = 1)
``````

### “Unable to find manifest signing certificate in the certificate store” - even when add new key

Try this: Right click on your project -> Go to properties -> Click signing which is left side of the screen -> Uncheck the Sign the click once manifests -> Save & Build

### Remote debugging Tomcat with Eclipse

In tomcat 7, catalina.sh has this code:

``````if [ "\$1" = "jpda" ] ; then
if [ -z "\$JPDA_TRANSPORT" ]; then
JPDA_TRANSPORT="dt_socket"
fi
if [ -z "\$JPDA_ADDRESS" ]; then
fi
if [ -z "\$JPDA_SUSPEND" ]; then
JPDA_SUSPEND="n"
fi
if [ -z "\$JPDA_OPTS" ]; then
fi
CATALINA_OPTS="\$CATALINA_OPTS \$JPDA_OPTS"
shift
fi
``````

Ii implies that you can setup JPDA with:

``````export JPDA_TRANSPORT=dt_socket
export JPDA_SUSPEND=n
``````

Or with:

``````JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"
``````

And finally use:

`catalina.sh jpda start`

Regards

### Comment out HTML and PHP together

Instead of using HTML comments (which have no effect on PHP code -- which will still be executed), you should use PHP comments:

``````<?php /*
<tr>
<td><?php echo \$entry_keyword; ?></td>
<td><input type="text" name="keyword" value="<?php echo \$keyword; ?>" /></td>
</tr>
<tr>
<td><?php echo \$entry_sort_order; ?></td>
<td><input name="sort_order" value="<?php echo \$sort_order; ?>" size="1" /></td>
</tr>
*/ ?>
``````

With that, the PHP code inside the HTML will not be executed; and nothing (not the HTML, not the PHP, not the result of its non-execution) will be displayed.

Just one note: you cannot nest C-style comments... which means the comment will end at the first `*/` encountered.

### How can I force component to re-render with hooks in React?

You can (ab)use normal hooks to force a rerender by taking advantage of the fact that React doesn't print booleans in JSX code

``````// create a hook
const [forceRerender, setForceRerender] = React.useState(true);

// ...put this line where you want to force a rerender
setForceRerender(!forceRerender);

// ...make sure that {forceRerender} is "visible" in your js code
// ({forceRerender} will not actually be visible since booleans are
// not printed, but updating its value will nonetheless force a
// rerender)
return (
<div>{forceRerender}</div>
)

``````

### Lists in ConfigParser

Coming late to this party, but I recently implemented this with a dedicated section in a config file for a list:

``````[paths]
path1           = /some/path/
path2           = /another/path/
...
``````

and using `config.items( "paths" )` to get an iterable list of path items, like so:

``````path_items = config.items( "paths" )
for key, path in path_items:
#do something with path
``````

Hope this helps other folk Googling this question ;)

### MySQL check if a table exists without throwing an exception

If the reason for wanting to do this is is conditional table creation, then 'CREATE TABLE IF NOT EXISTS' seems ideal for the job. Until I discovered this, I used the 'DESCRIBE' method above. More info here: MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

### How to zip a whole folder using PHP

``````\$zip = new ZipArchive;
\$zip->open('testPDFZip.zip', ZipArchive::CREATE);
\$new_filename = end(explode("/",\$file));
}
\$zip->close();
``````

### 0xC0000005: Access violation reading location 0x00000000

The problem here, as explained in other comments, is that the pointer is being dereference without being properly initialized. Operating systems like Linux keep the lowest addresses (eg first 32MB: 0x00_0000 -0x200_0000) out of the virtual address space of a process. This is done because dereferencing zeroed non-initialized pointers is a common mistake, like in this case. So when this type of mistake happens, instead of actually reading a random variable that happens to be at address 0x0 (but not the memory address the pointer would be intended for if initialized properly), the pointer would be reading from a memory address outside of the process's virtual address space. This causes a page fault, which results in a segmentation fault, and a signal is sent to the process to kill it. That's why you are getting the access violation error.

### Row numbers in query result using Microsoft Access

I needed the best x results of points per team.

Ranking does not solves this problem when there are results with equal points. So I need a `recordnumber`

I made a VBA function in Access to create a `recordnumber` that resets on ID change.

You have to query this query with where `recordnumber <= x` to get the points per team.

NB Access changes the record-number

1. when you query the query filtered on record number
2. when you filter out some results
3. when you change the sort order

That is not what I thought that would happen.

Solved this by using a temporary table and saving the `recordnumbers` and keys or an extra field in the table.

``````SELECT ID, Points, RecordNumberOffId([ID}) AS Recordnumber
FROM Team ORDER BY ID ASC, Points DESC;
``````

It uses 3 module level variables to remember between calls

``````Dim PreviousID As Long
Dim PreviousRecordNumber As Long
Dim TimeLastID As Date

Public Function RecordNumberOffID(ID As Long) As Long
'ID is sortgroup identity
'Reset if last call longer dan nn seconds in the past
If Time() - TimeLastID > 0.0003 Then '0,000277778 = 1 second
PreviousID = 0
PreviousRecordNumber = 0
End If
If ID <> PreviousID Then
PreviousRecordNumber = 0
PreviousID = ID
End If
PreviousRecordNumber = PreviousRecordNumber + 1
RecordNumberOffID = PreviousRecordNumber
TimeLastID = Time()
End Function
``````

### Writing image to local server

This thread is old but I wanted to do same things with the https://github.com/mikeal/request package.

Here a working example

``````var fs      = require('fs');
var request = require('request');
// var request = require('request').defaults({jar: true});

request.get({url: 'https://someurl/somefile.torrent', encoding: 'binary'}, function (err, response, body) {
fs.writeFile("/tmp/test.torrent", body, 'binary', function(err) {
if(err)
console.log(err);
else
console.log("The file was saved!");
});
});
``````

### How do I include inline JavaScript in Haml?

I'm using fileupload-jquery in haml. The original js is below:

_x000D_
_x000D_
``````<!-- The template to display files available for download -->_x000D_
{% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
{% if (file.error) { %}_x000D_
<td></td>_x000D_
<td class="name"><span>{%=file.name%}</span></td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
{% } else { %}_x000D_
<td class="preview">{% if (file.thumbnail_url) { %}_x000D_
{% } %}</td>_x000D_
<td class="name">_x000D_
</td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td colspan="2"></td>_x000D_
{% } %}_x000D_
<td class="delete">_x000D_
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
<i class="icon-trash icon-white"></i>_x000D_
</button>_x000D_
<input type="checkbox" name="delete" value="1">_x000D_
</td>_x000D_
</tr>_x000D_
{% } %}_x000D_
</script>``````
_x000D_
_x000D_
_x000D_

At first I used the `:cdata` to convert (from html2haml), it doesn't work properly (Delete button can't remove relevant component in callback).

_x000D_
_x000D_
``````<script id='template-download' type='text/x-tmpl'>_x000D_
<![CDATA[_x000D_
{% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
{% if (file.error) { %}_x000D_
<td></td>_x000D_
<td class="name"><span>{%=file.name%}</span></td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
{% } else { %}_x000D_
<td class="preview">{% if (file.thumbnail_url) { %}_x000D_
{% } %}</td>_x000D_
<td class="name">_x000D_
</td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td colspan="2"></td>_x000D_
{% } %}_x000D_
<td class="delete">_x000D_
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
<i class="icon-trash icon-white"></i>_x000D_
</button>_x000D_
<input type="checkbox" name="delete" value="1">_x000D_
</td>_x000D_
</tr>_x000D_
{% } %}_x000D_
]]>_x000D_
</script>``````
_x000D_
_x000D_
_x000D_

So I use `:plain` filter:

_x000D_
_x000D_
``````%script#template-download{:type => "text/x-tmpl"}_x000D_
:plain_x000D_
{% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
{% if (file.error) { %}_x000D_
<td></td>_x000D_
<td class="name"><span>{%=file.name%}</span></td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
{% } else { %}_x000D_
<td class="preview">{% if (file.thumbnail_url) { %}_x000D_
{% } %}</td>_x000D_
<td class="name">_x000D_
</td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td colspan="2"></td>_x000D_
{% } %}_x000D_
<td class="delete">_x000D_
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
<i class="icon-trash icon-white"></i>_x000D_
</button>_x000D_
<input type="checkbox" name="delete" value="1">_x000D_
</td>_x000D_
</tr>_x000D_
{% } %}``````
_x000D_
_x000D_
_x000D_

The converted result is exactly the same as the original.

So `:plain` filter in this senario fits my need.

:plain Does not parse the filtered text. This is useful for large blocks of text without HTML tags, when you don’t want lines starting with . or - to be parsed.

For more detail, please refer to haml.info

### Clear terminal in Python

This function works in gnome-terminal because, by default, it recognizes ANSI escape sequences. It gives you a CLEAN PROMPT `rows_max` distance from the bottom of the terminal, but also precisely from where it was called. Gives you complete control over how much to clear.

``````def clear(rows=-1, rows_max=None, *, calling_line=True, absolute=None,
store_max=[]):
"""clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up"""
from os import linesep
if rows_max and rows_max != -1:
store_max[:] = [rows_max, False]
elif not store_max or store_max[1] or rows_max == -1 or absolute:
try:
from shutil import get_terminal_size
columns_max, rows_max = get_terminal_size()
except ImportError:
columns_max, rows_max = 80, 24
if absolute is None:
store_max[:] = [rows_max, True]
if store_max:
if rows == -1:
rows = store_max[0]
elif isinstance(rows, float):
rows = round(store_max[0] * rows)
if rows > store_max[0] - 2:
rows = store_max[0] - 2
if absolute is None:
s = ('\033[1A' + ' ' * 30 if calling_line else '') + linesep * rows
else:
s = '\033[{}A'.format(absolute + 2) + linesep
if absolute > rows_max - 2:
absolute = rows_max - 2
s += (' ' * columns_max + linesep) * absolute + ' ' * columns_max
rows = absolute
print(s + '\033[{}A'.format(rows + 1))
``````

Implementation:

``````clear() # Clear all, TRIES to automatically get terminal height
clear(800, 24) # Clear all, set 24 as terminal (max) height
clear(12) # Clear half of terminal below if 24 is its height
clear(1000) # Clear to terminal height - 2 (24 - 2)
clear(0.5) # float factor 0.0 - 1.0 of terminal height (0.5 * 24 = 12)
clear() # Clear to rows_max - 2 of user given rows_max (24 - 2)
clear(0, 14) # Clear line, reset rows_max to half of 24 (14-2)
clear(0) # Just clear the line
clear(0, -1) # Clear line, restore auto-determining rows_max
clear(calling_line=False) # Clear all, don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up
``````

Parameters: `rows` is the number of clear text rows to add between prompt and bottom of terminal, pushing everything up. `rows_max` is the height of the terminal (or max clearing height) in text rows, and only needs to be set once, but can be reset at any time. `*,` in the third parameter position means all following parameters are keyword only (e.g., clear(absolute=5)). `calling_line=True` (default) works better in Interactive mode. `calling_line=False` works better for text-based, terminal applications. `absolute` was added to try to fix glitchy gap problems in Interactive mode after reducing size of terminal, but can also be used for terminal applications. `store_max` is just for secret, "persistent" storage of `rows_max` value; don't explicitly use this parameter. (When an argument is not passed for `store_max`, changing the list contents of `store_max` changes this parameter's default value. Hence, persistent storage.)

Portability: Sorry, this doesn't work in IDLE, but it works >> VERY COOL << in Interactive mode in a terminal (console) that recognizes ANSI escape sequences. I only tested this in Ubuntu 13.10 using Python 3.3 in gnome-terminal. So I can only assume portability is dependant upon Python 3.3 (for the `shutil.get_terminal_size()` function for BEST results) and ANSI recognition. The `print(...)` function is Python 3. I also tested this with a simple, text-based, terminal Tic Tac Toe game (application).

For use in Interactive mode: First copy and paste the `copy(...)` function in Interactive mode and see if it works for you. If so, then put the above function into a file named clear.py . In the terminal start python, with 'python3'. Enter:

``````>>> import sys
>>> sys.path
['', '/usr/lib/python3.3', ...
``````

Now drop the clear.py file into one of the `path` directories listed so that Python can find it (don't overwrite any existing files). To easily use from now on:

``````>>> from clear import clear
>>> clear()
>>> print(clear.__doc__)
clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up
``````

For use in a terminal application: Put the `copy(...)` function into a file named clear.py in the same folder with your main.py file. Here is a working abstract (skeleton) example from a Tic Tac Toe game application (run from terminal prompt: python3 tictactoe.py):

``````from os import linesep

class TicTacToe:
def __init__(self):
# Clear screen, but not calling line
try:
from clear import clear
self.clear = clear
self.clear(calling_line=False)
except ImportError:
self.clear = False
self.rows = 0    # Track printed lines to clear

# ...
self.moves = [' '] * 9

def do_print(self, *text, end=linesep):
text = list(text)
for i, v in enumerate(text[:]):
text[i] = str(v)
text = ' '.join(text)
print(text, end=end)
self.rows += text.count(linesep) + 1

def show_board(self):
if self.clear and self.rows:
self.clear(absolute=self.rows)
self.rows = 0
self.do_print('Tic Tac Toe')
self.do_print('''   |   |
{6} | {7} | {8}
|   |
-----------
|   |
{3} | {4} | {5}
|   |
-----------
|   |
{0} | {1} | {2}
|   |'''.format(*self.moves))

def start(self):
self.show_board()
ok = input("Press <Enter> to continue...")
self.moves = ['O', 'X'] * 4 + ['O']
self.show_board()
ok = input("Press <Enter> to close.")

if __name__ == "__main__":
TicTacToe().start()
``````

Explanation: `do_print(...)` on line 19 is a version of `print(...)` needed to keep track of how many new lines have been printed (`self.rows`). Otherwise, you would have to `self.rows += 1` all over the place where `print(...)` is called throughout the entire program. So each time the board is redrawn by calling `show_board()` the previous board is cleared out and the new board is printed exactly where it should be. Notice `self.clear(calling_line=False)` on line 9 basically pushes everything up RELATIVE to the bottom of the terminal, but does not clear the original calling line. In contrast, `self.clear(absolute=self.rows)` on line 29 absolutely clears out everything `self.rows` distance upward, rather than just pushing everything upward relative to the bottom of the terminal.

Ubuntu users with Python 3.3: Put `#!/usr/bin/env python3` on the very first line of the tictactoe.py file. Right click on the tictactoe.py file => Properties => Permissions tab => Check Execute: Allow executing file as program. Double click on the file => Click Run in Terminal button. If an open terminal's current directory is that of the tictactoe.py file, you can also start the file with `./tictactoe.py`.

### Hex-encoded String to Byte Array

Java SE 6 or Java EE 5 provides a method to do this now so there is no need for extra libraries.

The method is DatatypeConverter.parseHexBinary

In this case it can be used as follows:

``````String str = "9B7D2C34A366BF890C730641E6CECF6F";
byte[] bytes = DatatypeConverter.parseHexBinary(str);
``````

The class also provides type conversions for many other formats that are generally used in XML.

### Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I also received this error and tried everything I could find online and it wouldn't go away. In the end, I just downgraded MVC from 5.2.3 to 4.0.40804. I don't like this solution because eventually I'll need to use MVC 5, but it works for now. Hope this helps others.

### Creating a "Hello World" WebSocket example

(Posted answer on behalf of the OP).

I am able to send data now. This is my new version of the program thanks to your answers and the code of @Maksims Mihejevs.

#### Server

``````using System;
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography;

namespace ConsoleApplication1
{
class Program
{
static Socket serverSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

static void Main(string[] args)
{
serverSocket.Listen(128);
serverSocket.BeginAccept(null, 0, OnAccept, null);
}

private static void OnAccept(IAsyncResult result)
{
byte[] buffer = new byte[1024];
try
{
Socket client = null;
if (serverSocket != null && serverSocket.IsBound)
{
client = serverSocket.EndAccept(result);
// write received data to the console

}
if (client != null)
{
/* Handshaking and managing ClientSocket */

.Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
.Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
.Trim();

// key should now equal dGhlIHNhbXBsZSBub25jZQ==
var test1 = AcceptKey(ref key);

var newLine = "\r\n";

var response = "HTTP/1.1 101 Switching Protocols" + newLine
+ "Sec-WebSocket-Accept: " + test1 + newLine + newLine
//+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
//+ "Sec-WebSocket-Version: 13" + newLine
;

// which one should I use? none of them fires the onopen method
client.Send(System.Text.Encoding.UTF8.GetBytes(response));

var i = client.Receive(buffer); // wait for client to send a message

// once the message is received decode it in different formats
Console.WriteLine(Convert.ToBase64String(buffer).Substring(0, i));

Console.WriteLine("\n\nPress enter to send data to client");

var subA = SubArray<byte>(buffer, 0, i);
client.Send(subA);
Thread.Sleep(10000);//wait for message to be send

}
}
catch (SocketException exception)
{
throw exception;
}
finally
{
if (serverSocket != null && serverSocket.IsBound)
{
serverSocket.BeginAccept(null, 0, OnAccept, null);
}
}
}

public static T[] SubArray<T>(T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}

private static string AcceptKey(ref string key)
{
string longKey = key + guid;
byte[] hashBytes = ComputeHash(longKey);
return Convert.ToBase64String(hashBytes);
}

static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
private static byte[] ComputeHash(string str)
{
return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
}
}
}
``````

#### JavaScript:

``````<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script type="text/javascript">
function connect() {
var ws = new WebSocket("ws://localhost:8080/service");
ws.onopen = function () {
ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
};

ws.onmessage = function (evt) {
};
ws.onclose = function () {
// websocket is closed.
};
};

</script>
<body style="font-size:xx-large" >
<div>
</body>
</html>
``````

When I run that code I am able to send and receive data from both the client and the server. The only problem is that the messages are encrypted when they arrive to the server. Here are the steps of how the program runs:

Note how the message from the client is encrypted.

### Using Bootstrap Tooltip with AngularJS

You can create a simple directive like this:

``````angular.module('myApp',[])
.directive('myTooltip', function(){
return {
restrict: 'A',
element.tooltip();
}
}
});
``````

``````<button my-tooltip></button>
``````

### Clear contents and formatting of an Excel cell with a single command

Use the `.Clear` method.

``````Sheets("Test").Range("A1:C3").Clear
``````

MSDN documentation here.

### How to implement Rate It feature in Android App

As you see from the other post you have linked, there isn't a way for the app to know if the user has left a review or not. And for good reason.

Think about it, if an app could tell if the user has left a review or not, the developer could restrict certain features that would only be unlocked if the user leaves a 5/5 rating. This would lead the other users of Google Play to not trust the reviews and would undermine the rating system.

The alternative solutions I have seen is that the app reminds the user to submit a rating whenever the app is opened a specific number of times, or a set interval. For example, on every 10th time the app is opened, ask the user to leave a rating and provide a "already done" and "remind me later" button. Keep showing this message if the user has chosen to remind him/her later. Some other apps developers show this message with an increasing interval (like, 5, 10, 15nth time the app is opened), because if a user hasn't left a review on the, for example, 100th time the app was opened, it's probably likely s/he won't be leaving one.

This solution isn't perfect, but I think it's the best you have for now. It does lead you to trust the user, but realize that the alternative would mean a potentially worse experience for everyone in the app market.

### Nested ng-repeat

Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:

``````<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>
``````

### How to remove all leading zeroes in a string

``````(string)((int)"00000234892839")
``````

### Properly close mongoose's connection once you're done

You can close the connection with

``````mongoose.connection.close()
``````

### Array.sort() doesn't sort numbers correctly

The default sort for arrays in Javascript is an alphabetical search. If you want a numerical sort, try something like this:

``````var a = [ 1, 100, 50, 2, 5];
a.sort(function(a,b) { return a - b; });
``````

### How to remove spaces from a string using JavaScript?

_x000D_
_x000D_
``````var str = '/var/www/site/Brand new document.docx';

document.write( str.replace(/\s\/g, '') );

----------``````
_x000D_
_x000D_
_x000D_

### Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

``````=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
``````

For Excel 2003:

``````=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
``````

Note, that

• I'm using `List!A:C` in `VLOOKUP` and returns value from column ? `3`
• I'm using 4th argument for `VLOOKUP` equals to `FALSE`, in that case `VLOOKUP` will only find an exact match, and the values in the first column of `List!A:C` do not need to be sorted (opposite to case when you're using `TRUE`).

### What database does Google use?

As others have mentioned, Google uses a homegrown solution called BigTable and they've released a few papers describing it out into the real world.

The Apache folks have an implementation of the ideas presented in these papers called HBase. HBase is part of the larger Hadoop project which according to their site "is a software platform that lets one easily write and run applications that process vast amounts of data." Some of the benchmarks are quite impressive. Their site is at http://hadoop.apache.org.

### List comprehension on a nested list?

Here is how you would do this with a nested list comprehension:

``````[[float(y) for y in x] for x in l]
``````

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use `[float(y) for x in l for y in x]`.

### if else in a list comprehension

``````[x+1 if x >= 45 else x+5 for x in l]
``````

And for a reward, here is the comment, I wrote to remember this the first time I did this error:

Python's conditional expression is `a if C else b` and can't be used as:

``````[a for i in items if C else b]
``````

The right form is:

``````[a if C else b for i in items]
``````

Even though there is a valid form:

``````[a for i in items if C]
``````

But that isn't the same as that is how you filter by `C`, but they can be combined:

``````[a if tC else b for i in items if fC]
``````

### How do you write a migration to rename an ActiveRecord model and its table in Rails?

In Rails 4 all I had to do was the def change

``````def change
rename_table :old_table_name, :new_table_name
end
``````

And all of my indexes were taken care of for me. I did not need to manually update the indexes by removing the old ones and adding new ones.

And it works using the change for going up or down in regards to the indexes as well.

### How to use function srand() with time.h?

If you chose to `srand`, it is a good idea to then call `rand()` at least once before you use it, because it is a kind of horrible primitive psuedo-random generator. See Stack Overflow question Why does rand() % 7 always return 0?.

``````srand(time(NULL));
rand();
//Now use rand()
``````

If available, either `random` or `arc4rand` would be better.

### Disable Enable Trigger SQL server for a table

``````ALTER TABLE table_name DISABLE TRIGGER tr_name

ALTER TABLE table_name ENABLE TRIGGER tr_name
``````

### How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

If you use mod_rewrite to hide the extension of your scripts, or if you just like pretty URLs that end in /, then you might want to approach this from the other direction. Tell nginx to let anything with a non-static extension to go through to apache. For example:

``````location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)\$
{
root   /path/to/static-content;
}

location ~* ^!.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)\$ {
if (!-f \$request_filename) {
return 404;
}
proxy_pass http://127.0.0.1:8080;
}
``````

I found the first part of this snippet over at: http://code.google.com/p/scalr/wiki/NginxStatic

### detect key press in python?

Use this code for find the which key pressed

``````from pynput import keyboard

def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))

def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False

# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
``````

### Dark Theme for Visual Studio 2010 With Productivity Power Tools

1. Install the Visual Studio Color Theme Editor extension:
2. Make your own color scheme or try: The Dark Expression Blend Color Theme (preview below)
3. Once you have that, you'll want schemes for the text editor as well. This site has several, including the VS2012 "dark" theme implemented for VS2010.

### How can I change the color of AlertDialog title and the color of the line under it

check this is useful for you...

``````public void setCustomTitle (View customTitleView)
``````

you get detail from following link.

CustomDialog.java

``````Dialog alert = new Dialog(this);
``````

title.xml

``````<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000"
android:textAppearance="?android:attr/textAppearanceLarge" />

<ImageView
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_marginTop="5dp"
android:background="#00ff00"
/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#775500"
android:textAppearance="?android:attr/textAppearanceLarge" />
``````

### Concatenate a vector of strings/character

For `sdata`:

``````gsub(", ","",toString(sdata))
``````

For a vector of integers:

``````gsub(", ","",toString(c(1:10)))
``````

### Jquery - How to make \$.post() use contentType=application/json?

I ended up adding the following method to jQuery in my script:

``````jQuery["postJSON"] = function( url, data, callback ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
callback = data;
data = undefined;
}

return jQuery.ajax({
url: url,
type: "POST",
contentType:"application/json; charset=utf-8",
dataType: "json",
data: data,
success: callback
});
};
``````

And to use it

``````\$.postJSON('http://url', {data: 'goes', here: 'yey'}, function (data, status, xhr) {
});
``````

This was done by simply copying the code of "get" and "post" from the original JQuery sources and hardcoding a few parameters to force a JSON POST.

Thanks!

### How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

``````font-family:    Arial, Helvetica, sans-serif;
``````

### Concrete Javascript Regex for Accented Characters (Diacritics)

Which of these three approaches is most suited for the task?

Depends on the task :-) To match exactly all Latin characters and their accented versions, the Unicode ranges probably provide the best solution. They might be extended to all non-whitespace characters, which could be done using the `\S` character class.

I'm forcing a field in a UI to match the format: `last_name, first_name` (last [comma space] first)

The most basic problem I'm seeing here are not diacritics, but whitespaces. There are a few names that consist of multiple words, e.g. for titles. So you should go with the most generic, that is allowing everything but the comma that distinguishes first from last name:

``````/[^,]+,\s[^,]+/
``````

But your second solution with the `.` character class is just as fine, you only might need to care about multiple commata then.

### Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

I had similar issue on Windows 7. At first I setup M2, M2_HOME under User variable but when I echoed %PATH% , I did not see maven bin directory listed under PATH. Then I setup M2, M2_HOME under system variable and it worked.

### How to close TCP and UDP ports via windows command line

If you're runnning on Windows 8,`Windows Server 2012 or above with PowerShell v4 of above installed, you can use the below script. This finds the processes associated with the port & terminates them.

#### Code

``````#which port do you want to kill
[int]\$portOfInterest = 80

#fetch the process ids related to this port
[int[]]\$processId = Get-NetTCPConnection -LocalPort \$portOfInterest |
Select-Object -ExpandProperty OwningProcess -Unique |
Where-Object {\$_ -gt 0}

#kill those processes
Stop-Process -Id \$processId
``````

### How to set a background image in Xcode using swift?

``````override func viewDidLoad() {

let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "bg_image")
backgroundImage.contentMode = UIViewContentMode.scaleAspectfill
self.view.insertSubview(backgroundImage, at: 0)

}
``````

Updated at 20-May-2020:

The code snippet above doesn't work well after rotating the device. Here is the solution which can make the image stretch according to the screen size(after rotating):

``````class ViewController: UIViewController {

var imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.image = UIImage(named: "bg_image")
imageView.contentMode = .scaleToFill
return imageView
}()

view.insertSubview(imageView, at: 0)
NSLayoutConstraint.activate([
imageView.topAnchor.constraint(equalTo: view.topAnchor),
imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
``````

### SQL select statements with multiple tables

Like that:

``````SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299'
``````

### Change URL and redirect using jQuery

``````var temp="/yourapp/";
\$(location).attr('href','http://abcd.com'+temp);
``````

Try this... used as an alternative

### Why does instanceof return false for some literals?

For me the confusion caused by

``````"str".__proto__ // #1
=> String
``````

So `"str" istanceof String` should return `true` because how istanceof works as below:

``````"str".__proto__ == String.prototype // #2
=> true
``````

Results of expression #1 and #2 conflict each other, so there should be one of them wrong.

#1 is wrong

I figure out that it caused by the `__proto__` is non standard property, so use the standard one:`Object.getPrototypeOf`

``````Object.getPrototypeOf("str") // #3
=> TypeError: Object.getPrototypeOf called on non-object
``````

Now there's no confusion between expression #2 and #3

### What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

• RESTful services use REST architectural style,
• RESTless services use SOAP protocol.

• RESTful services use URL to expose business logic,
• RESTless services use the service interface to expose business logic.

3. Security

• RESTful inherits security from the underlying transport protocols,
• RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

• RESTful supports various data formats such as HTML, JSON, text, etc,
• RESTless supports XML format.

5. Flexibility

• RESTful is easier and flexible,
• RESTless is not as easy and flexible.

6. Bandwidth

• RESTful services consume less bandwidth and resource,
• RESTless services consume more bandwidth and resources.

### Get url parameters from a string in .NET

@Andrew and @CZFox

I had the same bug and found the cause to be that parameter one is in fact: `http://www.example.com?param1` and not `param1` which is what one would expect.

By removing all characters before and including the question mark fixes this problem. So in essence the `HttpUtility.ParseQueryString` function only requires a valid query string parameter containing only characters after the question mark as in:

``````HttpUtility.ParseQueryString ( "param1=good&param2=bad" )
``````

My workaround:

``````string RawUrl = "http://www.example.com?param1=good&param2=bad";
int index = RawUrl.IndexOf ( "?" );
if ( index > 0 )
RawUrl = RawUrl.Substring ( index ).Remove ( 0, 1 );

Uri myUri = new Uri( RawUrl, UriKind.RelativeOrAbsolute);
string param1 = HttpUtility.ParseQueryString( myUri.Query ).Get( "param1" );`
``````

### Concept of void pointer in C programming

You can easily print a void printer

``````int p=15;
void *q;
q=&p;
printf("%d",*((int*)q));
``````

### Extract first item of each sublist

Using list comprehension:

``````>>> lst = [['a','b','c'], [1,2,3], ['x','y','z']]
>>> lst2 = [item[0] for item in lst]
>>> lst2
['a', 1, 'x']
``````

### Ripple effect on Android Lollipop CardView

The ripple effect was omitted in the appcompat support library which is what you're using. If you want to see the ripple use the Android L version and test it on an Android L device. Per the AppCompat v7 site:

"Why are there no ripples on pre-Lollipop? A lot of what allows RippleDrawable to run smoothly is Android 5.0’s new RenderThread. To optimize for performance on previous versions of Android, we've left RippleDrawable out for now."

### How to use variables in SQL statement in Python?

http://www.amk.ca/python/writing/DB-API.html

Be careful when you simply append values of variables to your statements: Imagine a user naming himself `';DROP TABLE Users;'` -- That's why you need to use sql escaping, which Python provides for you when you use the cursor.execute in a decent manner. Example in the url is:

``````cursor.execute("insert into Attendees values (?, ?, ?)", (name,
seminar, paid) )
``````

### Get single listView SelectedItem

Usually `SelectedItems` returns either a collection, an array or an `IQueryable`.

Either way you can access items via the index as with an array:

``````String text = listView1.SelectedItems[0].Text;
``````

By the way, you can save an item you want to look at into a variable, and check its structure in the locals after setting a breakpoint.

### How to add image for button in android?

You should try something like this

``````    <Button
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/qrcode"/>
``````

the `android:background="@drawable/qrcode"` will do it

### Why are my PowerShell scripts not running?

I was able to bypass this error by invoking PowerShell like this:

``````powershell -executionpolicy bypass -File .\MYSCRIPT.ps1
``````

That is, I added the `-executionpolicy bypass` to the way I invoked the script.

This worked on Windows 7 Service Pack 1. I am new to PowerShell, so there could be caveats to doing that that I am not aware of.

[Edit 2017-06-26] I have continued to use this technique on other systems including Windows 10 and Windows 2012 R2 without issue.

Here is what I am using now. This keeps me from accidentally running the script by clicking on it. When I run it in the scheduler I add one argument: "scheduler" and that bypasses the prompt.

This also pauses the window at the end so I can see the output of PowerShell.

``````if NOT "%1" == "scheduler" (
@echo looks like you started the script by clicking on it.
@echo press space to continue or control C to exit.
pause
)

C:
cd \Scripts

powershell -executionpolicy bypass -File .\rundps.ps1

set psexitcode=%errorlevel%

if NOT "%1" == "scheduler" (
@echo Powershell finished.  Press space to exit.
pause
)

exit /b %psexitcode%
``````

### Access nested dictionary items via a list of keys?

Extending @DomTomCat and others' approach, these functional (ie, return modified data via deepcopy without affecting the input) setter and mapper works for nested `dict` and `list`.

setter:

``````def set_at_path(data0, keys, value):
data = deepcopy(data0)
if len(keys)>1:
if isinstance(data,dict):
return {k:(set_by_path(v,keys[1:],value) if k==keys[0] else v) for k,v in data.items()}
if isinstance(data,list):
return [set_by_path(x[1],keys[1:],value) if x[0]==keys[0] else x[1] for x in enumerate(data)]
else:
data[keys[-1]]=value
return data
``````

mapper:

``````def map_at_path(data0, keys, f):
data = deepcopy(data0)
if len(keys)>1:
if isinstance(data,dict):
return {k:(map_at_path(v,keys[1:],f) if k==keys[0] else v) for k,v in data.items()}
if isinstance(data,list):
return [map_at_path(x[1],keys[1:],f) if x[0]==keys[0] else x[1] for x in enumerate(data)]
else:
data[keys[-1]]=f(data[keys[-1]])
return data
``````

### How to export datagridview to excel using vb.net?

Excel Method

This method is different than many you will see. Others use a loop to write each cell and write the cells with text data type.

This method creates an object array from a `DataTable` or `DataGridView` and then writes the array to Excel. This means I can write to Excel without a loop and retain data types.

I extracted this from my library and I think I changed it enough to work with this code only, but more minor tweaking might be necessary. If you get errors just let me know and I'll correct them for you. Normally, I create an instance of my class and call these methods. If you would like to use my library then use this link to download it and if you need help just let me know.
https://zomp.co/Files.aspx?ID=zExcel

After copying the code to your solution you will use it like this.

`WriteDataGrid("Sheet1", grid)`

To open your file after exporting use this line

`System.Diagnostics.Process.Start("The location and filename of your file")`

In the `WriteArray` method you'll want to change the line that saves the workbook to where you want to save it. Probably makes sense to add this as a parameter.

`wb.SaveAs("C:\MyWorkbook.xlsx")`

``````Public Function WriteArray(Sheet As String, ByRef ObjectArray As Object(,)) As String
Try
Dim xl As Excel.Application = New Excel.Application
Dim wb As Excel.Workbook = xl.Workbooks.Add()
Dim ws As Excel.Worksheet = wb.Worksheets.Add()
ws.Name = Sheet
Dim range As Excel.Range = ws.Range("A1").Resize(ObjectArray.GetLength(0), ObjectArray.GetLength(1))
range.Value = ObjectArray

range = ws.Range("A1").Resize(1, ObjectArray.GetLength(1) - 1)

range.Interior.Color = RGB(0, 70, 132)  'Con-way Blue
range.Font.Color = RGB(Drawing.Color.White.R, Drawing.Color.White.G, Drawing.Color.White.B)
range.Font.Bold = True
range.WrapText = True

range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter

range.Application.ActiveWindow.SplitColumn = 0
range.Application.ActiveWindow.SplitRow = 1
range.Application.ActiveWindow.FreezePanes = True

wb.SaveAs("C:\MyWorkbook.xlsx")
wb.CLose()
xl.Quit()
xl = Nothing
wb = Nothing
ws  = Nothing
range = Nothing
ReleaseComObject(xl)
ReleaseComObject(wb)
ReleaseComObject(ws)
ReleaseComObject(range)

Return ""
Catch ex As Exception
Return "WriteArray()" & Environment.NewLine & Environment.NewLine & ex.Message
End Try
End Function

Public Function WriteDataGrid(SheetName As String, ByRef dt As DataGridView) As String
Try
Dim l(dt.Rows.Count + 1, dt.Columns.Count) As Object
For c As Integer = 0 To dt.Columns.Count - 1
Next

For r As Integer = 1 To dt.Rows.Count
For c As Integer = 0 To dt.Columns.Count - 1
l(r, c) = dt.Rows(r - 1).Cells(c)
Next
Next

Dim errors As String = WriteArray(SheetName, l)
If errors <> "" Then
Return errors
End If

Return ""
Catch ex As Exception
Return "WriteDataGrid()" & Environment.NewLine & Environment.NewLine & ex.Message
End Try
End Function

Public Function WriteDataTable(SheetName As String, ByRef dt As DataTable) As String
Try
Dim l(dt.Rows.Count + 1, dt.Columns.Count) As Object
For c As Integer = 0 To dt.Columns.Count - 1
l(0, c) = dt.Columns(c).ColumnName
Next

For r As Integer = 1 To dt.Rows.Count
For c As Integer = 0 To dt.Columns.Count - 1
l(r, c) = dt.Rows(r - 1).Item(c)
Next
Next

Dim errors As String = WriteArray(SheetName, l)
If errors <> "" Then
Return errors
End If

Return ""
Catch ex As Exception
Return "WriteDataTable()" & Environment.NewLine & Environment.NewLine & ex.Message
End Try
End Function
``````

I actually don't use this method in my Database program because it's a slow method when you have a lot of rows/columns. I instead create a CSV from the DataGridView. Writing to Excel with Excel Automation is only useful if you need to format the data and cells otherwise you should use CSV. You can use the code after the image for CSV export.

CSV Method

``````Private Sub DataGridToCSV(ByRef dt As DataGridView, Qualifier As String)
Dim TempDirectory As String = "A temp Directory"
System.IO.Directory.CreateDirectory(TempDirectory)
Dim oWrite As System.IO.StreamWriter
Dim file As String = System.IO.Path.GetRandomFileName & ".csv"
oWrite = IO.File.CreateText(TempDirectory & "\" & file)

Dim CSV As StringBuilder = New StringBuilder()

Dim i As Integer = 1
Dim CSVHeader As StringBuilder = New StringBuilder()
For Each c As DataGridViewColumn In dt.Columns
If i = 1 Then
Else
End If
i += 1
Next

oWrite.Flush()

For r As Integer = 0 To dt.Rows.Count - 1

Dim CSVLine As StringBuilder = New StringBuilder()
Dim s As String = ""
For c As Integer = 0 To dt.Columns.Count - 1
If c = 0 Then
'CSVLine.Append(Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier)
s = s & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier
Else
'CSVLine.Append("," & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier)
s = s & "," & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier
End If

Next
oWrite.WriteLine(s)
oWrite.Flush()
'CSV.AppendLine(CSVLine.ToString())
'CSVLine.Clear()
Next

'oWrite.Write(CSV.ToString())

oWrite.Close()
oWrite = Nothing

System.Diagnostics.Process.Start(TempDirectory & "\" & file)

GC.Collect()

End Sub
``````

### Initializing IEnumerable<string> In C#

`IEnumerable<T>` is an interface. You need to initiate with a concrete type (that implements `IEnumerable<T>`). Example:

``````IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3"};
``````

### What are Keycloak's OAuth2 / OpenID Connect endpoints?

You can also see this information by going into Admin Console -> Realm Settings -> Clicking the hyperlink on the Endpoints field.

### How to create a delay in Swift?

Try the following implementation in Swift 3.0

``````func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
completion()
}
}
``````

Usage

``````delayWithSeconds(1) {
//Do something
}
``````

### getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

Override service method like this:

``````protected void service(HttpServletRequest request, HttpServletResponse   response) throws ServletException, IOException {
doPost(request, response);
}
``````

And Voila!

### How to browse for a file in java swing library?

I ended up using this quick piece of code that did exactly what I needed:

``````final JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);

try {
// Open an input stream
}
``````

### what is the difference between const_iterator and iterator?

Performance wise there is no difference. The only purpose of having `const_iterator` over `iterator` is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

``````std::vector<int> integers{ 3, 4, 56, 6, 778 };
``````

If we were to read & write the members of a container we will use iterator:

``````for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
{*it = 4;  std::cout << *it << std::endl; }
``````

If we were to only read the members of the container `integers` you might wanna use const_iterator which doesn't allow to write or modify members of container.

``````for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
{ cout << *it << endl; }
``````

NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

### Enter key pressed event handler

You can also use PreviewKeyDown in WPF:

``````<TextBox PreviewKeyDown="EnterClicked" />
``````

or in C#:

``````myTextBox.PreviewKeyDown += EnterClicked;
``````

And then in the attached class:

``````void EnterClicked(object sender, KeyEventArgs e) {
if(e.Key == Key.Return) {
DoSomething();
e.Handled = true;
}
}
``````

### What is the recommended way to make a numeric TextField in JavaFX?

The `TextInput` has a `TextFormatter` which can be used to format, convert and limit the types of text that can be input.

The `TextFormatter` has a filter which can be used to reject input. We need to set this to reject anything that's not a valid integer. It also has a converter which we need to set to convert the string value to an integer value which we can bind later on.

Lets create a reusable filter:

``````public class IntegerFilter implements UnaryOperator<TextFormatter.Change> {
private final static Pattern DIGIT_PATTERN = Pattern.compile("\\d*");

@Override
public Change apply(TextFormatter.Change aT) {
return DIGIT_PATTERN.matcher(aT.getText()).matches() ? aT : null;
}
}
``````

The filter can do one of three things, it can return the change unmodified to accept it as it is, it can alter the change in some way it deems fit or it can return `null` to reject the change all together.

We will use the standard `IntegerStringConverter` as a converter.

Putting it all together we have:

``````TextField textField = ...;

TextFormatter<Integer> formatter = new TextFormatter<>(
new IntegerStringConverter(), // Standard converter form JavaFX
defaultValue,
new IntegerFilter());
formatter.valueProperty().bindBidirectional(myIntegerProperty);

textField.setTextFormatter(formatter);
``````

If you want don't need a reusable filter you can do this fancy one-liner instead:

``````TextFormatter<Integer> formatter = new TextFormatter<>(
new IntegerStringConverter(),
defaultValue,
c -> Pattern.matches("\\d*", c.getText()) ? c : null );
``````

### How do I parse a YAML file in Ruby?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in `some.yml`, then this:

``````require 'yaml'
puts thing.inspect
``````

gives me

``````{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}
``````

### How to set base url for rest in spring boot?

For those who use YAML configuration(application.yaml).

Note: this works only for `Spring Boot 2.x.x`

``````server:
servlet:
contextPath: /api

``````

If you are still using `Spring Boot 1.x`

``````server:
contextPath: /api
``````

### Force IE8 Into IE7 Compatiblity Mode

There is an HTTP header you can set that will force IE8 to use IE7-compatibility mode.

### What are the aspect ratios for all Android phone and tablet devices?

The Sony Tablet P is old, but it can switch between 32:15 and 32:30 for each app in landscape mode, and vice-versa in portrait mode, so that's a minimum range to aim for

### Favicon: .ico or .png / correct tags?

I know this is an old question.

Here's another option - attending to different platform requirements - Source

``````<link rel='shortcut icon' type='image/vnd.microsoft.icon' href='/favicon.ico'> <!-- IE -->
<link rel='apple-touch-icon' type='image/png' href='/icon.57.png'> <!-- iPhone -->
<link rel='apple-touch-icon' type='image/png' sizes='114x114' href='/icon.114.png'> <!-- iPhone4 -->
<link rel='icon' type='image/png' href='/icon.114.png'> <!-- Opera Speed Dial, at least 144×114 px -->
``````

This is the broadest approach I have found so far.

UPDATE May 27, 2018: As expected, time goes by and things change. But there's good news too. I found a tool called Real Favicon Generator that generates all the required lines for the icon to work on all modern browsers and platforms. It doesn't handle backwards compatibility though.

### Is there any way to debug chrome in any IOS device

You can't directly debug Chrome for iOS due to restrictions on the published `WKWebView` apps, but there are a few options already discussed in other SO threads:

1. If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.

2. WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.

3. You could try and create a simple `WKWebView` browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.

There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to `WKWebView`, Chrome for iOS would be debuggable.

Update January 2018:

Since my answer back in 2016, some work has been done to improve things.

There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.

Check out the getting started guide in the repo, which is quite detailed.

If you are interesting, you can read up on the background and architecture here.

### Is it possible to set UIView border properties from interface builder?

``````self.YourViewName.layer.cornerRadius = 15
``````

It will work fine.

### How do I find ' % ' with the LIKE operator in SQL Server?

Try this:

``````declare @var char(3)
set @var='[%]'
``````

You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _

### How to use android emulator for testing bluetooth application?

need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux instead of Other.

After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.

Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.

Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.

In VirtualBox screen, go to Devices>USB devices. Select your dongle.

Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.

Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.

Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .

Source

### php date validation

This function working well,

``````function validateDate(\$date, \$format = 'm/d/Y'){
\$d = DateTime::createFromFormat(\$format, \$date);
return \$d && \$d->format(\$format) === \$date;
}
``````

### What is a word boundary in regex, does \b match hyphen '-'?

In the course of learning regular expression, I was really stuck in the metacharacter which is `\b`. I indeed didn't comprehend its meaning while I was asking myself "what it is, what it is" repetitively. After some attempts by using the website, I watch out the pink vertical dashes at the every beginning of words and at the end of words. I got it its meaning well at that time. It's now exactly word(`\w`)-boundary.

My view is merely to immensely understanding-oriented. Logic behind of it should be examined from another answers.

### How do you get the magnitude of a vector in Numpy?

If you are worried at all about speed, you should instead use:

``````mag = np.sqrt(x.dot(x))
``````

Here are some benchmarks:

``````>>> import timeit
>>> timeit.timeit('np.linalg.norm(x)', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0450878
>>> timeit.timeit('np.sqrt(x.dot(x))', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0181372
``````

EDIT: The real speed improvement comes when you have to take the norm of many vectors. Using pure numpy functions doesn't require any for loops. For example:

``````In [1]: import numpy as np

In [2]: a = np.arange(1200.0).reshape((-1,3))

In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 4.23 ms per loop

In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 18.9 us per loop

In [5]: np.allclose([np.linalg.norm(x) for x in a],np.sqrt((a*a).sum(axis=1)))
Out[5]: True
``````

### Run function in script from command line (Node JS)

simple way:

let's say you have db.js file in a helpers directory in project structure.

now go inside helpers directory and go to node console

`````` helpers \$ node
``````

2) require db.js file

``````> var db = require("./db")
``````

``````> db.init()
``````

hope this helps

### How to reload or re-render the entire page using AngularJS

I've had a hard fight with this problem for months, and the only solution that worked for me is this:

``````var landingUrl = "http://www.ytopic.es"; //URL complete
\$window.location.href = landingUrl;
``````

### Change the icon of the exe file generated from Visual Studio 2010

I found it easier to edit the project file directly e.g. YourApp.csproj.

You can do this by modifying `ApplicationIcon` property element:

``````<ApplicationIcon>..\Path\To\Application.ico</ApplicationIcon>
``````

Also, if you create an MSI installer for your application e.g. using WiX, you can use the same icon again for display in Add/Remove Programs. See tip 5 here.

### What are my options for storing data when using React Native? (iOS and Android)

Folks above hit the right notes for storage, though if you also need to consider any PII data that needs to be stored then you can also stash into the keychain using something like https://github.com/oblador/react-native-keychain since ASyncStorage is unencrypted. It can be applied as part of the persist configuration in something like redux-persist.

### How to use the divide function in the query?

Assuming all of these columns are `int`, then the first thing to sort out is converting one or more of them to a better data type - `int` division performs truncation, so anything less than 100% would give you a result of 0:

``````select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)
from
CSPGI09_OVERSHIPMENT
``````

Here, I've mutiplied one of the numbers by `100.0` which will force the result of the calculation to be done with `float`s rather than `int`s. By choosing `100`, I'm also getting it ready to be treated as a `%`.

I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (`-` and `/`) at the same level, and so were relying on the precedence rules to define which operator applied first.

### Amazon AWS Filezilla transfer permission denied

If you're using Ubuntu then use the following:

``````sudo chown -R ubuntu /var/www/html

sudo chmod -R 755 /var/www/html
``````

### Model backing a DB Context has changed; Consider Code First Migrations

Adding this as another possible solution, because this is what fixed it in our case;

Make sure if you have multiple projects that they are using the same Entity Framework Nuget package version!.

In our case we had one project ( call if project A ) holding the EF code first context with all entities. It was this project that we were using to add migrations & update the database. However a second project ( B ) was referencing project A to make use of the context. When running this project we got the same error;

The model backing the 'MyDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

### Font Awesome & Unicode

For those who may stumble across this post, you need to set

``````font-family: FontAwesome;
``````

as a property in your CSS selector and then unicode will work fine in CSS

### How to add image to canvas

In my case, I was mistaken the function parameters, which are:

``````context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);
``````

If you expect them to be

``````context.drawImage(image, width, height);
``````

you will place the image just outside the canvas with the same effects as described in the question.

### how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character `\n` is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use `\r\n` instead, then it'll both see the line-break with only `\n` and `\r\n`, I've never had any problems using it.

Also, you should look into using a `StringBuilder` instead of concatenating the `String` in the while-loop at `BookCatalog.toString()`, it is a lot more effective. For instance:

``````public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
``````

### What's the best way to share data between activities?

Sharing data between activites example passing an email after login

"email" is the name that can be used to reference the value on the activity that's being requested

1 Code on the login page

``````Intent openLoginActivity = new Intent(getBaseContext(), Home.class);
``````

``````Bundle extras = getIntent().getExtras();
accountEmail = extras.getString("email");
``````

### Run a string as a command within a Bash script

don't put your commands in variables, just run it

``````matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
PWD=\$(pwd)
teamAComm="\$PWD/a.sh"
teamBComm="\$PWD/b.sh"
include="\$PWD/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd \$matchdir
\$serverbin include=\$include server::team_l_start = \${teamAComm} server::team_r_start=\${teamBComm} CSVSaver::save='true' CSVSaver::filename = 'out.csv'
``````

### How to add a color overlay to a background image?

You can use a pseudo element to create the overlay.

``````.testclass {
background-image: url("../img/img.jpg");
position: relative;
}
.testclass:before {
content: "";
position: absolute;
left: 0; right: 0;
top: 0; bottom: 0;
background: rgba(0,0,0,.5);
}
``````

### apache mod_rewrite is not working or not enabled

On centOS7 I changed the file /etc/httpd/conf/httpd.conf

from AllowOverride None to AllowOverride All

### How to remove specific element from an array using python

Using `filter()` and `lambda` would provide a neat and terse method of removing unwanted values:

``````newEmails = list(filter(lambda x : x != '[email protected]', emails))
``````

This does not modify emails. It creates the new list newEmails containing only elements for which the anonymous function returned True.

### Core Data: Quickest way to delete all instances of an entity

Dave Delongs's Swift 2.0 answer was crashing for me (in iOS 9)

But this worked:

``````let fetchRequest = NSFetchRequest(entityName: "Car")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

do {
try managedObjectContext.executeRequest(deleteRequest)
try managedObjectContext.save()
}
catch let error as NSError {
// Handle error
}
``````

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

It's the only construct in C that you can use to `#define` a multistatement operation, put a semicolon after, and still use within an `if` statement. An example might help:

``````#define FOO(x) foo(x); bar(x)

if (condition)
FOO(x);
else // syntax error here
...;
``````

Even using braces doesn't help:

``````#define FOO(x) { foo(x); bar(x); }
``````

Using this in an `if` statement would require that you omit the semicolon, which is counterintuitive:

``````if (condition)
FOO(x)
else
...
``````

If you define FOO like this:

``````#define FOO(x) do { foo(x); bar(x); } while (0)
``````

then the following is syntactically correct:

``````if (condition)
FOO(x);
else
....
``````

### How to advance to the next form input when the current input has a value?

If you have jQuery UI this little function allows basic tabbing

``````handlePseudoTab(direction) {
if (!document.hasFocus() || !document.activeElement) {
return;
}
const focusList = \$(":focusable", \$yourHTMLElement);
const i = focusList.index(document.activeElement);
if (i < 0) {
focusList[0].focus(); // nothing is focussed so go to list item 0
} else if (direction === 'next' && i + 1 < focusList.length) {
focusList[i + 1].focus(); // advance one
} else if (direction === 'prev' && i - 1 > -1) {
focusList[i - 1].focus(); // go back one
}
}
``````

### create table in postgreSQL

First the `bigint(20) not null auto_increment` will not work, simply use `bigserial primary key`. Then `datetime` is `timestamp` in PostgreSQL. All in all:

``````CREATE TABLE article (
article_id bigserial primary key,
article_name varchar(20) NOT NULL,
article_desc text NOT NULL,
);
``````

### Angularjs error Unknown provider

If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.

Remember:

``````angular.module('ModuleName', [])   // creates a module.

angular.module('ModuleName')       // gets you a pre-existing module.
``````

So if you are extending a existing module, remember not to overwrite when trying to fetch it.

### open program minimized via command prompt

Try this

1. Go to the `properties` of the shortcut that points to the program (ALT ENTER or `right` `click`->`properties`); if there is no shortcut to it, you can make it by dragging and dropping the program while holding CTRL SHIFT;

2. Click in the `Normal window` dropdown, and choose `minimized`;

3. Save and run the shortcut.

### Aren't Python strings immutable? Then why does a + " " + b work?

``````a = 'dog'
print(id(a))

a = a + 'cat'

import ctypes
``````

### Test if a string contains any of the strings from an array

``````import org.apache.commons.lang.StringUtils;
``````

String Utils

Use:

``````StringUtils.indexOfAny(inputString, new String[]{item1, item2, item3})
``````

It will return the index of the string found or -1 if none is found.

### How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The problem is in this line:

``````with pattern.findall(row) as f:
``````

You are using the `with` statement. It requires an object with `__enter__` and `__exit__` methods. But `pattern.findall` returns a `list`, `with` tries to store the `__exit__` method, but it can't find it, and raises an error. Just use

``````f = pattern.findall(row)
``````

I am not experiented .But i think XmlReader is unnecessary. It is very hard to use.
XElement is very easy to use.
If you need performance ( faster ) you must change file format and use StreamReader and StreamWriter classes.

### Attempted to read or write protected memory

For VS 2013, .NET Framework 4.5.1 also has a `AccessViolationException` bug (KB2915689) when dealing with SQL Server / TCP Sockets. Upgrading to .NET Framework 4.5.2 corrects this problem.

#### Reported VS.NET AccessViolationException

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

### Pass array to mvc Action via AJAX

You should be able to do this just fine:

``````\$.ajax({
url: 'controller/myaction',
data: JSON.stringify({
myKey: myArray
}),
success: function(data) { /* Whatever */ }
});
``````

Then your action method would be like so:

``````public ActionResult(List<int> myKey)
{
// Do Stuff
}
``````

For you, it looks like you just need to stringify your values. The JSONValueProvider in MVC will convert that back into an IEnumerable for you.

### Read and write a String from text file

Xcode 8.3.2 Swift 3.x. Using NSKeyedArchiver and NSKeyedUnarchiver

``````let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!
let jsonFilePath = documentsDirectoryPath.appendingPathComponent("Filename.json")

let fileManager = FileManager.default
var isDirectory: ObjCBool = false

if fileManager.fileExists(atPath: (jsonFilePath?.absoluteString)!, isDirectory: &isDirectory) {

let finalDataDict = NSKeyedUnarchiver.unarchiveObject(withFile: (jsonFilePath?.absoluteString)!) as! [String: Any]
}
else{
print("File does not exists")
}
``````

Write file to documents

``````NSKeyedArchiver.archiveRootObject(finalDataDict, toFile:(jsonFilePath?.absoluteString)!)
``````

### No such keg: /usr/local/Cellar/git

Had a similar issue while installing "Lua" in OS X using homebrew. I guess it could be useful for other users facing similar issue in homebrew.

On running the command:

`\$ brew install lua`

The command returned an error:

Error: /usr/local/opt/lua is not a valid keg
(in general the error can be of /usr/local/opt/ is not a valid keg

FIXED it by deleting the file/directory it is referring to, i.e., deleting the "/usr/local/opt/lua" file.

root-user # rm -rf /usr/local/opt/lua

And then running the brew install command returned success.

### Saving any file to in the database, just convert it to a byte array?

It really depends on the database server.

For example, SQL Server 2008 supports a `FILESTREAM` datatype for exactly this situation.

Other than that, if you use a `MemoryStream`, it has a `ToArray()` method that will convert to a `byte[]` - this can be used for populating a `varbinary` field..

### How do you get the current project directory from C# code when creating a custom MSBuild task?

``````using System;
using System.IO;

// This will get the current WORKING directory (i.e. \bin\Debug)
string workingDirectory = Environment.CurrentDirectory;
// or: Directory.GetCurrentDirectory() gives the same result

// This will get the current PROJECT bin directory (ie ../bin/)
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;

// This will get the current PROJECT directory
string projectDirectory = Directory.GetParent(workingDirectory).Parent.Parent.FullName;
``````

### Android - set TextView TextStyle programmatically?

Search for `setTextAppearance` or also `setTextTypeface`. There is similar question on stackoverflow: How to change a TextView's style at runtime

### Python Variable Declaration

This might be 6 years late, but in Python 3.5 and above, you declare a variable type like this:

``````variable_name: type_name
``````

or this:

``````variable_name # type: shinyType
``````

So in your case(if you have a `CustomObject` class defined), you can do:

``````customObj: CustomObject
``````

### How can I create a product key for my C# application?

The trick is to have an algorithm that only you know (such that it could be decoded at the other end).

There are simple things like, "Pick a prime number and add a magic number to it"

More convoluted options such as using asymmetric encryption of a set of binary data (that could include a unique identifier, version numbers, etc) and distribute the encrypted data as the key.

Might also be worth reading the responses to this question as well

### Unexpected 'else' in "else" error

I would suggest to read up a bit on the syntax. See here.

``````if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
``````

### How to change position of Toast in Android?

From the documentation:

Warning: Starting from Android Build.VERSION_CODES#R, for apps targeting API level Build.VERSION_CODES#R or higher, this method (setGravity) is a no-op when called on text toasts.

Which means that `setGravity` can no longer be used in API 30+ and will have to find another to achieve the required behaviour.

### Play infinitely looping video on-load in HTML5

You can do this the following two ways:

1) Using `loop` attribute in video element (mentioned in the first answer):

2) and you can use the `ended` media event:

``````window.addEventListener('load', function(){
var newVideo = document.getElementById('videoElementId');
this.currentTime = 0;
this.play();
}, false);

newVideo.play();

});
``````

### Maven build failed: "Unable to locate the Javac Compiler in: jre or jdk issue"

Eclipse setup only

Do the following steps:

1. Right click on Eclipse project Properties

2. Java Build Path → Libraries

3. Select JRE System Library → Click the Edit button

4. Click "Installed JREs..." button

5. Edit JRE as: Set JRE Home = JAVA_HOME or JAVA_HOME\jre

Screenshot:

### How to call another controller Action From a controller in Mvc

As @mxmissile says in the comments to the accepted answer, you shouldn't new up the controller because it will be missing dependencies set up for IoC and won't have the `HttpContext`.

``````var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);
``````

### Override element.style using CSS

Use JavaScript.

For example:

``````var elements = document.getElementById("demoFour").getElementsByTagName("li");
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = "inline";
}
``````

### Permanently add a directory to PYTHONPATH?

You need to add your new directory to the environment variable `PYTHONPATH`, separated by a colon from previous contents thereof. In any form of Unix, you can do that in a startup script appropriate to whatever shell you're using (`.profile` or whatever, depending on your favorite shell) with a command which, again, depends on the shell in question; in Windows, you can do it through the system GUI for the purpose.

`superuser.com` may be a better place to ask further, i.e. for more details if you need specifics about how to enrich an environment variable in your chosen platform and shell, since it's not really a programming question per se.

### How to copy a row from one SQL Server table to another

``````SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >
``````

### Create component to specific module with Angular-CLI

To create a component as part of a module you should

1. `ng g module newModule` to generate a module,
2. `cd newModule` to change directory into the `newModule` folder
3. `ng g component newComponent` to create a component as a child of the module.

UPDATE: Angular 9

Now it doesn't matter what folder you are in when generating the component.

1. `ng g module NewMoudle` to generate a module.
2. `ng g component new-module/new-component` to create NewComponent.

Note: When the Angular CLI sees new-module/new-component, it understands and translates the case to match new-module -> NewModule and new-component -> NewComponent. It can get confusing in the beginning, so easy way is to match the names in #2 with the folder names for the module and component.

### Hide Button After Click (With Existing Form on Page)

This is my solution. I Hide and then confirm check

onclick="return ConfirmSubmit(this);" />

``````function ConfirmSubmit(sender)
{
sender.disabled = true;
var displayValue = sender.style.
sender.style.display = 'none'

if (confirm('Seguro que desea entregar los paquetes?')) {
sender.disabled = false
return true;
}

sender.disabled = false;
sender.style.display = displayValue;
return false;
}
``````

### How to determine if binary tree is balanced?

Post order solution, traverse the tree only once. Time complexity is O(n), space is O(1), it's better than top-down solution. I give you a java version implementation.

``````public static <T> boolean isBalanced(TreeNode<T> root){
return checkBalance(root) != -1;
}

private static <T> int checkBalance(TreeNode<T> node){
if(node == null) return 0;
int left = checkBalance(node.getLeft());

if(left == -1) return -1;

int right = checkBalance(node.getRight());

if(right == -1) return -1;

if(Math.abs(left - right) > 1){
return -1;
}else{
return 1 + Math.max(left, right);
}
}
``````

### display:inline vs display:block

Display : block will take the whole line i.e without line break

Display :inline will take only exact space that it requires.

`````` #block
{
display : block;
background-color:red;
border:1px solid;
}

#inline
{
display : inline;
background-color:red;
border:1px solid;
}
``````

You can refer example in this fiddle http://jsfiddle.net/RJXZM/1/.

### How to create a QR code reader in a HTML5 website?

The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

### mysqld: Can't change dir to data. Server doesn't start

First run

``````mysqld -u root --initialize-insecure
``````

It will create data folder with root as user without password. Then run

``````mysqld.exe -u root --console
``````

### What is 'Currying'?

Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:

``````function add (a, b) {
return a + b;
}

``````

This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:

``````function add (a) {
return function (b) {
return a + b;
}
}
``````

This is a function that takes one argument, a, and returns a function that takes another argument, b, and that function returns their sum.

``````add(3)(4);

``````

The first statement returns 7, like the add(3, 4) statement. The second statement defines a new function called add3 that will add 3 to its argument. This is what some people may call a closure. The third statement uses the add3 operation to add 3 to 4, again producing 7 as a result.

### Onchange open URL via select - jQuery

``````**redirect on change option with jquery**

<select id="selectnav1" class="selectnav">
</option>
<option value="http://stackoverflow.com/">
stackoverflow
</option>

</select>

<script type="text/javascript">
\$(function () {

\$('#selectnav1').change( function() {
location.href = \$(this).val();
});
});
</script>
``````

### Vertically align an image inside a div with responsive height

Here is a technique to align inline elements inside a parent, horizontally and vertically at the same time:

# Vertical Alignment

1) In this approach, we create an `inline-block` (pseudo-)element as the first (or last) child of the parent, and set its `height` property to `100%` to take all the height of its parent.

2) Also, adding `vertical-align: middle` keeps the inline(-block) elements at the middle of the line space. So, we add that CSS declaration to the first-child and our element (the image) both.

3) Finally, in order to remove the white space character between inline(-block) elements, we could set the font size of the parent to zero by `font-size: 0;`.

Note: I used Nicolas Gallagher's image replacement technique in the following.

#### What are the benefits?

• The container (parent) can have dynamic dimensions.
• There's no need to specify the dimensions of the image element explicitly.

• We can easily use this approach to align a `<div>` element vertically as well; which may have a dynamic content (height and/or width). But note that you have to re-set the `font-size` property of the `div` to display the inside text. Online Demo.

``````<div class="container">
<div id="element"> ... </div>
</div>
``````
``````.container {
height: 300px;
text-align: center;  /* align the inline(-block) elements horizontally */
font: 0/0 a;         /* remove the gap between inline(-block) elements */
}

.container:before {    /* create a full-height inline block pseudo=element */
content: ' ';
display: inline-block;
vertical-align: middle;  /* vertical alignment of the inline element */
height: 100%;
}

#element {
display: inline-block;
vertical-align: middle;  /* vertical alignment of the inline element */
font: 16px/1 Arial sans-serif;        /* <-- reset the font property */
}
``````

# Responsive Container

This section is not going to answer the question as the OP already knows how to create a responsive container. However, I'll explain how it works.

In order to make the height of a container element changes with its width (respecting the aspect ratio), we could use a percentage value for top/bottom `padding` property.

A percentage value on top/bottom padding or margins is relative to the width of the containing block.

For instance:

``````.responsive-container {
width: 60%;

padding-top: 60%;    /* 1:1 Height is the same as the width */
padding-top: 100%;   /* width:height = 60:100 or 3:5        */
padding-top: 45%;    /* = 60% * 3/4 , width:height =  4:3   */
padding-top: 33.75%; /* = 60% * 9/16, width:height = 16:9   */
}
``````

Here is the Online Demo. Comment out the lines from the bottom and resize the panel to see the effect.

Also, we could apply the `padding` property to a dummy child or `:before`/`:after` pseudo-element to achieve the same result. But note that in this case, the percentage value on `padding` is relative to the width of the `.responsive-container` itself.

``````<div class="responsive-container">
<div class="dummy"></div>
</div>
``````
``````.responsive-container { width: 60%; }

.responsive-container .dummy {
padding-top: 100%;    /*  1:1 square */
padding-top: 75%;     /*  w:h =  4:3 */
padding-top: 56.25%;  /*  w:h = 16:9 */
}
``````

Demo #1.
Demo #2 (Using `:after` pseudo-element)

Using `padding-top` property causes a huge space at the top or bottom of the content, inside the container.

In order to fix that, we have wrap the content by a wrapper element, remove that element from document normal flow by using absolute positioning, and finally expand the wrapper (bu using `top`, `right`, `bottom` and `left` properties) to fill the entire space of its parent, the container.

Here we go:

``````.responsive-container {
width: 60%;
position: relative;
}

.responsive-container .wrapper {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
}
``````

Here is the Online Demo.

# Getting all together

``````<div class="responsive-container">
<div class="dummy"></div>

<div class="img-container">
<img src="http://placehold.it/150x150" alt="">
</div>
</div>
``````
``````.img-container {
text-align:center; /* Align center inline elements */
font: 0/0 a;       /* Hide the characters like spaces */
}

.img-container:before {
content: ' ';
display: inline-block;
vertical-align: middle;
height: 100%;
}

.img-container img {
vertical-align: middle;
display: inline-block;
}
``````

Here is the WORKING DEMO.

Obviously, you could avoid using `::before` pseudo-element for browser compatibility, and create an element as the first child of the `.img-container`:

``````<div class="img-container">
<div class="centerer"></div>
<img src="http://placehold.it/150x150" alt="">
</div>
``````
``````.img-container .centerer {
display: inline-block;
vertical-align: middle;
height: 100%;
}
``````

#### Using `max-*` properties

In order to keep the image inside of the box in lower width, you could set `max-height` and `max-width` property on the image:

``````.img-container img {
vertical-align: middle;
display: inline-block;
max-height: 100%;  /* <-- Set maximum height to 100% of its parent */
max-width: 100%;   /* <-- Set maximum width to 100% of its parent */
}
``````

Here is the UPDATED DEMO.

### Export a list into a CSV or TXT file in R

You can write your For loop to individually store dataframes from a list:

``````allocation = list()

for(i in 1:length(allocation)){
write.csv(data.frame(allocation[[i]]), file = paste0(path, names(allocation)[i], '.csv'))
}
``````

### Auto populate columns in one sheet from another sheet

If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?

It might not be the best way but you may type the following

=IF(sheet1!A1<>"",sheet1!A1,"")

and drag it down to the maximum number of rows you expect.