# Programs & Examples On #Jbi

### Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

``````while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
n = (3*n + 1) / 2;
if (n % 2 == 0) {
do n /= 2; while (n % 2 == 0);
if (n == 1) break;
}
}
``````

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

``````3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????
``````

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

``````k = n / 256;
m = n % 256;

switch (m) {
case 0: n = 1 * k + 0; break;
case 1: n = 81 * k + 1; break;
case 2: n = 81 * k + 1; break;
...
case 155: n = 729 * k + 425; break;
...
}
``````

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

``````static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
size_t lastBits = n % 256;
n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}
``````

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

### json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

``````json: cannot unmarshal object into Go struct field Comment.author of type string
``````

When this type of problem occurs simply delete previous path setting and add new path in Environment variable.

new path name JAVA_HOME path "Your computer path" without \bin

and also edit path variable with \bin path.

netbeans will working fine whatever the version is.either jdk 9 or upper version.

### How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using `keytool`, as of Java 7, `keytool` has an option to include a Subject Alternative Name (see the table in the documentation for `-ext`): you could use `-ext san=dns:www.example.com` or `-ext san=ip:10.0.0.1`.

EDIT:

You can request a SAN in OpenSSL by changing `openssl.cnf` (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the `OPENSSL_CONF` environment variable).

Set the following options (find the appropriate sections within brackets first):

``````[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
``````

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

### How to Load RSA Private Key From File

Two things. First, you must base64 decode the `mykey.pem` file yourself. Second, the openssl private key format is specified in PKCS#1 as the `RSAPrivateKey` ASN.1 structure. It is not compatible with java's `PKCS8EncodedKeySpec`, which is based on the `SubjectPublicKeyInfo` ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

``````import java.io.BufferedReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...

String keyPath = "mykey.pem";
PEMParser pp = new PEMParser(br);
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);
``````

### How to resize an Image C#

``````public static Image resizeImage(Image image, int new_height, int new_width)
{
Bitmap new_image = new Bitmap(new_width, new_height);
Graphics g = Graphics.FromImage((Image)new_image );
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(image, 0, 0, new_width, new_height);
return new_image;
}
``````

### Know relationships between all the tables of database in SQL Server

``````select * from information_schema.REFERENTIAL_CONSTRAINTS where
UNIQUE_CONSTRAINT_SCHEMA = 'TABLE_NAME'
``````

This will list the column with `TABLE_NAME` and `REFERENCED_COLUMN_NAME`.

### How to detect page zoom level in all modern browsers?

This has worked great for me in webkit-based browsers (Chrome, Safari):

``````function isZoomed() {
var width, mediaQuery;

width = document.body.clientWidth;
mediaQuery = '(max-width: ' + width + 'px) and (min-width: ' + width + 'px)';

return !window.matchMedia(mediaQuery).matches;
}
``````

Doesn't seem to work in Firefox though.

This also works in WebKit:

``````var zoomLevel = document.width / document.body.clientWidth;
``````

### How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

in this scenario:

``````DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
``````

aren't you missing the column you want to compare to? example:

``````DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
``````

I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.

### How to execute raw SQL in Flask-SQLAlchemy app

This is a simplified answer of how to run SQL query from Flask Shell

First, map your module (if your module/app is manage.py in the principal folder and you are in a UNIX Operating system), run:

``````export FLASK_APP=manage
``````

``````flask shell
``````

Import what we need::

``````from flask import Flask
db = SQLAlchemy(app)
from sqlalchemy import text
``````

``````result = db.engine.execute(text("<sql here>").execution_options(autocommit=True))
``````

This use the currently database connection which has the application.

### How to check if a string contains a substring in Bash

You should remember that shell scripting is less of a language and more of a collection of commands. Instinctively you think that this "language" requires you to follow an `if` with a `[` or a `[[`. Both of those are just commands that return an exit status indicating success or failure (just like every other command). For that reason I'd use `grep`, and not the `[` command.

Just do:

``````if grep -q foo <<<"\$string"; then
echo "It's there"
fi
``````

Now that you are thinking of `if` as testing the exit status of the command that follows it (complete with semi-colon), why not reconsider the source of the string you are testing?

``````## Instead of this
filetype="\$(file -b "\$1")"
if grep -q "tar archive" <<<"\$filetype"; then
#...

## Simply do this
if file -b "\$1" | grep -q "tar archive"; then
#...
``````

The `-q` option makes grep not output anything, as we only want the return code. `<<<` makes the shell expand the next word and use it as the input to the command, a one-line version of the `<<` here document (I'm not sure whether this is standard or a Bashism).

### How can I make git accept a self signed certificate?

You can set `GIT_SSL_NO_VERIFY` to `true`:

``````GIT_SSL_NO_VERIFY=true git clone https://example.com/path/to/git
``````

or alternatively configure Git not to verify the connection on the command line:

``````git -c http.sslVerify=false clone https://example.com/path/to/git
``````

Note that if you don't verify SSL/TLS certificates, then you are susceptible to MitM attacks.

### asp.net: Invalid postback or callback argument

asp:UpdatePanel ID="UpdatePanel1" runat="server" ViewStateMode="Disabled"

### Maximum concurrent Socket.IO connections

For +300k concurrent connection:

Set these variables in `/etc/sysctl.conf`:

``````fs.file-max = 10000000
fs.nr_open = 10000000
``````

Also, change these variables in `/etc/security/limits.conf`:

``````* soft nofile 10000000
* hard nofile 10000000
root soft nofile 10000000
root hard nofile 10000000
``````

And finally, increase TCP buffers in `/etc/sysctl.conf`, too:

``````net.ipv4.tcp_mem = 786432 1697152 1945728
net.ipv4.tcp_rmem = 4096 4096 16777216
net.ipv4.tcp_wmem = 4096 4096 16777216
``````

### GCC dump preprocessor defines

A portable approach that works equally well on Linux or Windows (where there is no /dev/null):

``````echo | gcc -dM -E -
``````

For c++ you may use (replace `c++11` with whatever version you use):

``````echo | gcc -x c++ -std=c++11 -dM -E -
``````

It works by telling gcc to preprocess stdin (which is produced by echo) and print all preprocessor defines (search for `-dletters`). If you want to know what defines are added when you include a header file you can use `-dD` option which is similar to -dM but does not include predefined macros:

``````echo "#include <stdlib.h>" | gcc -x c++ -std=c++11 -dD -E -
``````

Note, however, that empty input still produces lots of defines with `-dD` option.

### How to change the href for a hyperlink using jQuery

Stop using jQuery just for the sake of it! This is so simple with JavaScript only.

``````document.querySelector('#the-link').setAttribute('href', 'http://google.com');
``````

https://jsfiddle.net/bo77f8mg/1/

### Interview question: Check if one string is a rotation of other string

Surely a better answer would be, "Well, I'd ask the stackoverflow community and would probably have at least 4 really good answers within 5 minutes". Brains are good and all, but I'd place a higher value on someone who knows how to work with others to get a solution.

### Can I access a form in the controller?

Definitely you can't access form in scope bec. it is not created. The DOM from html template is loaded little bit slowly like controller constructor. the solution is to watch until DOM loaded and all the scope defined!

in controller:

``````\$timeout(function(){
console.log('customerForm:', \$scope.customerForm);
// everything else what you need
});
``````

### Eclipse executable launcher error: Unable to locate companion shared library

I have seen this in MacOS Sierra. Sometimes unzipping the app leaves extended attributes that seem to prevent the startup. The following command line removes extended attributes and seems to fix the problem:

`xattr -c Eclipse.app`

It also works for other applications that are built on the eclipse framework.

### How to remove "index.php" in codeigniter's path

If you are on linux and using apache2 server then we may need to override apache2.conf file also beside changes on .htaccess file. Find apache2 configuration file on /etc/apache2/apache2.conf .

Search Directory /var/www/ Change AllowOverride None -> AllowOverride All

``````<Directory /var/www/>
AllowOverride All
Require all granted
</Directory
``````

### Apply CSS to jQuery Dialog Buttons

Select the div which has role dialog then get the appropriate buttons in it and set the CSS.

``````\$("div[role=dialog] button:contains('Save')").css("color", "green");
\$("div[role=dialog] button:contains('Cancel')").css("color", "red");
``````

### Element implicitly has an 'any' type because expression of type 'string' can't be used to index

When we do something like this obj[key] Typescript can't know for sure if that key exists in that object. What I did:

``````Object.entries(data).forEach(item => {
formData.append(item[0], item[1]);
});
``````

### setting min date in jquery datepicker

``````\$(function () {
\$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
showButtonPanel: true,
changeMonth: true,
changeYear: true,
yearRange: '1999:2012',
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
minDate: new Date(1999, 10 - 1, 25),
maxDate: '+30Y',
inline: true
});
});
``````

Just added year range option. It should solve the problem

### Convert a string to int using sql query

You could use CAST or CONVERT:

``````SELECT CAST(MyVarcharCol AS INT) FROM Table

SELECT CONVERT(INT, MyVarcharCol) FROM Table
``````

### Rendering HTML inside textarea

This is possible with `<textarea>` the only thing you need to do is use Summernote WYSIWYG editor

it interprets HTML tags inside a textarea (namely `<strong>`, `<i>`, `<u>`, `<a>`)

### Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

This is not an answer, but it's hard to read if I put results in comment.

I get these results with a Mac Pro (Westmere 6-Cores Xeon 3.33 GHz). I compiled it with `clang -O3 -msse4 -lstdc++ a.cpp -o a` (-O2 get same result).

#### clang with `uint64_t size=atol(argv[1])<<20;`

``````unsigned    41950110000 0.811198 sec    12.9263 GB/s
uint64_t    41950110000 0.622884 sec    16.8342 GB/s
``````

#### clang with `uint64_t size=1<<20;`

``````unsigned    41950110000 0.623406 sec    16.8201 GB/s
uint64_t    41950110000 0.623685 sec    16.8126 GB/s
``````

I also tried to:

1. Reverse the test order, the result is the same so it rules out the cache factor.
2. Have the `for` statement in reverse: `for (uint64_t i=size/8;i>0;i-=4)`. This gives the same result and proves the compile is smart enough to not divide size by 8 every iteration (as expected).

Here is my wild guess:

The speed factor comes in three parts:

• code cache: `uint64_t` version has larger code size, but this does not have an effect on my Xeon CPU. This makes the 64-bit version slower.

• Instructions used. Note not only the loop count, but the buffer is accessed with a 32-bit and 64-bit index on the two versions. Accessing a pointer with a 64-bit offset requests a dedicated 64-bit register and addressing, while you can use immediate for a 32-bit offset. This may make the 32-bit version faster.

• Instructions are only emitted on the 64-bit compile (that is, prefetch). This makes 64-bit faster.

The three factors together match with the observed seemingly conflicting results.

### Mockito matcher and array of primitives

What works for me was `org.mockito.ArgumentMatchers.isA`

for example:

``````isA(long[].class)
``````

that works fine.

the implementation difference of each other is:

``````public static <T> T any(Class<T> type) {
reportMatcher(new VarArgAware(type, "<any " + type.getCanonicalName() + ">"));
return Primitives.defaultValue(type);
}

public static <T> T isA(Class<T> type) {
reportMatcher(new InstanceOf(type));
return Primitives.defaultValue(type);
}
``````

### How to add anchor tags dynamically to a div in Javascript?

here's a pure Javascript alternative:

``````var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
mydiv.appendChild(aTag);
``````

### Enabling WiFi on Android Emulator

The emulator does not provide virtual hardware for Wi-Fi if you use API 24 or earlier. From the Android Developers website:

When using an AVD with API level 25 or higher, the emulator provides a simulated Wi-Fi access point ("AndroidWifi"), and Android automatically connects to it.

You can disable Wi-Fi in the emulator by running the emulator with the command-line parameter -feature -Wifi.

What's not supported

The Android Emulator doesn't include virtual hardware for the following:

• Bluetooth
• NFC
• SD card insert/eject
• USB

The watch emulator for Android Wear doesn't support the Overview (Recent Apps) button, D-pad, and fingerprint sensor.

https://developer.android.com/studio/run/emulator.html#wi-fi

### Add column with number of days between dates in DataFrame pandas

Assuming these were datetime columns (if they're not apply `to_datetime`) you can just subtract them:

``````df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])

In [11]: df.dtypes  # if already datetime64 you don't need to use to_datetime
Out[11]:
A    datetime64[ns]
B    datetime64[ns]
dtype: object

In [12]: df['A'] - df['B']
Out[12]:
one   -58 days
two   -26 days
dtype: timedelta64[ns]

In [13]: df['C'] = df['A'] - df['B']

In [14]: df
Out[14]:
A          B        C
one 2014-01-01 2014-02-28 -58 days
two 2014-02-03 2014-03-01 -26 days
``````

Note: ensure you're using a new of pandas (e.g. 0.13.1), this may not work in older versions.

### What is the standard Python docstring format?

PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 -- a complete specification for docstrings.

### MySQL Trigger: Delete From Table AFTER DELETE

Why not set ON CASCADE DELETE on Foreign Key `patron_info`.pid?

### making matplotlib scatter plots from dataframes in Python's pandas

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

Working code:

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

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

### How to get JSON Key and Value?

``````\$.each(result, function(key, value) {
console.log(key+ ':' + value);
});
``````

### How can I convert a DateTime to the number of seconds since 1970?

You can create a startTime and endTime of DateTime, then do endTime.Subtract(startTime). Then output your span.Seconds.

I think that should work.

### Comparing two maps

As long as you override `equals()` on each key and value contained in the map, then `m1.equals(m2)` should be reliable to check for maps equality.

The same result can be obtained also by comparing `toString()` of each map as you suggested, but using `equals()` is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using `Arrays.equals()`. More details about this see here.

Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?

If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.

If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

As per the technical difference, and also my understanding:

1. Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domainSO Question also mentions it.

2. `localStorage` is an implementation of the `Storage` Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.

### Searching a list of objects in Python

You can get a list of all matching elements with a list comprehension:

``````[x for x in myList if x.n == 30]  # list of all elements with .n==30
``````

If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do

``````def contains(list, filter):
for x in list:
if filter(x):
return True
return False

if contains(myList, lambda x: x.n == 3)  # True if any element has .n==3
# do stuff
``````

### Excel Date to String conversion

``````=TEXT(A1,"DD/MM/YYYY hh:mm:ss")
``````

(24 hour time)

``````=TEXT(A1,"DD/MM/YYYY hh:mm:ss AM/PM")
``````

(standard time)

### updating table rows in postgres using subquery

``````update json_source_tabcol as d
set isnullable = a.is_Nullable
from information_schema.columns as a
where a.table_name =d.table_name
and a.table_schema = d.table_schema
and a.column_name = d.column_name;
``````

### No submodule mapping found in .gitmodule for a path that's not a submodule

The problem for us was that duplicate submodule entries had been added into .gitmodules (probably from a merge). We searched for the path git complained about in .gitmodules and found the two identical sections. Deleting one of the sections solved the problem for us.

For what it is worth, git 1.7.1 gave the "no submodule mapping" error but git 2.13.0 didn't seem to care.

### How do I get the name of the current executable in C#?

Try this:

``````System.Reflection.Assembly.GetExecutingAssembly()
``````

This returns you a `System.Reflection.Assembly` instance that has all the data you could ever want to know about the current application. I think that the `Location` property might get what you are after specifically.

### How to run .NET Core console app from the command line

Using CMD you can run a console .net core project if .net core SDK is installed in your machine :

To run console project using windows command-Line, choose the specific path from your directory and type following below command

dotnet run

### Interop type cannot be embedded

In most cases, this error is the result of code which tries to instantiate a COM object. For example, here is a piece of code starting up Excel:

``````Excel.ApplicationClass xlapp = new Excel.ApplicationClass();
``````

Typically, in .NET 4 you just need to remove the 'Class' suffix and compile the code:

``````Excel.Application xlapp = new Excel.Application();
``````

An MSDN explanation is here.

### Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

Somewhere, you need to tell Apache that people are allowed to see contents of this directory.

``````<Directory "F:/bar/public">
Order Allow,Deny
Allow from All
# Any other directory-specific stuff
</Directory>
``````

### What is 'Currying'?

I found this article, and the article it references, useful, to better understand currying: http://blogs.msdn.com/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx

As the others mentioned, it is just a way to have a one parameter function.

This is useful in that you don't have to assume how many parameters will be passed in, so you don't need a 2 parameter, 3 parameter and 4 parameter functions.

### Is the Javascript date object always one day off?

The best way to handle this without using more conversion methods,

`````` var mydate='2016,3,3';
var utcDate = Date.parse(mydate);
console.log(" You're getting back are 20.  20h + 4h = 24h :: "+utcDate);
``````

Now just add GMT in your date or you can append it.

`````` var  mydateNew='2016,3,3'+ 'GMT';
var utcDateNew = Date.parse(mydateNew);
console.log("the right time that you want:"+utcDateNew)
``````

### generate model using user:references vs user_id:integer

how does rails know that `user_id` is a foreign key referencing `user`?

Rails itself does not know that `user_id` is a foreign key referencing `user`. In the first command `rails generate model Micropost user_id:integer` it only adds a column `user_id` however rails does not know the use of the col. You need to manually put the line in the `Micropost` model

``````class Micropost < ActiveRecord::Base
belongs_to :user
end

class User < ActiveRecord::Base
has_many :microposts
end
``````

the keywords `belongs_to` and `has_many` determine the relationship between these models and declare `user_id` as a foreign key to `User` model.

The later command `rails generate model Micropost user:references` adds the line `belongs_to :user` in the `Micropost` model and hereby declares as a foreign key.

FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models/tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using software like `MySql Workbench` you find that there is no relationship threads drawn between the models. Like in the following pic

However, if you use the later method you find that you migration file looks like:

``````def change
create_table :microposts do |t|
t.references :user, index: true

t.timestamps null: false
end
``````

Now the foreign key is set at the database level. and you can generate proper `EER` diagrams.

### Open firewall port on CentOS 7

CentOS (RHEL) 7, has changed the firewall to use `firewall-cmd` which has a notion of zones which is like a Windows version of Public, Home, and Private networks. You should look here to figure out which one you think you should use. EL7 uses `public` by default so that is what my examples below use.

You can check which zone you are using with `firewall-cmd --list-all` and change it with `firewall-cmd --set-default-zone=<zone>`.

You will then know what zone to allow a service (or port) on:

`firewall-cmd --permanent --zone=<zone> --add-service=http`

`firewall-cmd --permanent --zone=<zone> --add-port=80/tcp`

You can check if the port has actually be opened by running:

`firewall-cmd --zone=<zone> --query-port=80/tcp`

`firewall-cmd --zone=<zone> --query-service=http`

According to the documentation,

When making changes to the firewall settings in Permanent mode, your selection will only take effect when you reload the firewall or the system restarts.

You can reload the firewall settings with: `firewall-cmd --reload`.

### Add custom message to thrown exception while maintaining stack trace in Java

Following code is a simple example that worked for me.Let me call the function `main` as parent function and `divide` as child function.
Basically i am throwing a new exception with my custom message (for the parent's call) if an exception occurs in child function by catching the Exception in the child first.

``````class Main {
public static void main(String args[]) {
try{
long ans=divide(0);
}
catch(Exception e){
System.out.println("got exception:"+e.getMessage());

}

}
public static long divide(int num) throws Exception{
long x=-1;
try {
x=5/num;
}
catch (Exception e){
throw new Exception("Error occured in divide for number:"+num+"Error:"+e.getMessage());
}
return x;
}
}
``````

the last line `return x` will not run if error occurs somewhere in between.

### scp (secure copy) to ec2 instance without password

Making siliconerockstar's comment an answer since it worked for me

``````scp -i kp1.pem ./file.txt [email protected]:/home/ec2-user
``````

### How to install pandas from pip on windows cmd?

Reply to abccd and Question to anyone:

The command: `C:\Python34\Scripts>py -3 -m pip install pandas` executed just fine. Unfortunately, I can't import Pandas.

Directory path: `C:\users\myname\downloads\miniconda3\lib\site-packages`

My Question: How is it that Pandas' dependency packages(numpy, python-dateutil, pytz, six) also having the same above directory path are able to import just fine but Pandas does not?

``````import pandas

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
import pandas
ImportError: No module named 'pandas'
``````

I finally got Pandas reinstalled and imported with the help of the following web pages: *http://pandas.pydata.org/pandas-docs/stable/pandas.pdf (Pages 403 and 404 of 2215 ... 2.2.2 Installing Pandas with Miniconda) *https://conda.io/docs/user-guide/install/download.html *https://conda.io/docs/user-guide/getting-started.html

After installing Miniconda, I created a new environment area to get Pandas reinstalled and imported. This new environment included the current Python version 3.6.3. I could not import Pandas using Python 3.4.4.

### What's the difference between 'int?' and 'int' in C#?

int belongs to System.ValueType and cannot have null as a value. When dealing with databases or other types where the elements can have a null value, it might be useful to check if the element is null. That is when int? comes into play. int? is a nullable type which can have values ranging from -2147483648 to 2147483648 and null.

### Main differences between SOAP and RESTful web services in Java

SOAP web service always make a POST operation whereas using REST you can choose specific HTTP methods like GET, POST, PUT, and DELETE.

Example: to get an item using SOAP you should create a request XML, but in the case of REST you can just specify the item id in the URL itself.

### How to change int into int64?

``````i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64
``````

### Any way to generate ant build.xml file automatically from Eclipse?

If all you need is the classpath entries, I do something like the following to use the eclipse build path.

``````<xmlproperty file=".classpath" collapseAttributes="true" delimiter=";" />
``````

Then set that value in the path

``````<path id="eclipse.classpath">
<pathelement path="\${classpath.classpathentry.path}"/>
</path>

<target name="compile" depends="init">

<javac srcdir="\${src}" destdir="\${build}" updatedProperty="compiled">
<classpath refid="eclipse.classpath"/>
</javac>
</target>
``````

### Difference between static class and singleton pattern?

In singleton pattern you can create the singleton as an instance of a derived type, you can't do that with a static class.

Quick Example:

``````if( useD3D )
IRenderer::instance = new D3DRenderer
else
IRenderer::instance = new OpenGLRenderer
``````

### How can I check if string contains characters & whitespace, not just whitespace?

I've used the following method to detect if a string contains only whitespace. It also matches empty strings.

``````if (/^\s*\$/.test(myStr)) {
// the string contains only whitespace
}
``````

### Passing an array of parameters to a stored procedure

``````declare @ids nvarchar(1000)

set @ids = '100,2,3,4,5' --Parameter passed

set @ids = ',' + @ids + ','

select   *
from     TableName
where    charindex(',' + CAST(Id as nvarchar(50)) + ',', @ids) > 0
``````

### Run bash script from Windows PowerShell

There is now a "native" solution on Windows 10, after enabling Bash on Windows, you can enter Bash shell by typing `bash`:

You can run Bash script like `bash ./script.sh`, but keep in mind that C drive is located at `/mnt/c`, and external hard drives are not mountable. So you might need to change your script a bit so it is compatible to Windows.

Also, even as `root`, you can still get permission denied when moving files around in `/mnt`, but you have your full `root` power in the `/` file system.

Also make sure your shell script is formatted with Unix style, or there can be errors.

### C# equivalent to Java's charAt()?

Console.WriteLine allows the user to specify a position in a string.

See sample:

string str = "Tigger"; Console.WriteLine( str[0] ); //returns "T"; Console.WriteLine( str[2] ); //returns "g";

There you go!

### HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around `utf-8` in the content type. It failed with a generic `"Server Error"` and it took hours to figure out what it didn't like:

``````request.ContentType = "text/xml; encoding=utf-8";
``````

### UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

``````frame.origin = center - bounds.size / 2
``````

(which is the same as)

``````center = frame.origin + bounds.size / 2
``````

(and there’s also)

``````frame.size = bounds.size
``````

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

### Bad File Descriptor with Linux Socket write() Bad File Descriptor C

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:

1. The fd is already closed somewhere.
2. The fd has a wrong value, which is inconsistent with the value obtained from socket() api

### How to press back button in android programmatically?

Sometimes is useful to override method onBackPressed() because in case you work with fragments and you're changing between them if you push backbutton they return to the previous fragment.

### How could I use requests in asyncio?

The answers above are still using the old Python 3.4 style coroutines. Here is what you would write if you got Python 3.5+.

`aiohttp` supports http proxy now

``````import aiohttp
import asyncio

async def fetch(session, url):
async with session.get(url) as response:
return await response.text()

async def main():
urls = [
'http://python.org',
'http://yifei.me'
]
async with aiohttp.ClientSession() as session:
for url in urls:
for html in htmls:
print(html[:100])

if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
``````

### PHP Create and Save a txt file to root directory

It's creating the file in the same directory as your script. Try this instead.

``````\$content = "some text here";
\$fp = fopen(\$_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite(\$fp,\$content);
fclose(\$fp);
``````

### Calling a function of a module by using its name (a string)

none of what was suggested helped me. I did discover this though.

``````<object>.__getattribute__(<string name>)(<params>)
``````

I am using python 2.66

Hope this helps

### Core dump file analysis

You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run `gdb path/to/the/binary path/to/the/core/dump/file` to debug it.

When it starts up, you can use `bt` (for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use `frame number` (replacing number with the corresponding number in the stack trace) to select a particular stack frame.

You can then use `list` to see code around that function, and `info locals` to see the local variables. You can also use `print name_of_variable` (replacing "name_of_variable" with a variable name) to see its value.

Typing `help` within GDB will give you a prompt that will let you see additional commands.

### Responsive Image full screen and centered - maintain aspect ratio, not exceed window

You could use a `div` with a background image instead and this CSS3 property:

`background-size: contain`

You can check out an example on:

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain

To quote Mozilla:

The contain value specifies that regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.

However, keep in mind that your image will be upscaled if the `div` is larger than your original image.

### Inserting Data into Hive Table

You can use following lines of code to insert values into an already existing table. Here the table is db_name.table_name having two columns, and I am inserting 'All','done' as a row in the table.

``````insert into table db_name.table_name
select 'ALL','Done';
``````

### How can I perform an inspect element in Chrome on my Galaxy S3 Android device?

Update: 8-20-2015

Please note the instructions have changed since this question was asked 2 yrs ago.

So on Newer versions of Android and Chrome for Android. You need to use this.

I have the S3 and it works fine. I have found that a common mistake is not enabling USB Debugging in Chrome mobile. Not only do you have to enable USB debugging on the device itself under developer options but you have to go to the Chrome Browser on your phone and enable it in the settings there too.

Try this with the SDK

1. Chrome for Mobile - Settings > Developer Tools > [x] Enable USB Web debugging
2. Device - Settings > Developer options > [x] USB debugging
3. Connect Device to Computer
4. Enable port forwarding on your computer by doing the following command below

Go to `http://localhost:9222` in Chrome on your Computer

TroubleShooting:

If you get `command not found` when trying to run `ADB`, make sure Platform-Tools is in your path or just use the whole path to your SDK and run it

``````C:\path-to-SDK\platform-tools\adb forward tcp:9222 localabstract:chrome_devtools_remote
``````

If you get "`device not found`", then run `adb kill-server` and then try again.

### Git: How to commit a manually deleted file?

It's better if you do `git rm <fileName>`, though.

### How to convert string date to Timestamp in java?

You can even try this.

``````   String date="09/08/1980";    // take a string  date
Timestamp ts=null;  //declare timestamp
Date d=new Date(date); // Intialize date with the string date
if(d!=null){  // simple null check
ts=new java.sql.Timestamp(d.getTime()); // convert gettime from date and assign it to your timestamp.
}
``````

### How do you reindex an array in PHP but with indexes starting from 1?

Simply do this:

``````<?php

array_push(\$array, '');
\$array = array_reverse(\$array);
array_shift(\$array);
``````

### What does "connection reset by peer" mean?

It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.

### Break or return from Java 8 stream forEach?

``````public static void main(String[] args) {
List<String> list = Arrays.asList("one", "two", "three", "seven", "nine");
AtomicBoolean yes = new AtomicBoolean(true);
list.stream().takeWhile(value -> yes.get()).forEach(value -> {
System.out.println("prior cond" + value);
if (value.equals("two")) {
System.out.println(value);
yes.set(false);
}

});
//System.out.println("Hello World");
}
``````

### AngularJS How to dynamically add HTML and bind to controller

For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.

After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope (`\$rootScope` if there is no `\$scope` for that element)

``````/**
* AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
*/
var AngularHelper = (function () {
var AngularHelper = function () { };

/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "myApplicationName";

/**
* Compile : Compile html with the rootScope of an application
*  and replace the content of a target element with the compiled html
* @\$targetDom : The dom in which the compiled html should be placed
* @htmlToCompile : The html to compile using angular
* @applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function (\$targetDom, htmlToCompile, applicationName) {
var \$injector = angular.injector(["ng", applicationName || defaultApplicationName]);

\$injector.invoke(["\$compile", "\$rootScope", function (\$compile, \$rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var \$scope = \$targetDom.html(htmlToCompile).scope();
\$compile(\$targetDom)(\$scope || \$rootScope);
\$rootScope.\$digest();
}]);
}

return AngularHelper;
})();
``````

It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.

Hope it will help.

### Java substring: 'string index out of range'

It is a pity that `substring` is not implemented in a way that handles short strings – like in other languages e.g. Python.

Ok, we cannot change that and have to consider this edge case every time we use `substr`, instead of if-else clauses I would go for this shorter variant:

``````myText.substring(0, Math.min(6, myText.length()))
``````

### Converting year and month ("yyyy-mm" format) to a date?

Indeed, as has been mentioned above (and elsewhere on SO), in order to convert the string to a date, you need a specific date of the month. From the `as.Date()` manual page:

If the date string does not specify the date completely, the returned answer may be system-specific. The most common behaviour is to assume that a missing year, month or day is the current one. If it specifies a date incorrectly, reliable implementations will give an error and the date is reported as NA. Unfortunately some common implementations (such as `glibc`) are unreliable and guess at the intended meaning.

A simple solution would be to paste the date `"01"` to each date and use `strptime()` to indicate it as the first day of that month.

For those seeking a little more background on processing dates and times in R:

In R, times use `POSIXct` and `POSIXlt` classes and dates use the `Date` class.

Dates are stored as the number of days since January 1st, 1970 and times are stored as the number of seconds since January 1st, 1970.

So, for example:

``````d <- as.Date("1971-01-01")
unclass(d)  # one year after 1970-01-01
# [1] 365

pct <- Sys.time()  # in POSIXct
unclass(pct)  # number of seconds since 1970-01-01
# [1] 1450276559
plt <- as.POSIXlt(pct)
up <- unclass(plt)  # up is now a list containing the components of time
names(up)
# [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"   "wday"   "yday"   "isdst"  "zone"
# [11] "gmtoff"
up\$hour
# [1] 9
``````

To perform operations on dates and times:

``````plt - as.POSIXlt(d)
# Time difference of 16420.61 days
``````

And to process dates, you can use `strptime()` (borrowing these examples from the manual page):

``````strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
# [1] "2006-02-20 11:16:16 EST"

# And in vectorized form:
dates <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
strptime(dates, "%d%b%Y")
# [1] "1960-01-01 EST" "1960-01-02 EST" "1960-03-31 EST" "1960-07-30 EDT"
``````

### Best way to require all files from a directory in ruby?

``````Dir.glob(File.join('path', '**', '*.rb'), &method(:require))
``````

or alternatively, if you want to scope the files to load to specific folders:

``````Dir.glob(File.join('path', '{folder1,folder2}', '**', '*.rb'), &method(:require))
``````

explanation:

Dir.glob takes a block as argument.

method(:require) will return the require method.

&method(:require) will convert the method to a bloc.

### Making HTTP Requests using Chrome Developer tools

If you want to do a POST from the same domain, you can always insert a form into the DOM using Developer tools and submit that:

### How can I specify a display?

The way that X works is the same as the way any network program works. You have a server of some description (in this case, the X display server) which runs on a specific machine, and you have X clients (like firefox) that try to connect to that server to get their information displayed.

Often (on "home" machines), the client and server run on the same box and there's only one server, but X is powerful enough that this doesn't need to happen. It was built with the server/client separation built in from the start.

This allows you to do such wondrous things such as log on to your box (in text mode) halfway around the planet, tell it that the display server is the box you're currently on and, voila, the windows suddenly start appearing locally.

In order for a client to interact with a user, it needs to know how to find the server. There are a number of ways to do this. Many clients allow the `-display` or `--display`option to specify it:

``````xeyes -display paxbox1.paxco.com:0.0
``````

Many will use the `DISPLAY` environment variable if a display isn't specifically given. You can set this variable like any other:

``````DISPLAY=paxbox1.paxco.com:0.0; export DISPLAY # in .profile
export DISPLAY=paxbox1.paxco.com:0.0 # in your shell
DISPLAY=paxbox1.paxco.com:0.0 firefox & # for that command (shell permitting)
``````

The first part of the `DISPLAY` variable is just the address of the display server machine. It follows the same rule as any other IP address; it can be a resolvable DNS name (including `localhost`) or a specific IP address (such as 192.168.10.55).

The second part is X-specific. It gives the X "display" (X server) number and screen number to use. The first (display number) generally refers to a group of devices containing one or more screens but with a single keyboard and mouse (i.e., one input stream). The screen number generally gives the specific screen within that group.

An example would be:

``````+----------------------------------------+
|paxbox1.paxco.com|                      |
+-----------------+                      |
|                                        |
|  +----------+----+  +----------+----+  |
|  |Display :0|    |  |Display :1|    |  |
|  +----------+    |  +----------+    |  |
|  |               |  |               |  |
|  | +-----------+ |  |               |  |
|  | |Screen :0.0| |  |               |  |
|  | +-----------+ |  |               |  |
|  | +-----------+ |  |               |  |
|  | |Screen :0.1| |  |               |  |
|  | +-----------+ |  |               |  |
|  | +-----------+ |  | +-----------+ |  |
|  | |Screen :0.2| |  | |Screen :1.0| |  |
|  | +-----------+ |  | +-----------+ |  |
|  | +-----------+ |  | +-----------+ |  |
|  | |Screen :0.3| |  | |Screen :1.1| |  |
|  | +-----------+ |  | +-----------+ |  |
|  | +-----------+ |  | +-----------+ |  |
|  | | Keyboard  | |  | |  Keyboard | |  |
|  | +-----------+ |  | +-----------+ |  |
|  | +-----------+ |  | +-----------+ |  |
|  | |   Mouse   | |  | |   Mouse   | |  |
|  | +-----------+ |  | +-----------+ |  |
|  +---------------+  +---------------+  |
|                                        |
+----------------------------------------+
``````

Here you have a single machine (`paxbox1.paxco.com`) with two display servers. The first has four screens and the second has two. The possibilities are then:

``````DISPLAY=paxbox1.paxco.com:0.0
DISPLAY=paxbox1.paxco.com:0.1
DISPLAY=paxbox1.paxco.com:0.2
DISPLAY=paxbox1.paxco.com:0.3
DISPLAY=paxbox1.paxco.com:1.0
DISPLAY=paxbox1.paxco.com:1.1
``````

depending on where you want your actual windows to appear and which input devices you want to use.

### Date Conversion from String to sql Date in Java giving different output?

While using the date formats, you may want to keep in mind to always use `MM` for months and `mm` for minutes. That should resolve your problem.

### Importing data from a JSON file into R

packages:

• library(httr)
• library(jsonlite)

I have had issues converting json to dataframe/csv. For my case I did:

``````Token <- "245432532532"
source <- "http://......."
full_token <- paste0("Bearer ", Token)
text_json <- content(response, type = 'text', encoding = "UTF-8")
jfile <- fromJSON(text_json)
df <- as.data.frame(jfile)
``````

then from df to csv.

In this format it should be easy to convert it to multiple .csvs if needed.

The important part is content function should have `type = 'text'`.

### Vue.js redirection to another page

According to the docs, router.push seems like the preferred method:

To navigate to a different URL, use router.push. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.

FYI : Webpack & component setup, single page app (where you import the router through Main.js), I had to call the router functions by saying:

``````this.\$router
``````

Example: if you wanted to redirect to a route called "Home" after a condition is met:

``````this.\$router.push('Home')
``````

### git with development, staging and production branches

Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!

### C# MessageBox dialog result

``````DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{
//...
}
else if (result == DialogResult.No)
{
//...
}
else
{
//...
}
``````

### Using Git with Visual Studio

Currently there are 2 options for Git Source Control in Visual Studio (2010 and 12):

I have tried both and have found 1st one to be more mature, and has more features. For instance it plays nicely with both tortoise git and git extensions, and even exposed their features.

Note: Whichever extension you use, make sure that you enable it from `Tools -> Options -> Source control -> Plugin Selection` for it to work.

### How can I debug my JavaScript code?

As with most answers, it really depends: What are you trying to achieve with your debugging? Basic development, fixing performance issues? For basic development, all the previous answers are more than adequate.

For performance testing specifically, I recommend Firebug. Being able to profile which methods are the most expensive in terms of time has been invaluable for a number of projects I have worked on. As client-side libraries become more and more robust, and more responsibility is placed client-side in general, this type of debugging and profiling will only become more useful.

Firebug Console API: http://getfirebug.com/console.html

### WebView and HTML5 <video>

On honeycomb use `hardwareaccelerated=true` and `pluginstate.on_demand` seems to work

### Get Character value from KeyCode in JavaScript... then trim

I know this is an old question, but I came across it today searching for a pre-packaged solution to this problem, and found nothing that really met my needs.

Here is a solution (English only) that correctly supports Upper Case (shifted), Lower Case, punctuation, number keypad, etc.

It also allows for simple and straight-forward identification of - and reaction to - non-printable keys, like ESC, Arrows, Function keys, etc.

https://jsfiddle.net/5hhu896g/1/

``````keyboardCharMap and keyboardNameMap are the key to making this work
``````

Thanks to DaveAlger for saving me some typing - and much discovery! - by providing the Named Key Array.

### Open Jquery modal dialog on click event

``````\$( "#dialog" ).dialog( "open" );
``````

This method worked for me. It seems that the "close" command messes up the dialog opening again with only the .dialog() .

Using your code as an example, it would go in like this (note that you may need to add more to your code for it to make sense):

``````    <script type="text/javascript">
//\$('#dialog').dialog();
\$( "#dialog" ).dialog( "open" );
\$('#dialog').dialog();
return false;
});
});
</script>
<div id="dialog" title="Dialog Title" style="display:none"> Some text</div>
</body></html>
``````

### How to display a database table on to the table in the JSP page

The problem here is very simple. If you want to display value in JSP, you have to use <%= %> tag instead of <% %>, here is the solved code:

```<tr> <td><%=rs.getInt("ID") %></td> <td><%=rs.getString("NAME") %></td> <td><%=rs.getString("SKILL") %></td> </tr>```

### Removing "NUL" characters

This might help, I used to fi my files like this: http://security102.blogspot.ru/2010/04/findreplace-of-nul-objects-in-notepad.html

Basically you need to replace \x00 characters with regular expressions

### When would you use the Builder Pattern?

Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.

As Joshua Bloch states in Effective Java, 2nd Edition:

The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:

``````Pizza(int size) { ... }
Pizza(int size, boolean cheese) { ... }
Pizza(int size, boolean cheese, boolean pepperoni) { ... }
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }
``````

This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

``````Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
``````

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

The better alternative is to use the Builder Pattern.

``````public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;

public static class Builder {
//required
private final int size;

//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;

public Builder(int size) {
this.size = size;
}

public Builder cheese(boolean value) {
cheese = value;
return this;
}

public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}

public Builder bacon(boolean value) {
bacon = value;
return this;
}

public Pizza build() {
return new Pizza(this);
}
}

private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
}
``````

Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.

``````Pizza pizza = new Pizza.Builder(12)
.cheese(true)
.pepperoni(true)
.bacon(true)
.build();
``````

This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.

I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.

There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.

### How to get calendar Quarter from a date in TSQL

Since your date field data is in `int` you will need to convert it to a datetime:

``````declare @date int
set @date = 20080102

SELECT Datename(quarter, Cast(left(@date, 4) + '-'
+ substring(cast(@date as char(8)), 5, 2) + '-'
+ substring(cast(@date as char(8)), 7, 2) as datetime)) as Quarter
``````

or

``````SELECT Datename(quarter, Cast(left(@date, 4) + '-'
+ substring(cast(@date as char(8)), 5, 2) + '-'
+ right(@date, 2) as datetime)) as quarter
``````

Then if you want the `Q1` added:

``````SELECT left(@date, 4) + '-Q' + Convert(varchar(1), Datename(quarter, Cast(left(@date, 4) + '-'
+ substring(cast(@date as char(8)), 5, 2) + '-'
+ right(@date, 2) as datetime))) as quarter
``````

My advice would be to store your `date` data as a `datetime` so then you do not need to perform these conversions.

### How to parse JSON Array (Not Json Object) in Android

``````public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";

JSONArray jsonarray = new JSONArray(str);

for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);

String name = obj.getString("name");
String url = obj.getString("url");

System.out.println(name);
System.out.println(url);
}
}
``````

Output:

``````name1
url1
name2
url2
``````

### How to use subprocess popen Python

In the recent Python version, `subprocess` has a big change. It offers a brand-new class `Popen` to handle `os.popen1|2|3|4`.

The new `subprocess.Popen()`

``````import subprocess
subprocess.Popen('ls -la', shell=True)
``````

Its arguments:

``````subprocess.Popen(args,
bufsize=0,
executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False,
shell=False,
cwd=None, env=None,
universal_newlines=False,
startupinfo=None,
creationflags=0)
``````

Simply put, the new `Popen` includes all the features which were split into 4 separate old `popen`.

The old `popen`:

``````Method  Arguments
popen   stdout
popen2  stdin, stdout
popen3  stdin, stdout, stderr
popen4  stdin, stdout and stderr
``````

You could get more information in Stack Abuse - Robert Robinson. Thank him for his devotion.

### Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

`````` * The arguments which may be supplied in the recovery.command file:
*   --send_intent=anystring - write the text out to recovery.intent
*   --update_package=path - verify install an OTA package file
*   --wipe_data - erase user data (and cache), then reboot
*   --wipe_cache - wipe cache (but not user data), then reboot
*   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
``````

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

``````adb shell
recovery --wipe_data
``````

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

### UL has margin on the left

The `<ul>` element has browser inherent padding & margin by default. In your case, Use

``````#footer ul {
margin: 0; /* To remove default bottom margin */
}
``````

or a CSS browser reset ( https://cssreset.com/ ) to deal with this.

### How can I view the source code for a function?

In RStudio, there are (at least) 3 ways:

1. Press the F2 key while cursor is on any function.
2. Click on the function name while holding Ctrl or Command
3. `View`(function_name) (as stated above)

A new pane will open with the source code. If you reach .Primitive or .C you'll need another method, sorry.

### React component initialize state from props

``````constructor(props) {
super(props);
this.state = {
productdatail: ''
};
}

this.setState({ productdatail: nextProps.productdetailProps })
}
``````

### Using HTTPS with REST in Java

Here's the painful route:

``````    SSLContext ctx = null;
try {
KeyStore trustStore;
trustStore = KeyStore.getInstance("JKS");
"asdfgh".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory
.getInstance("SunX509");
tmf.init(trustStore);
ctx = SSLContext.getInstance("SSL");
ctx.init(null, tmf.getTrustManagers(), null);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
ClientConfig config = new DefaultClientConfig();
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
new HTTPSProperties(null, ctx));

WebResource service = Client.create(config).resource(
"https://localhost:9999/");

// Attempt to view the user's page.
try {
} catch (Exception e) {
e.printStackTrace();
}
``````

Gotta love those six different caught exceptions :). There are certainly some refactoring to simplify the code a bit. But, I like delfuego's -D options on the VM. I wish there was a javax.net.ssl.trustStore static property that I could just set. Just two lines of code and done. Anyone know where that would be?

This may be too much to ask, but, ideally the keytool would not be used. Instead, the trustedStore would be created dynamically by the code and the cert is added at runtime.

There must be a better answer.

### How do I create a singleton service in Angular 2?

Syntax has been changed. Check this link

Dependencies are singletons within the scope of an injector. In below example, a single HeroService instance is shared among the HeroesComponent and its HeroListComponent children.

Step 1. Create singleton class with @Injectable decorator

``````@Injectable()
export class HeroService {
getHeroes() { return HEROES;  }
}
``````

Step 2. Inject in constructor

``````export class HeroListComponent {
constructor(heroService: HeroService) {
this.heroes = heroService.getHeroes();
}
``````

Step 3. Register provider

``````@NgModule({
imports: [
BrowserModule,
FormsModule,
routing,
HttpModule,
JsonpModule
],
declarations: [
AppComponent,
HeroesComponent,
routedComponents
],
providers: [
HeroService
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
``````

### When does Java's Thread.sleep throw InterruptedException?

You should generally NOT ignore the exception. Take a look at the following paper:

Don't swallow interrupts

Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can't rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt() to "reinterrupt" the current thread, as shown in Listing 3. At the very least, whenever you catch InterruptedException and don't rethrow it, reinterrupt the current thread before returning.

``````public class TaskRunner implements Runnable {

this.queue = queue;
}

public void run() {
try {
while (true) {
}
}
catch (InterruptedException e) {
// Restore the interrupted status
}
}
}
``````

See the entire paper here:

http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-

### Sort Pandas Dataframe by Date

The data containing the date column can be read by using the below code:

``````data = pd.csv(file_path,parse_dates=[date_column])
``````

Once the data is read by using the above line of code, the column containing the information about the date can be accessed using `pd.date_time()` like:

``````pd.date_time(data[date_column], format = '%d/%m/%y')
``````

to change the format of date as per the requirement.

If you are so lost for read the last comment. I have reached another solution.

The main problem is the way that you named the services names.

In this case, if in your `docker-compose.yml`, the service for php are called "api" or something like that, you must ensure that in the file `nginx.conf` the line that begins with `fastcgi_pass` have the same name as the php service. i.e `fastcgi_pass api:9000;`

### How to create an android app using HTML 5

you can use webview in android that will use chrome browser Or you can try Phonegap or sencha Touch

### @Scope("prototype") bean scope not creating new bean

As mentioned by nicholas.hauschild injecting Spring context is not a good idea. In your case, @Scope("request") is enough to fix it. But let say you need several instances of `LoginAction` in controller method. In this case, I would recommend to create the bean of Supplier (Spring 4 solution):

``````    @Bean
}
``````

Then inject it into controller:

``````@Controller
public class HomeController {
@Autowired
``````

### Ajax call Into MVC Controller- Url Issue

Starting from Rob's answer, I am currently using the following syntax.Since the question has received a lot of attention,I decided to share it with you :

``````var requrl = '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)';
\$.ajax({
type: "POST",
url: requrl,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
}
});
``````

### How to edit incorrect commit message in Mercurial?

In TortoiseHg, right-click on the revision you want to modify. Choose Modify History->Import MQ. That will convert all the revisions up to and including the selected revision from Mercurial changesets into Mercurial Queue patches. Select the Patch you want to modify the message for, and it should automatically change the screen to the MQ editor. Edit the message which is in the middle of the screen, then click QRefresh. Finally, right click on the patch and choose Modify History->Finish Patch, which will convert it from a patch back into a change set.

Oh, this assumes that MQ is an active extension for TortoiseHG on this repository. If not, you should be able to click File->Settings, click Extensions, and click the mq checkbox. It should warn you that you have to close TortoiseHg before the extension is active, so close and reopen.

### Get parent directory of running script

If your script is located in `/var/www/dir/index.php` then the following would return:

``````dirname(__FILE__); // /var/www/dir
``````

or

``````dirname( dirname(__FILE__) ); // /var/www
``````

#### Edit

This is a technique used in many frameworks to determine relative paths from the app_root.

File structure:

``` /var/
www/
index.php
subdir/
library.php
```

index.php is my dispatcher/boostrap file that all requests are routed to:

``````define(ROOT_PATH, dirname(__FILE__) ); // /var/www
``````

library.php is some file located an extra directory down and I need to determine the path relative to the app root (/var/www/).

``````\$path_current = dirname( __FILE__ ); // /var/www/subdir
\$path_relative = str_replace(ROOT_PATH, '', \$path_current); // /subdir
``````

There's probably a better way to calculate the relative path then `str_replace()` but you get the idea.

### Javascript change font color

Consider changing your markup to this:

``````<span id="someId">onlineff</span>
``````

Then you can use this script:

``````var x = document.getElementById('someId');
x.style.color = '#00FF00';
``````

see it here: http://jsfiddle.net/2ANmM/

### How to fix warning from date() in PHP"

Try to set `date.timezone` in `php.ini` file. Or you can manually set it using `ini_set()` or `date_default_timezone_set()`.

### How do I enable logging for Spring Security?

Spring security logging for webflux reactive apps is now available starting with version 5.4.0-M2 (as mentionned by @bzhu in comment How do I enable logging for Spring Security?)

Until this gets into a GA release, here is how to get this milestone release in gradle

``````repositories {
mavenCentral()
if (!version.endsWith('RELEASE')) {
maven { url "https://repo.spring.io/milestone" }
}
}

// Force earlier milestone release to get securing logging preview
// https://github.com/spring-projects/spring-security/pull/8504
// https://github.com/spring-projects/spring-security/releases/tag/5.4.0-M2
ext['spring-security.version']='5.4.0-M2'
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:\${springCloudVersion}"
}

}
``````

### Could not load type 'XXX.Global'

I solved it with this solution, by giving CREATOR OWNER full rights to the Windows Temp folder. For some reason, that user had no rights at all assigned. Maybe because some time ago I ran Combofix on my computer.

### Javascript - How to extract filename from a file input control

``````var pieces = str.split('\\');
var filename = pieces[pieces.length-1];
``````

### How to solve java.lang.NoClassDefFoundError?

if you are using `gradlew`, go to `./gradle/wrapper/gradle-wrapper.properties` and change `distributionUrl` to the correct version of gradle.

If you are using JDK14 try

``````distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
``````

### Converting XML to JSON using Python?

There is a method to transport XML-based markup as JSON which allows it to be losslessly converted back to its original form. See http://jsonml.org/.

It's a kind of XSLT of JSON. I hope you find it helpful

### set height of imageview as matchparent programmatically

``````imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;
``````

steps to install maven :

2. \$tar xvf apache-maven-3.5.4-bin.tar.gz
3. copy the apache folder to desired place \$cp -R apache-maven-3.5.4 /Users/locals
4. go to apache directory \$cd /Users/locals/apache-maven-3.5.4/
5. create .bash_profile \$vim ~/.bash_profile
6. write these two command : export M2_HOME=/Users/manisha/apache-maven-3.5.4 export PATH=\$PATH:\$M2_HOME/bin 7 save and quit the vim :wq!
7. restart the terminal and type mvn -version

### Secondary axis with twinx(): how to add to legend?

``````ax2.legend(loc=0)
``````

You'll get this:

But if you want all labels on one legend then you should do something like this:

``````import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10

fig = plt.figure()

lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')

lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax2.set_ylabel(r"Temperature (\$^\circ\$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
``````

Which will give you this:

### Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

Most programs will check the `\$EDITOR` environment variable, so you can set that to the path of TextEdit in your bashrc. Git will use this as well.

#### How to do this:

• Add the following to your `~/.bashrc` file:
`export EDITOR="/Applications/TextEdit.app/Contents/MacOS/TextEdit"`
• or just type the following command into your Terminal:
`echo "export EDITOR=\"/Applications/TextEdit.app/Contents/MacOS/TextEdit\"" >> ~/.bashrc`

If you are using zsh, use `~/.zshrc` instead of `~/.bashrc`.

### Interactive shell using Docker Compose

Using docker-compose, I found the easiest way to do this is to do a `docker ps -a` (after starting my containers with `docker-compose up`) and get the ID of the container I want to have an interactive shell in (let's call it xyz123).

Then it's a simple matter to execute `docker exec -ti xyz123 /bin/bash`

and voila, an interactive shell.

### What’s the best way to reload / refresh an iframe?

In IE8 using .Net, setting the `iframe.src` for the first time is ok, but setting the `iframe.src` for the second time is not raising the `page_load` of the iframed page. To solve it i used `iframe.contentDocument.location.href = "NewUrl.htm"`.

Discover it when used jQuery thickBox and tried to reopen same page in the thickbox iframe. Then it just showed the earlier page that was opened.

### How to run a cron job inside a docker container?

So, my problem was the same. The fix was to change the command section in the `docker-compose.yml`.

From

command: crontab /etc/crontab && tail -f /etc/crontab

To

command: crontab /etc/crontab

command: tail -f /etc/crontab

The problem was the '&&' between the commands. After deleting this, it was all fine.

### I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

1. What exactly doesn't work?
2. Why are you using a 2d array?
3. If you must use a 2d array:

``int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } ``

Does this give you a hint?

### How do I remove newlines from a text file?

Using the gedit text editor (3.18.3)

1. Click Search
2. Click Find and Replace...
3. Enter `\n\s` into Find field
4. Leave Replace with blank (nothing)
5. Check Regular expression box
6. Click the Find button

Note: this doesn't exactly address the OP's original, 7 year old problem but should help some noob linux users (like me) who find their way here from the SE's with similar "how do I get my text all on one line" questions.

### Your project path contains non-ASCII characters android studio

This error occur because of path of project. Change your project path wiht way which dont contain nonAscii character.

### SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Look at SignalR Tests for the feature.

Test "SendToUser" takes automatically the user identity passed by using a regular owin authentication library.

The scenario is you have a user who has connected from multiple devices/browsers and you want to push a message to all his active connections.

### What is the difference between JAX-RS and JAX-WS?

Can JAX-RS do Asynchronous Request like JAX-WS?

Yes, it can surely do use @Async

Can JAX-RS access a web service that is not running on the Java platform, and vice versa?

Yes, it can Do

What does it mean by "REST is particularly useful for limited-profile devices, such as PDAs and mobile phones"?

It is mainly use for public apis it depends on which approach you want to use.

What does it mean by "JAX-RS do not require XML messages or WSDL service–API definitions?

It has its own standards WADL(Web application Development Language) it has http request by which you can access resources they are altogether created by different mindset,In case in Jax-Rs you have to think of exposing resources

### React Native absolute positioning horizontal centre

You can center absolute items by providing the left property with the width of the device divided by two and subtracting out half of the element you'd like to center's width.

For example, your style might look something like this.

``````bottom: {
position: 'absolute',
left: (Dimensions.get('window').width / 2) - 25,
top: height*0.93,
}
``````

### Pass array to ajax request in \$.ajax()

``````info = [];
info[0] = 'hi';
info[1] = 'hello';

\$.ajax({
type: "POST",
data: {info:info},
url: "index.php",
success: function(msg){
}
});
``````

### The point of test %eax %eax

This checks if `EAX` is zero. The instruction `test` does bitwise `AND` between the arguments, and if `EAX` contains zero, the result sets the ZF, or ZeroFlag.

### Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

Found the flex magic.

Here's an example of how to do a fixed header and a scrollable content. Code:

``````<!DOCTYPE html>
<html style="height: 100%">
<meta charset=utf-8 />
<title>Holy Grail</title>
<!-- Reset browser defaults -->
<body style="display: flex; height: 100%; flex-direction: column">
</div>
<div style="flex: 1; overflow: auto">
CONTENT - START<br/>
<script>
for (var i=0 ; i<1000 ; ++i) {
document.write(" Very long content!");
}
</script>
<br/>CONTENT - END
</div>
</body>
</html>
``````

* The advantage of the flex solution is that the content is independent of other parts of the layout. For example, the content doesn't need to know height of the header.

For a full Holy Grail implementation (header, footer, nav, side, and content), using flex display, go to here.

### Git's famous "ERROR: Permission to .git denied to user"

I encountered this error when using Travis CI to deploy content, which involved pushing edits to a repository.

I eventually solved the issue by updating the GitHub personal access token associated with the Travis account with the `public_repo` scope access permission:

### How to remove a Gitlab project?

• 4.Select Settings (from left sidebar)
• 5.Click Advanced settings Expand the Advanced settings this will be middle of the page
• 6.Click Remove
• 7.Project In the Modal write your project name

Hope you can Successfully remove your project. Happy Coding :)

### PHP - auto refreshing page

This works with Firefox Quantum 60+ and Chrome v72 (2019)

``````//set a header to instruct the browser to call the page every 30 sec
``````

It does not seem to be NECESSARY to pass the page url as well as the refresh period in order to (re)call the same page. I haven't tried this with Safari/Opera or IE/Edge.

### Finding first blank row, then writing to it

I would have done it like this. Short and sweet :)

``````Sub test()
Dim rngToSearch As Range
Dim FirstBlankCell As Range
Dim firstEmptyRow As Long

Set rngToSearch = Sheet1.Range("A:A")
'Check first cell isn't empty
If IsEmpty(rngToSearch.Cells(1, 1)) Then
firstEmptyRow = rngToSearch.Cells(1, 1).Row
Else
Set FirstBlankCell = rngToSearch.FindNext(After:=rngToSearch.Cells(1, 1))
If Not FirstBlankCell Is Nothing Then
firstEmptyRow = FirstBlankCell.Row
Else
'no empty cell in range searched
End If
End If
End Sub
``````

Updated to check if first row is empty.

Edit: Update to include check if entire row is empty

``````Option Explicit

Sub test()
Dim rngToSearch As Range
Dim firstblankrownumber As Long

Set rngToSearch = Sheet1.Range("A1:C200")
firstblankrownumber = FirstBlankRow(rngToSearch)
Debug.Print firstblankrownumber

End Sub

Function FirstBlankRow(ByVal rngToSearch As Range, Optional activeCell As Range) As Long
Dim FirstBlankCell As Range

If activeCell Is Nothing Then Set activeCell = rngToSearch.Cells(1, 1)
'Check first cell isn't empty
If WorksheetFunction.CountA(rngToSearch.Cells(1, 1).EntireRow) = 0 Then
FirstBlankRow = rngToSearch.Cells(1, 1).Row
Else

Set FirstBlankCell = rngToSearch.FindNext(After:=activeCell)
If Not FirstBlankCell Is Nothing Then

If WorksheetFunction.CountA(FirstBlankCell.EntireRow) = 0 Then
FirstBlankRow = FirstBlankCell.Row
Else
Set activeCell = FirstBlankCell
FirstBlankRow = FirstBlankRow(rngToSearch, activeCell)

End If
Else
'no empty cell in range searched
End If
End If
End Function
``````

### Prevent row names to be written to file when using write.csv

``````write.csv(t, "t.csv", row.names=FALSE)
``````

From `?write.csv`:

``````row.names: either a logical value indicating whether the row names of
‘x’ are to be written along with ‘x’, or a character vector
of row names to be written.
``````

### How do I select an element in jQuery by using a variable for the ID?

The shortest way would be:

``````\$("#" + row_id)
``````

Limiting the search to the body doesn't have any benefit.

Also, you should consider renaming your `id`s to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.

### How do I hide the PHP explode delimiter from submitted form results?

``<select name="FakeName" id="Fake-ID" aria-required="true" required>  <?php \$options=nl2br(file_get_contents("employees.txt")); \$options=explode("<br />",\$options);  foreach (\$options as \$item_array) { echo "<option value='".\$item_array"'>".\$item_array"</option>";  } ?> </select> ``

### Change text color with Javascript?

Try below code:

``````\$(document).ready(function(){
});
``````

http://jsfiddle.net/jPCFC/

### How to fix "Referenced assembly does not have a strong name" error?

Situation: You had project A,B,C,D in solution X,Y

Project A, B, C in X Project A, C, D in Y

I need use project C in project A, but later i dont use. In bin Debug project A had C.dll.

If I compile solution X, all good ( in this solution i delete reference A -> C. ), but in solution Y I get this problem.

Solution is delete C.dll in project A bin Debug

### How can I read and manipulate CSV file data in C++?

But the simplest form:

``````#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

int main()
{
std::ifstream  data("plop.csv");

std::string line;
while(std::getline(data,line))
{
std::stringstream  lineStream(line);
std::string        cell;
while(std::getline(lineStream,cell,','))
{
// You have a cell!!!!
}
}
}
``````

Also see this question: CSV parser in C++

### Optional query string parameters in ASP.NET Web API

if you want to pass multiple parameters then you can create model instead of passing multiple parameters.

in case you dont want to pass any parameter then you can skip as well in it, and your code will look neat and clean.

### Delete a database in phpMyAdmin

Taking a queue from michael's answer above, I was unable to find the DROP Database command on my `phpMyAdmin` console in the `localhost`.

Apparantly I was missing a setting. Go to `config.inc.php` file of the `phpMyAdmin` folder, and add this:

`\$cfg['AllowUserDropDatabase'] = true;`

Save and restart the local server and the command appears inside the console.

### Const in JavaScript: when to use it and is it necessary?

`const` is not immutable.

From the MDN:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

### Colors in JavaScript console

There are a series of inbuilt functions for coloring the console log:

``````//For pink background and red text
console.error("Hello World");

//For yellow background and brown text
console.warn("Hello World");

//For just a INFO symbol at the beginning of the text
console.info("Hello World");

//for custom colored text
console.log('%cHello World','color:blue');
//here blue could be replaced by any color code

//for custom colored text with custom background text
console.log('%cHello World','background:red;color:#fff')
``````

### Redirect using AngularJS

It is hard to say without knowing your code. My best guess is that the `onchange` event is not firing when you change your textbox value from JavaScript code.

There are two ways for this to work; the first is to call `onchange` by yourself, and the second is to wait for the textbox to lose focus.

Check this question; same issue, different framework.

### what does "error : a nonstatic member reference must be relative to a specific object" mean?

Only static functions are called with class name.

``````classname::Staicfunction();
``````

Non static functions have to be called using objects.

``````classname obj;
obj.Somefunction();
``````

This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.

### html table cell width for different rows

As far as i know that is impossible and that makes sense since what you are trying to do is against the idea of tabular data presentation. You could however put the data in multiple tables and remove any padding and margins in between them to achieve the same result, at least visibly. Something along the lines of:

_x000D_
_x000D_
``````<html>_x000D_
_x000D_
<style type="text/css">_x000D_
.mytable {_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
background-color: white;_x000D_
}_x000D_
border: 1px solid black;_x000D_
margin-bottom: 0;_x000D_
}_x000D_
border: 1px solid black;_x000D_
}_x000D_
.mytable-body {_x000D_
border: 1px solid black;_x000D_
border-top: 0;_x000D_
margin-top: 0;_x000D_
margin-bottom: 0;_x000D_
}_x000D_
.mytable-body td {_x000D_
border: 1px solid black;_x000D_
border-top: 0;_x000D_
}_x000D_
.mytable-footer {_x000D_
border: 1px solid black;_x000D_
border-top: 0;_x000D_
margin-top: 0;_x000D_
}_x000D_
.mytable-footer td {_x000D_
border: 1px solid black;_x000D_
border-top: 0;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<body>_x000D_
<tr>_x000D_
<td width="25%">25</td>_x000D_
<td width="50%">50</td>_x000D_
<td width="25%">25</td>_x000D_
</tr>_x000D_
</table>_x000D_
<table class="mytable mytable-body">_x000D_
<tr>_x000D_
<td width="50%">50</td>_x000D_
<td width="30%">30</td>_x000D_
<td width="20%">20</td>_x000D_
</tr>_x000D_
</table>_x000D_
<table class="mytable mytable-body">_x000D_
<tr>_x000D_
<td width="16%">16</td>_x000D_
<td width="68%">68</td>_x000D_
<td width="16%">16</td>_x000D_
</tr>_x000D_
</table>_x000D_
<table class="mytable mytable-footer">_x000D_
<tr>_x000D_
<td width="20%">20</td>_x000D_
<td width="30%">30</td>_x000D_
<td width="50%">50</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
_x000D_
</html>``````
_x000D_
_x000D_
_x000D_

JSFIDDLE

I don't know your requirements but i'm sure there's a more elegant solution.

### C++ cout hex values?

Use:

``````#include <iostream>

...

std::cout << std::hex << a;
``````

There are many other options to control the exact formatting of the output number, such as leading zeros and upper/lower case.

### How to create a new instance from a class object in Python

Just call the "type" built in using three parameters, like this:

``````ClassName = type("ClassName", (Base1, Base2,...), classdictionary)
``````

update as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.

To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:

``````instance = ClassObject()
``````

The mechanism for instantiation is thus:

Python does not use the `new` keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:

Its class' `__call__` method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in `type`). The normal behavior of this call is to invoke the (pseudo) static `__new__` method on the class being instantiated, followed by its `__init__`. The `__new__` method is responsible for allocating memory and such, and normally is done by the `__new__` of `object` which is the class hierarchy root.

So calling `ClassObject()` invokes `ClassObject.__class__.call()` (which normally will be `type.__call__`) this `__call__` method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)

``````class type:
...
def __call__(cls, *args, **kw):
constructor = getattr(cls, "__new__")
instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
instance.__init__(cls, *args, **kw)
return instance
``````

(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root `__new__` and passing it to other classes - but it is what happen "in real life" - if `object.__new__` is called with any extra parameters it raises a type error - however, any custom implementation of a `__new__` will get the extra parameters normally)

### Changing the browser zoom level

Possible in IE and chrome although it does not work in firefox:

``````<script>
function toggleZoomScreen() {
document.body.style.zoom = "80%";
}
</script>

<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">
``````

### Exception of type 'System.OutOfMemoryException' was thrown. Why?

Where does it fail?

I agree that your issue is probably that your dataset of 600,000 rows is probably just too large. I see that you are then adding it to Session. If you are using Sql session state, it will have to serialize that data as well.

Even if you dispose of your objects properly, you will always have at least 2 copies of this dataset in memory if you run it twice, once in session, once in procedural code. This will never scale in a web application.

Do the math, 600,000 rows, at even 1-128 bit guid per row would yield 9.6 megabytes (600k * 128 / 8) of just data, not to mention the dataset overhead.

### How do I set a program to launch at startup

In addition to Xepher Dotcom's answer, folder path to Windows Startup should be coded that way:

``````var Startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
``````

### Convert string to float?

``````String s = "3.14";
float f = Float.parseFloat(s);
``````

### Best way to use multiple SSH private keys on one client

``````ssh-add ~/.ssh/xxx_id_rsa
``````

Make sure you test it before adding with:

``````ssh -i ~/.ssh/xxx_id_rsa [email protected]
``````

If you have any problems with errors sometimes changing the security of the file helps:

``````chmod 0600 ~/.ssh/xxx_id_rsa
``````

### C++ convert string to hexadecimal and vice versa

This will convert Hello World to 48656c6c6f20576f726c64 and print it.

``````#include <iostream>
#include <cstring>

using namespace std;

int main()
{
char hello[20]="Hello World";

for(unsigned int i=0; i<strlen(hello); i++)
cout << hex << (int) hello[i];
return 0;
}
``````

### PHP code to get selected text of a combo box

Try with this. You will get the select box value in \$_POST['Make'] and name will get in \$_POST['selected_text']

``````<form method="POST" >
<label for="Manufacturer"> Manufacturer : </label>
<select id="cmbMake" name="Make"     onchange="document.getElementById('selected_text').value=this.options[this.selectedIndex].text">
<option value="0">Select Manufacturer</option>
<option value="1">--Any--</option>
<option value="2">Toyota</option>
<option value="3">Nissan</option>
</select>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>

<?php

if(isset(\$_POST['search']))
{

\$makerValue = \$_POST['Make']; // make value

\$maker = mysql_real_escape_string(\$_POST['selected_text']); // get the selected text
echo \$maker;
}
?>
``````

### Ignore mapping one property with Automapper

From Jimmy Bogard: `CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());`

It's in one of the comments at his blog.

### Finding the type of an object in C++

Because your class is not polymorphic. Try:

``````struct BaseClas { int base; virtual ~BaseClas(){} };
class Derived1 : public BaseClas { int derived1; };
``````

Now `BaseClas` is polymorphic. I changed class to struct because the members of a struct are public by default.

### How can I jump to class/method definition in Atom text editor?

Use atom-ctags as a package for C language with all things you need:

• Generated ctags for your project. Auto-complete.
• Go to declaration: Ctrl+Alt+Down and Alt+Click by default.
• There are customizable options for Click action.

### Preprocessor check if multiple defines are not defined

FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.

main.c has a main wrapper like this:

``````#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
// the true main() routine.
}
``````

spi.c, serial.c and usb.c have main wrappers for their respective test code like this:

``````#ifdef TEST_USB
int main(int argc, char *argv[]) {
// the  main() routine for testing the usb code.
}
``````

config.h Which is included by all the c files has an entry like this:

``````// Uncomment below to test the serial
//#define TEST_SERIAL

// Uncomment below to test the spi code
//#define TEST_SPI

// Uncomment below to test the usb code
#define TEST_USB
``````

### Python Matplotlib figure title overlaps axes label when using twiny

I was having an issue with the x-label overlapping a subplot title; this worked for me:

``````import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 1)
ax[0].scatter(...)
ax[1].scatter(...)
plt.tight_layout()
.
.
.
plt.show()
``````

# after

reference:

### handling DATETIME values 0000-00-00 00:00:00 in JDBC

My point is that I just want the raw DATETIME string, so I can parse it myself as is.

That makes me think that your "workaround" is not a workaround, but in fact the only way to get the value from the database into your code:

``````SELECT CAST(add_date AS CHAR) as add_date
``````

By the way, some more notes from the MySQL documentation:

Before MySQL 5.0.2, MySQL is forgiving of illegal or improper data values and coerces them to legal values for data entry. In MySQL 5.0.2 and up, that remains the default behavior, but you can change the server SQL mode to select more traditional treatment of bad values such that the server rejects them and aborts the statement in which they occur.

[..]

If you try to store NULL into a column that doesn't take NULL values, an error occurs for single-row INSERT statements. For multiple-row INSERT statements or for INSERT INTO ... SELECT statements, MySQL Server stores the implicit default value for the column data type.

MySQL 5.x Date and Time Types:

MySQL also allows you to store '0000-00-00' as a “dummy date” (if you are not using the NO_ZERO_DATE SQL mode). This is in some cases more convenient (and uses less data and index space) than using NULL values.

[..]

By default, when MySQL encounters a value for a date or time type that is out of range or otherwise illegal for the type (as described at the beginning of this section), it converts the value to the “zero” value for that type.

Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that's 8 concurrent requests.

Flask doesn't spawn or manage threads or processes. That's the responsability of the WSGI gateway (eg. gunicorn).

### Difference between chr(13) and chr(10)

`Chr(10)` is the Line Feed character and `Chr(13)` is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.

Historically, Line Feed would move down a line but not return to column 1:

``````This
is
a
test.
``````

Similarly Carriage Return would return to column 1 but not move down a line:

``````This
is
a
test.
``````

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

### Jquery Ajax Posting json to webservice

I have query,

``````\$("#login-button").click(function(e){ alert("hiii");

\$.ajax({
type: "POST",
url: url,
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify(markers),
contentType: "application/json; charset=utf-8",
dataType: "json",
failure: function(errMsg) {
}
});

});
``````

I'm posting the the login details in json and getting a string as `"Success"`,but I'm not getting the response.

### How to completely uninstall Android Studio on Mac?

You may also delete gradle file, if you don't use gradle any where else:

``````rm -Rfv ~/.gradle/
``````

because .gradle folder contains cached artifacts that are no longer needed.

### How do I get the full url of the page I am on in C#

I usually use `Request.Url.ToString()` to get the full url (including querystring), no concatenation required.

### How can I find last row that contains data in a specific column?

``````Function GetLastRow(strSheet, strColumn) As Long
Dim MyRange As Range

Set MyRange = Worksheets(strSheet).Range(strColumn & "1")
GetLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).Row
End Function
``````

Regarding a comment, this will return the row number of the last cell even when only a single cell in the last row has data:

``````Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
``````

You may need to change the Appication Pool setting "Enable 32bit Applications" to TRUE in IIS7 if you have at least 1 32bit dll\exe in your project.

### How to make html <select> element look like "disabled", but pass values?

if you don't want add the attr disabled can do it programmatically

can disable the edition into the `<select class="yourClass">` element with this code:

``````//bloqueo selects
//block all selects
jQuery(document).on("focusin", 'select.yourClass', function (event) {
var \$selectDiabled = jQuery(this).attr('disabled', 'disabled');
setTimeout(function(){ \$selectDiabled.removeAttr("disabled"); }, 30);
});
``````

if you want try it can see it here: https://jsfiddle.net/9kjqjLyq/

### How do I add a resources folder to my Java project in Eclipse

After adding a resource folder try this :

``````ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

try {
} catch (IOException e) {
e.printStackTrace();
}
``````

### Reading NFC Tags with iPhone 6 / iOS 8

The iPhone6/6s/6+ are NOT designed to read passive NFC tags (aka Discovery Mode). There's a lot of misinformation on this topic, so I thought to provide some tangible info for developers to consider. The lack of NFC tag read support is not because of software but because of hardware. To understand why, you need to understand how NFC works. NFC works by way of Load Modulation. That means that the interrogator (PCD) emits a carrier magnetic field that energizes the passive target (PICC). With the potential generated by this carrier field, the target then is able to demodulate data coming from the interrogator and respond by modulating data over top of this very same field. The key here is that the target never creates a field of its own.

If you look at the iPhone6 teardown and parts list you will see the presence of a very small NFC loop antenna as well as the use of the AS3923 booster IC. This design was intended for custom microSD or SIM cards to enable mobile phones of old to do payments. This is the type of application where the mobile phone presents a Card Emulated credential to a high power contactless POS terminal. The POS terminal acts as the reader, energizing the iPhone6 with help from the AS3923 chip. The AS3923 block diagram clearly shows how the RX and TX modulation is boosted from a signal presented by a reader device. In other words the iPhone6 is not meant to provide a field, only to react to one. That's why it's design is only meant for NFC Card Emulation and perhaps Peer-2-Peer, but definitely not tag Discovery.

There are some alternatives to achieving tag Discovery with an iPhone6 using HW accessories. I talk about these integrations and how developers can architect solutions in this blog post. Our low power reader designs open interesting opportunities for mobile engagement that few developers are thinking about.

Disclosure: I'm the founder of Flomio, Inc., a TechStars company that delivers proximity ID hardware, software, and services for applications ranging from access control to payments.

Update: This rumor, if true, would open up the possibility for the iPhone to practically support NFC tag Discovery mode. An all glass design would not interfere with the NFC antenna as does the metal back of the current iPhone. We've attempted this design approach --albeit with cheaper materials-- on some of our custom reader designs with success so looking forward to this improvement.

Update: iOS11 has announced support for "NFC reader mode" for iPhone7/7+. Details here. API only supports reading NDEF messages (no ISO7816 APDUs) while an app is in the foreground (no background detection). Due out in the Fall, 2017... check the screenshot from WWDC keynote:

This limit is indeed not specified, however their TOS mentions that: "FOR EXAMPLE, WE DON’T MAKE ANY COMMITMENTS ABOUT THE CONTENT WITHIN THE SERVICES, THE SPECIFIC FUNCTIONS OF THE SERVICES, OR THEIR RELIABILITY, AVAILABILITY, OR ABILITY TO MEET YOUR NEEDS. WE PROVIDE THE SERVICES “AS IS”. "

This means to me that the download limit is calculated based on a set of factors that describe the user and is subject to change from one to another.

### What's the whole point of "localhost", hosts and ports at all?

I heard a good description (parable) which illustrates ports as different delivery points for a large building, e.g. Post office for letters and small parcels, Goods In for large deliveries / pallets, Doors for people.

### possibly undefined macro: AC_MSG_ERROR

For Debian. Required packages are: m4 automake pkg-config libtool

### Java image resize, maintain aspect ratio

This is my solution:

``````/*
Change dimension of Image
*/
public static Image resizeImage(Image image, int scaledWidth, int scaledHeight, boolean preserveRatio) {

if (preserveRatio) {
double imageHeight = image.getHeight();
double imageWidth = image.getWidth();

if (imageHeight/scaledHeight > imageWidth/scaledWidth) {
scaledWidth = (int) (scaledHeight * imageWidth / imageHeight);
} else {
scaledHeight = (int) (scaledWidth * imageHeight / imageWidth);
}
}
BufferedImage inputBufImage = SwingFXUtils.fromFXImage(image, null);
// creates output image
BufferedImage outputBufImage = new BufferedImage(scaledWidth, scaledHeight, inputBufImage.getType());
// scales the input image to the output image
Graphics2D g2d = outputBufImage.createGraphics();
g2d.drawImage(inputBufImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
return SwingFXUtils.toFXImage(outputBufImage, null);
}
``````

### jQuery AutoComplete Trigger Change Event

Here is a relatively clean solution for others looking up this topic:

``````// run when eventlistener is triggered
\$("#CompanyList").on( "autocompletechange", function(event,ui) {
// post value to console for validation
console.log(\$(this).val());
});
``````

Per api.jqueryui.com/autocomplete/, this binds a function to the eventlistener. It is triggered both when the user selects a value from the autocomplete list and when they manually type in a value. The trigger fires when the field loses focus.

### How to get file creation date/time in Bash/Debian?

As @mikyra explained, creation date time is not stored anywhere.

All the methods above are nice, but if you want to quickly get only last modify date, you can type:

``````ls -lit /path
``````

with -t option you list all file in /path odered by last modify date.

### Simple two column html layout without using tables

``````<style type="text/css">
#wrap {
width:600px;
margin:0 auto;
}
#left_col {
float:left;
width:300px;
}
#right_col {
float:right;
width:300px;
}
</style>

<div id="wrap">
<div id="left_col">
...
</div>
<div id="right_col">
...
</div>
</div>
``````

Make sure that the sum of the colum-widths equals the wrap width. Alternatively you can use percentage values for the width as well.

For more info on basic layout techniques using CSS have a look at this tutorial

### Android Service Stops When App Is Closed

From Android O, you cant use the services for the long running background operations due to this, https://developer.android.com/about/versions/oreo/background . Jobservice will be the better option with Jobscheduler implementation.

### Implementing autocomplete

I have created a module for anuglar2 autocomplete In this module you can use array, or url npm link : ang2-autocomplete

### how to make log4j to write to the console as well

Write the root logger as below for logging on both console and FILE

log4j.rootLogger=ERROR,console,FILE

And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).

### jquery's append not working with svg element?

`````` var svg; // if you have variable declared and not assigned value.
// then you make a mistake by appending elements to that before creating element
svg.appendChild(document.createElement("g"));
// at some point you assign to svg
svg = document.createElementNS('http://www.w3.org/2000/svg', "svg")
// then you put it in DOM
document.getElementById("myDiv").appendChild(svg)
// it wont render unless you manually change myDiv DOM with DevTools

// to fix assign before you append
var svg = createElement("svg", [
["version", "1.2"],
["aria-labelledby", "title"],
["role", "img"],
["class", "graph"]
]);
function createElement(tag, attributeArr) {
// .createElementNS  NS is must! Does not draw without
let elem = document.createElementNS('http://www.w3.org/2000/svg', tag);
attributeArr.forEach(element => elem.setAttribute(element[0], element[1]));
return elem;
}
// extra: <circle> for example requires attributes to render. Check if missing.
``````

### What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

#### `bootstrap.yml` or `bootstrap.properties`

It's only used/needed if you're using Spring Cloud and your application's configuration is stored on a remote configuration server (e.g. Spring Cloud Config Server).

From the documentation:

A Spring Cloud application operates by creating a "bootstrap" context, which is a parent context for the main application. Out of the box it is responsible for loading configuration properties from the external sources, and also decrypting properties in the local external configuration files.

Note that the `bootstrap.yml` or `bootstrap.properties` can contain additional configuration (e.g. defaults) but generally you only need to put bootstrap config here.

Typically it contains two properties:

• location of the configuration server (`spring.cloud.config.uri`)
• name of the application (`spring.application.name`)

Upon startup, Spring Cloud makes an HTTP call to the config server with the name of the application and retrieves back that application's configuration.

#### `application.yml` or `application.properties`

Contains standard application configuration - typically default configuration since any configuration retrieved during the bootstrap process will override configuration defined here.

### Inversion of Control vs Dependency Injection

IOC - DIP - DI

1. Inversion of Control (IOC)
2. Dependency Inversion Principle (DIP)
3. Dependency Injection (DI)

1- IOC: abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to procedural programming.

2-DIP: is Object Oriented Programming(OOP) principle(D of SOLID).

3-DI: is a software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle.

### Rails: How do I create a default value for attributes in Rails activerecord's model?

You can set a default option for the column in the migration

``````....
add_column :status, :string, :default => "P"
....
``````

OR

You can use a callback, `before_save`

``````class Task < ActiveRecord::Base
before_save :default_values
def default_values
self.status ||= 'P' # note self.status = 'P' if self.status.nil? might be safer (per @frontendbeauty)
end
end
``````

### How to specify a editor to open crontab file? "export EDITOR=vi" does not work

You can use below command to open it in VIM editor.

``````export VISUAL=vim; crontab -e
``````

### Nth max salary in Oracle

``````Select min(salary) from (
select distinct(salary) from empdetails order by salary desc
) where rownum <=&rn
``````

Just enter nth number which you want.

### Measure the time it takes to execute a t-sql query

If you want a more accurate measurement than the answer above:

``````set statistics time on

-- Query 1 goes here

-- Query 2 goes here

set statistics time off
``````

The results will be in the Messages window.

Update (2015-07-29):

By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by `sys.dm_exec_procedure_stats` that may also be of value:

``````-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.

-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';

AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
(OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
(DB_NAME(database_id)=@DbName OR @DbName IS NULL)
``````

### Why doesn't importing java.util.* include Arrays and Lists?

Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.

#### Update

It gives that warning because your the line should actually be

``````List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();
``````

You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.

### AVD Manager - No system image installed for this target

you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

if not installed ARM EABI v7a System Image, you should install all.

### How do I get hour and minutes from NSDate?

Use an NSDateFormatter to convert `string1` into an `NSDate`, then get the required NSDateComponents:

Obj-C:

``````NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"<your date format goes here"];
NSDate *date = [dateFormatter dateFromString:string1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
``````

Swift 1 and 2:

``````let dateFormatter = NSDateFormatter()
let date = dateFormatter.dateFromString(string1)
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Hour, .Minute], fromDate: date)
let hour = comp.hour
let minute = comp.minute
``````

Swift 3:

``````let dateFormatter = DateFormatter()
let date = dateFormatter.date(from: string1)
let calendar = Calendar.current
let comp = calendar.dateComponents([.hour, .minute], from: date)
let hour = comp.hour
let minute = comp.minute
``````

More about the dateformat is on the official unicode site

### enabling cross-origin resource sharing on IIS7

Alsalaam Aleykum.

Which corresponds to these configuration:

_x000D_
_x000D_
``````<handlers>_x000D_
<clear />_x000D_
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" type="" modules="ProtocolSupportModule" scriptProcessor="" resourceType="Unspecified" requireAccess="Read" allowPathInfo="false" preCondition="" responseBufferLimit="4194304" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="4194304" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="4194304" />_x000D_
resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
<add name="rules-ISAPI-4.0_64bit" path="*.rules" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
responseBufferLimit="4194304" />_x000D_
<add name="rules-ISAPI-4.0_32bit" path="*.rules" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
responseBufferLimit="4194304" />_x000D_
scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
<add name="xoml-ISAPI-4.0_64bit" path="*.xoml" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
responseBufferLimit="4194304" />_x000D_
<add name="xoml-ISAPI-4.0_32bit" path="*.xoml" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
responseBufferLimit="4194304" />_x000D_
scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
<add name="svc-ISAPI-4.0_64bit" path="*.svc" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
responseBufferLimit="4194304" />_x000D_
<add name="svc-ISAPI-4.0_32bit" path="*.svc" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
responseBufferLimit="4194304" />_x000D_
resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
<add name="ISAPI-dll" path="*.dll" verb="*" type="" modules="IsapiModule" scriptProcessor="" resourceType="File" requireAccess="Execute" allowPathInfo="true" preCondition="" responseBufferLimit="4194304" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
<add name="aspq-ISAPI-4.0_64bit" path="*.aspq" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
responseBufferLimit="4194304" />_x000D_
responseBufferLimit="4194304" />_x000D_
preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
responseBufferLimit="4194304" />_x000D_
responseBufferLimit="4194304" />_x000D_
responseBufferLimit="4194304" />_x000D_
responseBufferLimit="4194304" />_x000D_
responseBufferLimit="4194304" />_x000D_
scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
<add name="aspq-ISAPI-4.0_32bit" path="*.aspq" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
<add name="TRACEVerbHandler" path="*" verb="TRACE" type="" modules="ProtocolSupportModule" scriptProcessor="" resourceType="Unspecified" requireAccess="None" allowPathInfo="false" preCondition="" responseBufferLimit="4194304" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />_x000D_
<add name="StaticFile" path="*" verb="*" type="" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" scriptProcessor="" resourceType="Either" requireAccess="Read" allowPathInfo="false" preCondition="" responseBufferLimit="4194304"_x000D_
/>_x000D_
</handlers>``````
_x000D_
_x000D_
_x000D_

The second way is as to respond to the HTTP OPTIONS verb in your BeginRequest method.

``````  protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{

HttpContext.Current.Response.End();
}
}
``````

### Java associative-array

Java doesn't support associative arrays, however this could easily be achieved using a `Map`. E.g.,

``````Map<String, String> map = new HashMap<String, String>();
map.put("name", "demo");
map.put("fname", "fdemo");
// etc

map.get("name"); // returns "demo"
``````

Even more accurate to your example (since you can replace String with any object that meet your needs) would be to declare:

``````List<Map<String, String>> data = new ArrayList<>();
data.get(0).get("name");
``````

### calling a java servlet from javascript

I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.

This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.

### How to add more than one machine to the trusted hosts list using winrm

The suggested answer by Loïc MICHEL blindly writes a new value to the TrustedHosts entry.
I believe, a better way would be to first query TrustedHosts.
As Jeffery Hicks posted in 2010, first query the TrustedHosts entry:

``````PS C:\> \$current=(get-item WSMan:\localhost\Client\TrustedHosts).value
PS C:\> \$current+=",testdsk23,alpha123"
PS C:\> set-item WSMan:\localhost\Client\TrustedHosts –value \$current
``````

### How to fix HTTP 404 on Github Pages?

in my case i had to go to project settings and enable the github pages. The default is off