# Programs & Examples On #Graphml

File-format for graphs which consists of a language core to describe the structural properties of a graph and a flexible extension mechanism to add application-specific data

### How to get coordinates of an svg element?

You can use the function getBBox() to get the bounding box for the path. This will give you the position and size of the tightest rectangle that could contain the rendered path.

An advantage of using this method over reading the x and y values is that it will work with all graphical objects. There are more objects than paths that do not have x and y, for example circles that have cx and cy instead.

### Byte Array and Int conversion in Java

Your methods should be (something like)

``````public static int byteArrayToInt(byte[] b)
{
return   b[3] & 0xFF |
(b[2] & 0xFF) << 8 |
(b[1] & 0xFF) << 16 |
(b[0] & 0xFF) << 24;
}

public static byte[] intToByteArray(int a)
{
return new byte[] {
(byte) ((a >> 24) & 0xFF),
(byte) ((a >> 16) & 0xFF),
(byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF)
};
}
``````

These methods were tested with the following code :

``````Random rand = new Random(System.currentTimeMillis());
byte[] b;
int a, v;
for (int i=0; i<10000000; i++) {
a = rand.nextInt();
b = intToByteArray(a);
v = byteArrayToInt(b);
if (a != v) {
System.out.println("ERR! " + a + " != " + Arrays.toString(b) + " != " + v);
}
}
System.out.println("Done!");
``````

### POST string to ASP.NET Web Api application - returns null

``````([FromBody] IDictionary<string,object> data)
``````

### API pagination best practices

There may be two approaches depending on your server side logic.

Approach 1: When server is not smart enough to handle object states.

You could send all cached record unique id’s to server, for example ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10"] and a boolean parameter to know whether you are requesting new records(pull to refresh) or old records(load more).

Your sever should responsible to return new records(load more records or new records via pull to refresh) as well as id’s of deleted records from ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10"].

Example:- If you are requesting load more then your request should look something like this:-

``````{
"isRefresh" : false,
"cached" : ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10"]
}
``````

Now suppose you are requesting old records(load more) and suppose "id2" record is updated by someone and "id5" and "id8" records is deleted from server then your server response should look something like this:-

``````{
"records" : [
{"id" :"id2","more_key":"updated_value"},
{"id" :"id11","more_key":"more_value"},
{"id" :"id12","more_key":"more_value"},
{"id" :"id13","more_key":"more_value"},
{"id" :"id14","more_key":"more_value"},
{"id" :"id15","more_key":"more_value"},
{"id" :"id16","more_key":"more_value"},
{"id" :"id17","more_key":"more_value"},
{"id" :"id18","more_key":"more_value"},
{"id" :"id19","more_key":"more_value"},
{"id" :"id20","more_key":"more_value"}],
"deleted" : ["id5","id8"]
}
``````

But in this case if you’ve a lot of local cached records suppose 500, then your request string will be too long like this:-

``````{
"isRefresh" : false,
"cached" : ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10",………,"id500"]//Too long request
}
``````

Approach 2: When server is smart enough to handle object states according to date.

You could send the id of first record and the last record and previous request epoch time. In this way your request is always small even if you’ve a big amount of cached records

Example:- If you are requesting load more then your request should look something like this:-

``````{
"isRefresh" : false,
"firstId" : "id1",
"lastId" : "id10",
"last_request_time" : 1421748005
}
``````

Your server is responsible to return the id’s of deleted records which is deleted after the last_request_time as well as return the updated record after last_request_time between "id1" and "id10" .

``````{
"records" : [
{"id" :"id2","more_key":"updated_value"},
{"id" :"id11","more_key":"more_value"},
{"id" :"id12","more_key":"more_value"},
{"id" :"id13","more_key":"more_value"},
{"id" :"id14","more_key":"more_value"},
{"id" :"id15","more_key":"more_value"},
{"id" :"id16","more_key":"more_value"},
{"id" :"id17","more_key":"more_value"},
{"id" :"id18","more_key":"more_value"},
{"id" :"id19","more_key":"more_value"},
{"id" :"id20","more_key":"more_value"}],
"deleted" : ["id5","id8"]
}
``````

Pull To Refresh:-

### How to set time to a date object in java

If you don't have access to java 8 and the API java.time, here is my simple function to copy the time of one date to another date using the old java.util.Calendar (inspire by Jigar Joshi) :

``````/**
* Copy only the time of one date to the date of another date.
*/
public static Date copyTimeToDate(Date date, Date time) {
Calendar t = Calendar.getInstance();
t.setTime(time);

Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, t.get(Calendar.HOUR_OF_DAY));
c.set(Calendar.MINUTE, t.get(Calendar.MINUTE));
c.set(Calendar.SECOND, t.get(Calendar.SECOND));
c.set(Calendar.MILLISECOND, t.get(Calendar.MILLISECOND));
return c.getTime();
}
``````

### JQuery create a form and add elements to it programmatically

Using Jquery

Rather than creating temp variables it can be written in a continuous flow pattern as follows:

``````\$('</form>', { action: url, method: 'POST' }).append(
\$('<input>', {type: 'hidden', id: 'id_field_1', name: 'name_field_1', value: val_field_1}),
\$('<input>', {type: 'hidden', id: 'id_field_2', name: 'name_field_2', value: val_field_2}),
).appendTo('body').submit();
``````

### How to set image to fit width of the page using jsPDF?

i faced same problem but i solve using this code

``````html2canvas(body,{
onrendered:function(canvas){
var pdf=new jsPDF("p", "mm", "a4");
var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();
pdf.save('test11.pdf');
}
})
``````

### How can I add reflection to a C++ application?

The two reflection-like solutions I know of from my C++ days are:

1) Use RTTI, which will provide a bootstrap for you to build your reflection-like behaviour, if you are able to get all your classes to derive from an 'object' base class. That class could provide some methods like GetMethod, GetBaseClass etc. As for how those methods work you will need to manually add some macros to decorate your types, which behind the scenes create metadata in the type to provide answers to GetMethods etc.

2) Another option, if you have access to the compiler objects is to use the DIA SDK. If I remember correctly this lets you open pdbs, which should contain metadata for your C++ types. It might be enough to do what you need. This page shows how you can get all base types of a class for example.

Both these solution are a bit ugly though! There is nothing like a bit of C++ to make you appreciate the luxuries of C#.

Good Luck.

### Empty an array in Java / processing

You can simply assign `null` to the reference. (This will work for any type of array, not just `ints`)

``````int[] arr = new int[]{1, 2, 3, 4};
arr = null;
``````

This will 'clear out' the array. You can also assign a new array to that reference if you like:

``````int[] arr = new int[]{1, 2, 3, 4};
arr = new int[]{6, 7, 8, 9};
``````

If you are worried about memory leaks, don't be. The garbage collector will clean up any references left by the array.

Another example:

``````float[] arr = ;// some array that you want to clear
arr = new float[arr.length];
``````

This will create a new `float[]` initialized to the default value for float.

### postgres default timezone

Maybe not related to the question, but I needed to use CST, set the system timezone to the desired tz (America/...) and then in postgresql conf set the value of the timezone to 'localtime' and it worked as a charm, current_time printing the right time (Postgresql 9.5 on Ubuntu 16)

### Powershell get ipv4 address into a variable

Here is what I ended up using

``````\$ipaddress = \$(ipconfig | where {\$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; \$Matches[1])
``````

which breaks down as

• execute ipconfig command - get all the network interface information
• use powershell's where filter with a regular expression
• regular expression finds the line with "IPv4" and a set of 4 blocks each with 1-3 digits separated by periods, i.e. a v4 IP address
• disregard the output by piping it to null
• finally get the first matched group as defined by the brackets in the regular expression.
• catch that output in \$ipaddress for later use.

I did not have much success with the above `setTimeout` methods in Firefox.

``````window.onload = function () {
if (location.hash) {
window.scrollTo(0, 0);
}
};
``````

It's still very glitchy, unfortunately.

### Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

``````<!-- Latest compiled and minified CSS -->

<!-- Optional theme -->

<!-- Latest compiled and minified JavaScript -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
``````

### How to parse JSON in Kotlin?

You can use this library https://github.com/cbeust/klaxon

Klaxon is a lightweight library to parse JSON in Kotlin.

### Formatting a float to 2 decimal places

The first thing you need to do is use the `decimal` type instead of `float` for the prices. Using `float` is absolutely unacceptable for that because it cannot accurately represent most decimal fractions.

Once you have done that, `Decimal.Round()` can be used to round to 2 places.

### Keep overflow div scrolled to bottom unless user scrolls up

In 2020, you can use css snap, but before Chrome 81 the layout change will not trigger re-snap, a pure css chat ui works on Chrome 81, also you can check Can I use CSS snap.

This demo will snap the last element if visible, scroll to bottom to see the effect.

_x000D_
_x000D_
``````.container {
overflow-y: scroll;
overscroll-behavior-y: contain;
scroll-snap-type: y proximity;
}

.container > div > div:last-child {
scroll-snap-align: end;
}

.container > div > div {
background: lightgray;
height: 3rem;
font-size: 1.5rem;
}
.container > div > div:nth-child(2n) {
background: gray;
}``````
_x000D_
``````<div class="container" style="height:6rem">
<div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</div>``````
_x000D_
_x000D_
_x000D_

EDIT

use `scroll-snap-type: y proximity;`, scroll up easier.

### Convert pandas.Series from dtype object to float, and errors to nans

#### Use `pd.to_numeric` with `errors='coerce'`

``````# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object
``````

``````pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64
``````

If you need the `NaN`s filled in, use `Series.fillna`.

``````pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64
``````

Note, `downcast='infer'` will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

``````pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32
``````

There are other options to choose from as well, read the docs for more.

#### Extension for `DataFrames`

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using `DataFrame.apply`.

``````# Setup.
np.random.seed(0)
df = pd.DataFrame({
'A' : np.random.choice(10, 5),
'C' : np.random.choice(10, 5),
'B' : ['1', '###', '...', 50, '234'],
'D' : ['23', '1', '...', '268', '\$\$']}
)[list('ABCD')]
df

A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   \$\$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object
``````

``````df2 = df.apply(pd.to_numeric, errors='coerce')
df2

A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object
``````

You can also do this with `DataFrame.transform`; although my tests indicate this is marginally slower:

``````df.transform(pd.to_numeric, errors='coerce')

A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN
``````

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying `pd.to_numeric` on the non-numeric columns only.

``````df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN
``````

Applying `pd.to_numeric` along the columns (i.e., `axis=0`, the default) should be slightly faster for long DataFrames.

### Unable to install pyodbc on Linux

Adding one more answer on this question. For Linux Debian Stretch release you would need to install the following dependencies:

``````apt-get update
apt-get install g++
apt-get install unixodbc-dev
pip install pyodbc
``````

### How can one display images side by side in a GitHub README.md?

The easiest way I can think of solving this is using the tables included in GitHub's flavored markdown.

To your specific example it would look something like this:

``````Solarized dark             |  Solarized Ocean
:-------------------------:|:-------------------------:
![](https://...Dark.png)  |  ![](https://...Ocean.png)
``````

This creates a table with Solarized Dark and Ocean as headers and then contains the images in the first row. Obviously you would replace the `...` with the real link. The `:`s are optional (They just center the content in the cells, which is kinda unnecessary in this case). Also you might want to downsize the images so they will display better side-by-side.

### ssh : Permission denied (publickey,gssapi-with-mic)

And I think this will clearify the cause of posted problem, actualy this is bug of pssh itself (contains inside "askpass-client.py"). It is pssh's lib file. And there is documented issue for -A case: https://code.google.com/archive/p/parallel-ssh/issues/80 There are two possible resolutions to use version of pssh containing this bug in case you forced to use passphrase for private key access:

2. Using your favorite pass keeper.

Thnks for attention, hope it helps!

### Angular/RxJs When should I unsubscribe from `Subscription`

You don't need to have bunch of subscriptions and unsubscribe manually. Use Subject and takeUntil combo to handle subscriptions like a boss:

``````import { Subject } from "rxjs"
import { takeUntil } from "rxjs/operators"

@Component({
moduleId: __moduleName,
selector: "my-view",
templateUrl: "../views/view-route.view.html"
})
export class ViewRouteComponent implements OnInit, OnDestroy {
componentDestroyed\$: Subject<boolean> = new Subject()

constructor(private titleService: TitleService) {}

ngOnInit() {
this.titleService.emitter1\$
.pipe(takeUntil(this.componentDestroyed\$))
.subscribe((data: any) => { /* ... do something 1 */ })

this.titleService.emitter2\$
.pipe(takeUntil(this.componentDestroyed\$))
.subscribe((data: any) => { /* ... do something 2 */ })

//...

this.titleService.emitterN\$
.pipe(takeUntil(this.componentDestroyed\$))
.subscribe((data: any) => { /* ... do something N */ })
}

ngOnDestroy() {
this.componentDestroyed\$.next(true)
this.componentDestroyed\$.complete()
}
}
``````

Alternative approach, which was proposed by @acumartini in comments, uses takeWhile instead of takeUntil. You may prefer it, but mind that this way your Observable execution will not be cancelled on ngDestroy of your component (e.g. when you make time consuming calculations or wait for data from server). Method, which is based on takeUntil, doesn't have this drawback and leads to immediate cancellation of request. Thanks to @AlexChe for detailed explanation in comments.

So here is the code:

``````@Component({
moduleId: __moduleName,
selector: "my-view",
templateUrl: "../views/view-route.view.html"
})
export class ViewRouteComponent implements OnInit, OnDestroy {
alive: boolean = true

constructor(private titleService: TitleService) {}

ngOnInit() {
this.titleService.emitter1\$
.pipe(takeWhile(() => this.alive))
.subscribe((data: any) => { /* ... do something 1 */ })

this.titleService.emitter2\$
.pipe(takeWhile(() => this.alive))
.subscribe((data: any) => { /* ... do something 2 */ })

// ...

this.titleService.emitterN\$
.pipe(takeWhile(() => this.alive))
.subscribe((data: any) => { /* ... do something N */ })
}

ngOnDestroy() {
this.alive = false
}
}
``````

### Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes

Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so

``````import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')
``````

to yield,

``````0    58
1     3
2     8
dtype: float64
``````

### Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

This can happen if you accidentally are not dragging the element that does have an id assigned (for example you are dragging the surrounding element). In that case the ID is empty and the function drag() is assigning an empty value which is then passed to drop() and fails there.

Try assigning the ids to all of your elements, including the tds, divs, or whatever is around your draggable element.

### Determine if map contains a value for a key?

As long as the map is not a multimap, one of the most elegant ways would be to use the count method

``````if (m.count(key))
// key exists
``````

The count would be 1 if the element is indeed present in the map.

### embedding image in html email

One additional hint to Pavel Perna's post which helped me very much (cannot comment with my reputation, that's why I post this as answer): In some versions of Microsoft Exchange, the inline contents disposition is removed (see this post by Microsoft). The image is simply not part in the mail the user sees in Outlook. As a workaround, use "Content-Disposition: attachement" instead. Outlook 2016 won't show images as attachement that are used in the mail message, although they use the "Content-Disposition: attachement".

### Testing for empty or nil-value string

``````variable = id if variable.to_s.empty?
``````

### How to speed up insertion performance in PostgreSQL

Use `COPY table TO ... WITH BINARY` which is according to the documentation is "somewhat faster than the text and CSV formats." Only do this if you have millions of rows to insert, and if you are comfortable with binary data.

### What is the difference between String and StringBuffer in Java?

Performance wise StringBuffer is much better than String ; because whenever you apply concatenation on String Object then new String object are created on each concatenation.

Principal Rule : String are immutable(Non Modifiable) and StringBuffer are mutable(Modifiable)

Here is the programmatic experiment where you get the performance difference

``````public class Test {

public static int LOOP_ITERATION= 100000;

public static void stringTest(){
long startTime = System.currentTimeMillis();
String string = "This";
for(int i=0;i<LOOP_ITERATION;i++){
string = string+"Yasir";
}

long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}

public static void stringBufferTest(){
long startTime = System.currentTimeMillis();
StringBuffer stringBuffer = new StringBuffer("This");
for(int i=0;i<LOOP_ITERATION;i++){
stringBuffer.append("Yasir");
}

long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}

public static void main(String []args){
stringTest()
stringBufferTest();
}
}
``````

Output of String are in my machine 14800

Output of StringBuffer are in my machine 14

### Simple way to compare 2 ArrayLists

Convert Lists to `Collection` and use `removeAll`

``````    Collection<String> listOne = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
Collection<String> listTwo = new ArrayList(Arrays.asList("a","b",  "d", "e", "f", "gg", "h"));

List<String> sourceList = new ArrayList<String>(listOne);
List<String> destinationList = new ArrayList<String>(listTwo);

sourceList.removeAll( listTwo );
destinationList.removeAll( listOne );

System.out.println( sourceList );
System.out.println( destinationList );
``````

Output:

``````[c, g]
[gg, h]
``````

[EDIT]

other way (more clear)

``````  Collection<String> list = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));

List<String> sourceList = new ArrayList<String>(list);
List<String> destinationList = new ArrayList<String>(list);

list.remove("b");

sourceList.removeAll( list );
list.removeAll( destinationList );

System.out.println( sourceList );
System.out.println( list );
``````

Output:

``````[b]
[boo]
``````

### Google Maps V3 - How to calculate the zoom level for a given bounds

For version 3 of the API, this is simple and working:

``````var latlngList = [];

latlngList.each(function(n) {
bounds.extend(n);
});

map.setCenter(bounds.getCenter()); //or use custom center
map.fitBounds(bounds);
``````

and some optional tricks:

``````//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom() - 1);

// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom() > 15){
map.setZoom(15);
}
``````

### Compare and contrast REST and SOAP web services?

SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

REST is over only HTTP

Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

### Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

Eclipse is launching your application with whatever JRE you defined in your launch configuration. Since you're running the 32-bit Eclipse, you're running/debugging against its 32-bit SWT libraries, and you'll need to run a 32-bit JRE.

To change this, first make sure you have a 32-bit JRE configured in the Installed JREs preference. Go to Window -> Preferences and navigate to Java -> Installed JREs:

You can click Add and navigate to your 32-bit JVM's `JAVA_HOME` to add it.

Then in your Run Configuration, find your Eclipse Application and make sure the Runtime JRE is set to the 32-bit JRE you just configured:

(Note the combobox that is poorly highlighted.)

Don't try replacing SWT jars, that will likely end poorly.

### Undo a merge by pull request?

Starting June 24th, 2014, you can try cancel a PR easily (See "Reverting a pull request") with:

Introducing the Revert Button

you can easily revert a pull request on GitHub by clicking Revert:

You'll be prompted to create a new pull request with the reverted changes:

It remains to be tested though if that revert uses `-m` or not (for reverting merges as well)

That is the expected behavior, it created a new branch and you can create a PR from this new branch to your `master`.
This way in the future you can un-revert the revert if need be, it is safest option and not directly changing your `master`.

Warning: Korayem points out in the comments that:

After a revert, let's say you did some further changes on Git branch and created a new PR from same source/destination branch.
You will find the PR showing only new changes, but nothing of what was there before reverting.

Korayem refers us to "Github: Changes ignored after revert (`git cherry-pick`, `git rebase`)" for more.

### How do I reverse a C++ vector?

There's a function `std::reverse` in the `algorithm` header for this purpose.

``````#include <vector>
#include <algorithm>

int main() {
std::vector<int> a;
std::reverse(a.begin(), a.end());
return 0;
}
``````

### How to remove underline from a link in HTML?

All the above-mentioned code did not work for me. When I dig into the problem I realize that it was not working because I'd placed the style after the href. When I placed the style before the href it was working as expected.

``````<a style="text-decoration:none" href="http://yoursite.com/">yoursite</a>
``````

### How to format a date using ng-model?

I prefer to have the server return the date without modification, and have javascript do the view massaging. My API returns "MM/DD/YYYY hh:mm:ss" from SQL Server.

Resource

``````angular.module('myApp').factory('myResource',
function(\$resource) {
return \$resource('api/myRestEndpoint/', null,
{
'GET': { method: 'GET' },
'QUERY': { method: 'GET', isArray: true },
'POST': { method: 'POST' },
'PUT': { method: 'PUT' },
'DELETE': { method: 'DELETE' }
});
}
);
``````

Controller

``````var getHttpJson = function () {
return myResource.GET().\$promise.then(
function (response) {

if (response.myDateExample) {
response.myDateExample = \$filter('date')(new Date(response.myDateExample), 'M/d/yyyy');
};

\$scope.myModel= response;
},
function (response) {
console.log(response.data);
}
);
};
``````

myDate Validation Directive

``````angular.module('myApp').directive('myDate',
function(\$window) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {

var moment = \$window.moment;

var acceptableFormats = ['M/D/YYYY', 'M-D-YYYY'];

function isDate(value) {

var m = moment(value, acceptableFormats, true);

var isValid = m.isValid();

//console.log(value);
//console.log(isValid);

return isValid;

};

ngModel.\$parsers.push(function(value) {

if (!value || value.length === 0) {
return value;
};

if (isDate(value)) {
ngModel.\$setValidity('myDate', true);
} else {
ngModel.\$setValidity('myDate', false);
}

return value;

});

}
}
}
);
``````

HTML

``````<div class="form-group">
<label for="myDateExample">My Date Example</label>
<input id="myDateExample"
name="myDateExample"
class="form-control"
required=""
my-date
maxlength="50"
ng-model="myModel.myDateExample"
type="text" />
<div ng-messages="myForm.myDateExample.\$error" ng-if="myForm.\$submitted || myForm.myDateExample.\$touched" class="errors">
<div ng-messages-include="template/validation/messages.html"></div>
</div>
</div>
``````

template/validation/messages.html

``````<div ng-message="required">Required Field</div>
<div ng-message="number">Must be a number</div>
<div ng-message="email">Must be a valid email address</div>
<div ng-message="minlength">The data entered is too short</div>
<div ng-message="maxlength">The data entered is too long</div>
<div ng-message="myDate">Must be a valid date</div>
``````

### Count the number of times a string appears within a string

Your regular expression should be `\btrue\b` to get around the 'miscontrue' issue Casper brings up. The full solution would look like this:

``````string searchText = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
string regexPattern = @"\btrue\b";
int numberOfTrues = Regex.Matches(searchText, regexPattern).Count;
``````

Make sure the System.Text.RegularExpressions namespace is included at the top of the file.

### Can you hide the controls of a YouTube embed without enabling autoplay?

use `autoplay=0`

autoplay takes 2 values.

``````Values: 0 or 1. Default is 0. Sets whether or not the initial video will autoplay when the player loads.
``````

the important part

``````autoplay=0&showinfo=0&controls=0
``````

Here is the demo for ur problem FIDDLE

### Hexadecimal string to byte array in C

The best way I know:

``````int hex2bin_by_zibri(char *source_str, char *dest_buffer)
{
char *line = source_str;
char *data = line;
int offset;
int data_len = 0;

while (sscanf(data, " %02x%n", &read_byte, &offset) == 1) {
data += offset;
}
return data_len;
}
``````

The function returns the number of converted bytes saved in dest_buffer. The input string can contain spaces and mixed case letters.

"01 02 03 04 ab Cd eF garbage AB"

translates to dest_buffer containing 01 02 03 04 ab cd ef

and also "01020304abCdeFgarbageAB"

translates as before.

Parsing stops at the first "error".

### excel formula to subtract number of days from a date

Assuming the original date is in cell A1:

``````=DATE(YEAR(A1), MONTH(A1), DAY(A1)-180)
``````

### Loop through each cell in a range of cells when given a Range object

``````Sub LoopRange()

Dim rCell As Range
Dim rRng As Range

Set rRng = Sheet1.Range("A1:A6")

For Each rCell In rRng.Cells
Next rCell

End Sub
``````

### Truncating long strings with CSS: feasible yet?

Update: `text-overflow: ellipsis` is now supported as of Firefox 7 (released September 27th 2011). Yay! My original answer follows as a historical record.

Justin Maxwell has cross browser CSS solution. It does come with the downside however of not allowing the text to be selected in Firefox. Check out his guest post on Matt Snider's blog for the full details on how this works.

Note this technique also prevents updating the content of the node in JavaScript using the `innerHTML` property in Firefox. See the end of this post for a workaround.

CSS

``````.ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
-moz-binding: url('assets/xml/ellipsis.xml#ellipsis');
}
``````

`ellipsis.xml` file contents

``````<?xml version="1.0"?>
<bindings
xmlns="http://www.mozilla.org/xbl"
xmlns:xbl="http://www.mozilla.org/xbl"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
<binding id="ellipsis">
<content>
<xul:window>
<xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
</xul:window>
</content>
</binding>
</bindings>
``````

Updating node content

To update the content of a node in a way that works in Firefox use the following:

``````var replaceEllipsis(node, content) {
node.innerHTML = content;
// use your favorite framework to detect the gecko browser
if (YAHOO.env.ua.gecko) {
var pnode = node.parentNode,
newNode = node.cloneNode(true);

pnode.replaceChild(newNode, node);
}
};
``````

### How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

If you want to downgrade php version, just simply edit yout .htaccess file. Like you want to downgrade any php version to 5.6, just add this into .htaccess file

``````<FilesMatch "\.(php4|php5|php7|php3|php2|php|phtml)\$">
etHandler application/x-lsphp56
</FilesMatch>
``````

### ORACLE and TRIGGERS (inserted, updated, deleted)

The NEW values (or NEW_BUFFER as you have renamed them) are only available when INSERTING and UPDATING. For DELETING you would need to use OLD (OLD_BUFFER). So your trigger would become:

``````CREATE or REPLACE TRIGGER test001
AFTER INSERT OR DELETE OR UPDATE ON tabletest001
REFERENCING OLD AS old_buffer NEW AS new_buffer
FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00')
``````

You may need to add logic inside the trigger to cater for code that updates field1 from 'HBP000' to something else.

### Opening PDF String in new window with javascript

You might want to explore using the data URI. It would look something like.

``````window.open("data:application/pdf," + escape(pdfString));
``````

I wasn't immediately able to get this to work, possible because formating of the binary string provided. I also usually use base64 encoded data when using the data URI. If you are able to pass the content from the backend encoded you can use..

``````window.open("data:application/pdf;base64, " + base64EncodedPDF);
``````

Hopefully this is the right direction for what you need. Also note this will not work at all in IE6/7 because they do not support Data URIs.

### How to add click event to a iframe with JQuery

None of the suggested answers worked for me. I solved a similar case the following way:

``````<a href="http://my-target-url.com" id="iframe-wrapper"></a>
<iframe id="iframe_id" src="http://something.com" allowtrancparency="yes" frameborder="o"></iframe>
``````

The css (of course exact positioning should change according to the app requirements):

``````#iframe-wrapper, iframe#iframe_id {
width: 162px;
border: none;
height: 21px;
position: absolute;
top: 3px;
left: 398px;
}
z-index: 1000;
}
``````

Of course now you can catch any event on the iframe-wrapper.

### Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

I realize this question is over a year old, but I just stumbled across it in dealing with a similar problem and thought I would share another potential solution in case it might help a future traveler (or myself, when I forget this later and find myself flopping around on StackOverflow between screams and throwings of the nearest object on my desk).

In my case I was able to get the effect I wanted by using a DataGridTemplateColumn instead of a DataGridComboBoxColumn, a la the following snippet. [caveat: I'm using .NET 4.0, and what I've been reading leads me to believe the DataGrid has done a lot of evolving, so YMMV if using earlier version]

``````<DataGridTemplateColumn Header="Identifier_TEMPLATED">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox IsEditable="False"
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ComponentIdentifier}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
``````

### Can I pass parameters by reference in Java?

I don't think you can. Your best option might be to encapsulate the thing you want to pass "by ref" onto another class instance, and pass the (outer) class's reference (by value). If you see what I mean...

i.e. your method changes the internal state of the object it is passed, which is then visible to the caller.

### Oracle SQL Where clause to find date records older than 30 days

Use:

``````SELECT *
FROM YOUR_TABLE
WHERE creation_date <= TRUNC(SYSDATE) - 30
``````

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the `creation_date` that is 30 days previous including the current time.

``````SELECT *
FROM YOUR_TABLE
``````

### Finding Variable Type in JavaScript

For builtin JS types you can use:

``````function getTypeName(val) {
return {}.toString.call(val).slice(8, -1);
}
``````

Here we use 'toString' method from 'Object' class which works different than the same method of another types.

Examples:

``````// Primitives
getTypeName(42);        // "Number"
getTypeName("hi");      // "String"
getTypeName(true);      // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null);      // "Null"
getTypeName(undefined); // "Undefined"

// Non-primitives
getTypeName({});            // "Object"
getTypeName([]);            // "Array"
getTypeName(new Date);      // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/);           // "RegExp"
getTypeName(new Error);     // "Error"
``````

If you need a class name you can use:

``````instance.constructor.name
``````

Examples:

``````({}).constructor.name       // "Object"
[].constructor.name         // "Array"
(new Date).constructor.name // "Date"

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"
``````

But this feature was added in ES2015.

### What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

i am not sure but, I think you can use `@ResponseEntity` and `@ResponseBody` and send 2 different one is Success and second is error message like :

``````@RequestMapping(value ="/book2", produces =MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
Book bookInfo2() {
Book book = new Book();
book.setBookName("Ramcharitmanas");
book.setWriter("TulasiDas");
return book;
}

@RequestMapping(value ="/book3", produces =MediaType.APPLICATION_JSON_VALUE )
public ResponseEntity<Book> bookInfo3() {
Book book = new Book();
book.setBookName("Ramayan");
book.setWriter("Valmiki");
return ResponseEntity.accepted().body(book);
}
``````

For more detail refer to this: http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity

### jQuery 'input' event

Using jQuery, the following are identical in effect:

``````\$('a').click(function(){ doSomething(); });
\$('a').on('click', function(){ doSomething(); });
``````

With the `input` event, however, only the second pattern seems to work in the browsers I've tested.

Thus, you'd expect this to work, but it DOES NOT (at least currently):

``````\$(':text').input(function(){ doSomething(); });
``````

Again, if you wanted to leverage event delegation (e.g. to set up the event on the `#container` before your `input.text` is added to the DOM), this should come to mind:

``````\$('#container').on('input', ':text', function(){ doSomething(); });
``````

Sadly, again, it DOES NOT work currently!

Only this pattern works:

``````\$(':text').on('input', function(){ doSomething(); });
``````

EDITED WITH MORE CURRENT INFORMATION

I can certainly confirm that this pattern:

``````\$('#container').on('input', ':text', function(){ doSomething(); });
``````

NOW WORKS also, in all 'standard' browsers.

### Special characters like @ and & in cURL POST data

How about using the entity codes...

`@ = %40`

`& = %26`

So, you would have:

`curl -d 'name=john&passwd=%4031%263*J' https://www.mysite.com`

### How to calculate moving average without keeping the count and data-total?

From a blog on running sample variance calculations, where the mean is also calculated using Welford's method:

### How to identify unused CSS definitions from multiple CSS files in a project

I have just found this site – http://unused-css.com/

Looks good but I would need to thoroughly check its outputted 'clean' css before uploading it to any of my sites.

Also as with all these tools I would need to check it didn't strip id's and classes with no style but are used as JavaScript selectors.

The below content is taken from http://unused-css.com/ so credit to them for recommending other solutions:

Latish Sehgal has written a windows application to find and remove unused CSS classes. I haven't tested it but from the description, you have to provide the path of your html files and one CSS file. The program will then list the unused CSS selectors. From the screenshot, it looks like there is no way to export this list or download a new clean CSS file. It also looks like the service is limited to one CSS file. If you have multiple files you want to clean, you have to clean them one by one.

Dust-Me Selectors is a Firefox extension (for v1.5 or later) that finds unused CSS selectors. It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered. This tool is supposed to be able to spider a whole website but I unfortunately could make it work. Also, I don't believe you can configure and download the CSS file with the styles removed.

Topstyle is a windows application including a bunch of tools to edit CSS. I haven't tested it much but it looks like it has the ability to removed unused CSS selectors. This software costs 80 USD.

Liquidcity CSS cleaner is a php script that uses regular expressions to check the styles of one page. It will tell you the classes that aren't available in the HTML code. I haven't tested this solution.

Deadweight is a CSS coverage tool. Given a set of stylesheets and a set of URLs, it determines which selectors are actually used and lists which can be "safely" deleted. This tool is a ruby module and will only work with rails website. The unused selectors have to be manually removed from the CSS file.

Helium CSS is a javascript tool for discovering unused CSS across many pages on a web site. You first have to install the javascript file to the page you want to test. Then, you have to call a helium function to start the cleaning.

UnusedCSS.com is web application with an easy to use interface. Type the url of a site and you will get a list of CSS selectors. For each selector, a number indicates how many times a selector is used. This service has a few limitations. The @import statement is not supported. You can't configure and download the new clean CSS file.

CSSESS is a bookmarklet that helps you find unused CSS selectors on any site. This tool is pretty easy to use but it won't let you configure and download clean CSS files. It will only list unused CSS files.

### How do I install a module globally using npm?

You might not have write permissions to install a node module in the global location such as `/usr/local/lib/node_modules`, in which case run npm install -g package as root.

### how do you insert null values into sql server

``````INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)
``````

### Unit testing void methods?

As always: test what the method is supposed to do!

Should it change global state (uuh, code smell!) somewhere?

Should it call into an interface?

Should it throw an exception when called with the wrong parameters?

Should it throw no exception when called with the right parameters?

Should it ...?

### Adding an .env file to React Project

If in case you are getting the values as `undefined`, then you should consider restarting the node server and recompile again.

### How to add SHA-1 to android application

Try pasting this code in CMD:

``````keytool -list -v -alias androiddebugkey -keystore  %USERPROFILE%\.android\debug.keystore
``````

### Compression/Decompression string with C#

For those who still getting The magic number in GZip header is not correct. Make sure you are passing in a GZip stream. ERROR and if your string was zipped using php you'll need to do something like:

``````       public static string decodeDecompress(string originalReceivedSrc) {

using (var mem = new MemoryStream()) {
//the trick is here
mem.Write(new byte[] { 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
mem.Write(bytes, 0, bytes.Length);

mem.Position = 0;

using (var gzip = new GZipStream(mem, CompressionMode.Decompress))
}
}
}
``````

### How to get URL parameters with Javascript?

``````function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|\$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
``````

So you can use:

``````myvar = getURLParameter('myvar');
``````

### Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I think I got this from not explicitly deleting some tables from the edmx before renaming and re-adding them. Instead, I just renamed the tables and then did an Update Model from Database, thinking it would see them gone, and delete them from model. I then did another Update Model from Database and added the renamed tables.

The site was working with the new tables, but I had the error. Eventually, I noticed the original tables were still in the model. I deleted them from the model (click them in edmx screen, delete key), and then the error went away.

### Unable to load DLL 'SQLite.Interop.dll'

I had this problem because Visual C++ 2010 redistributable no installed in my PC.if you have not already installed Visual c++ 2010 redistributable Download and install this(check x86 or 64 dll).

### Display the current date and time using HTML and Javascript with scrollable effects in hta application

``````<div id="clockbox" style="font:14pt Arial; color:#FF0000;text-align: center; border:1px solid red;background:cyan; height:50px;padding-top:12px;"></div>
``````

### MD5 hashing in Android

The androidsnippets.com code does not work reliably because 0's seem to be cut out of the resulting hash.

A better implementation is here.

``````public static String MD5_Hash(String s) {
MessageDigest m = null;

try {
m = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}

m.update(s.getBytes(),0,s.length());
String hash = new BigInteger(1, m.digest()).toString(16);
return hash;
}
``````

### How to make a Bootstrap accordion collapse when clicking the header div?

Actually my panel had this collapse state arrow icon and I tried other answers in this post , but icon position changed, so here is the solution with collapse state arrow icon.

`````` .panel-heading
{
cursor: pointer;
}

a.accordion-toggle
{
display: block;
}
``````

Credit's goes to this post answerer.

Hope helps.

### Making the main scrollbar always visible

I do this:

``````html {
margin-left: calc(100vw - 100%);
margin-right: 0;
}
``````

Then I don't have to look at the ugly greyed out scrollbar when it's not needed.

### 'tuple' object does not support item assignment

PIL pixels are tuples, and tuples are immutable. You need to construct a new tuple. So, instead of the for loop, do:

``````pixels = [(pixel[0] + 20, pixel[1], pixel[2]) for pixel in pixels]
image.putdata(pixels)
``````

Also, if the pixel is already too red, adding 20 will overflow the value. You probably want something like `min(pixel[0] + 20, 255)` or `int(255 * (pixel[0] / 255.) ** 0.9)` instead of `pixel[0] + 20`.

And, to be able to handle images in lots of different formats, do `image = image.convert("RGB")` after opening the image. The convert method will ensure that the pixels are always (r, g, b) tuples.

### What is the opposite of :hover (on mouse leave)?

You have misunderstood `:hover`; it says the mouse is over an item, rather than the mouse has just entered the item.

You could add animation to the selector without `:hover` to achieve the effect you want.

Transitions is a better option: http://jsfiddle.net/Cvx96/

### Command to get nth line of STDOUT

For the sake of completeness ;-)

shorter code

``````find / | awk NR==3
``````

shorter life

``````find / | awk 'NR==3 {print \$0; exit}'
``````

### How do I increase the scrollback buffer in a running screen session?

For posterity, this answer is incorrect as noted by Steven Lu. Leaving original text however.

To those arriving via web search (several years later)...

When using screen, your scrollback buffer is a combination of both the `screen` scrollback buffer as the two previous answers have noted, as well as your putty scrollback buffer.

Be sure that you are increasing BOTH the putty scrollback buffer as well as the screen scrollback buffer, else your putty window itself won't let you scroll back to see your `screen`'s scrollback history (overcome by scrolling within screen with `ctrl+a->ctrl+u`)

You can change your putty scrollback limit under the "Window" category in the settings. Exiting and reopening a putty session to your screen won't close your screen (assuming you just close the putty window and don't type `exit`), as the OP asked for.

Hope that helps identify why increasing the screen's scrollback buffer doesn't solve someone's problem.

### "Press Any Key to Continue" function in C

Use `getch()`:

``````printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
``````

Windows alternative should be _getch().

If you're using Windows, this should be the full example:

``````#include <conio.h>
#include <ctype.h>

int main( void )
{
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
_getch();
}
``````

P.S. as @Rörd noted, if you're on POSIX system, you need to make sure that curses library is setup right.

### Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

Your welcome page is set as That Servlet . So all css , images path should be given relative to that servlet DIR . which is a bad idea ! why do you need the servlet as a home page ? set .jsp as index page and redirect to any page from there ?

are you trying to populate any fields from db is that why you are using servlet ?

### webpack command not working

You can run `npx webpack`. The npx command, which ships with Node 8.2/npm 5.2.0 or higher, runs the webpack binary (./node_modules/.bin/webpack) of the webpack package. Source of info: https://webpack.js.org/guides/getting-started/

### Angular2 disable button

`````` <button [disabled]="this.model.IsConnected() == false"
[ngClass]="setStyles()"
class="action-button action-button-selected button-send"
(click)= "this.Send()">
SEND
</button>
``````

.ts code

``````setStyles()
{
let styles = {

'action-button-disabled': this.model.IsConnected() == false
};
return styles;
}
``````

### Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the * operator on a list.

For example:

``````import math
import numpy as np
alpha = 0.2
beta=1-alpha
C = (-math.log(1-beta))/alpha

coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C
``````

The error:

``````    coff *= C
TypeError: can't multiply sequence by non-int of type 'float'
``````

The solution - convert the list to numpy array:

``````coff = np.asarray(coff) * C
``````

### Set the maximum character length of a UITextField in Swift

thanks

``````extension UITextField {

/// Runtime key
private struct AssociatedKeys {
/// max lenght key
static var maxlength: UInt8 = 0
/// temp string key
static var tempString: UInt8 = 0
}

/// Limit the maximum input length of the textfiled
@IBInspectable var maxLength: Int {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.maxlength) as? Int ?? 0
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.maxlength, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}

/// temp string
private var tempString: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.tempString) as? String
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.tempString, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}

/// When the text changes, process the amount of text in the input box so that its length is within the controllable range.
@objc private func handleEditingChanged(textField: UITextField) {

/// Special Processing for Chinese Input Method
guard markedTextRange == nil else { return }

if textField.text?.count == maxLength {

/// SET lastQualifiedString where text length == max lenght
tempString = textField.text
} else if textField.text?.count ?? 0 < maxLength {

/// clear lastQualifiedString when text lengeht > maxlength
tempString = nil
}

/// keep current text range in arcgives
let archivesEditRange: UITextRange?

if textField.text?.count ?? 0 > maxLength {

/// if text length > maxlength,remove last range,to move to -1 postion.
let position = textField.position(from: safeTextPosition(selectedTextRange?.start), offset: -1) ?? textField.endOfDocument
archivesEditRange = textField.textRange(from: safeTextPosition(position), to: safeTextPosition(position))
} else {

/// just set current select text range
archivesEditRange = selectedTextRange
}

/// main handle string max length
textField.text = tempString ?? String((textField.text ?? "").prefix(maxLength))

/// last config edit text range
textField.selectedTextRange = archivesEditRange
}

/// get safe textPosition
private func safeTextPosition(_ optionlTextPosition: UITextPosition?) -> UITextPosition {

/* beginningOfDocument -> The end of the the text document. */
return optionlTextPosition ?? endOfDocument
}
}
``````

### Output first 100 characters in a string

Most of previous examples will raise an exception in case your string is not long enough.

Another approach is to use `'yourstring'.ljust(100)[:100].strip()`.

This will give you first 100 chars. You might get a shorter string in case your string last chars are spaces.

### How does the "position: sticky;" property work?

One of the most common mistakes when going about the `position` `sticky` is:

1. Browser not supporting it
2. Not including any top bottom right left properties. Bare in mind that the Browser won't know how to handle that properly if you don't give it enough information. It will be just be `statically` positioned without it.

I have written about that and more insides on this article. Just putting a reference so I don't repeat myself too much.

### Can't draw Histogram, 'x' must be numeric

Because of the thousand separator, the data will have been read as 'non-numeric'. So you need to convert it:

`````` we <- gsub(",", "", we)   # remove comma
we <- as.numeric(we)      # turn into numbers
``````

and now you can do

`````` hist(we)
``````

and other numeric operations.

### How to increase the vertical split window size in Vim

Another tip from my side:

In order to set the window's width to let's say exactly 80 columns, use

``````80 CTRL+W |
``````

In order to set it to maximum width, just omit the preceding number:

``````CTRL+W |
``````

### How can I run an external command asynchronously from Python?

This is covered by Python 3 Subprocess Examples under "Wait for command to terminate asynchronously":

``````import asyncio

proc = await asyncio.create_subprocess_exec(
'ls','-lha',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)

# do something else while ls is working

# if proc takes very long to complete, the CPUs are free to use cycles for
# other processes
stdout, stderr = await proc.communicate()
``````

The process will start running as soon as the `await asyncio.create_subprocess_exec(...)` has completed. If it hasn't finished by the time you call `await proc.communicate()`, it will wait there in order to give you your output status. If it has finished, `proc.communicate()` will return immediately.

The gist here is similar to Terrels answer but I think Terrels answer appears to overcomplicate things.

See `asyncio.create_subprocess_exec` for more information.

### How to set max and min value for Y axis

The above answers didn't work for me. Possibly the option names were changed since '11, but the following did the trick for me:

``````ChartJsProvider.setOptions
scaleBeginAtZero: true
``````

### Formatting "yesterday's" date in python

``````from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
``````

### Split string and get first value only

These are the two options I managed to build, not having the luxury of working with `var` type, nor with additional variables on the line:

``````string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);

string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);
``````

This is what it gets:

### Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

The solution for me was sooo dumb!!

I was using Python 3.8 in my environment. I made a new environment using Python 3.7, and the install worked fine.

source

Here is a list of the available shortcuts in Notepad++.

In case your desired functionality is not available, you are able to define own macros and assign them to a custom shortcut (i am not used to use macros).

UPDATE: I will post the shortcuts here in case the link gets invalid:

``````Shortcut    Command

Ctrl-C  Copy
Ctrl-X  Cut
Ctrl-V  Paste
Ctrl-Z  Undo
Ctrl-Y  Redo
Ctrl-A  Select All
Ctrl-F  Launch Find Dialog
Ctrl-H  Launch Find / Replace Dialog
Ctrl-D  Duplicate Current Line
Ctrl-L  Delete Current Line
Ctrl-T  Switch the current line position with the previous line position
F3  Find Next
Shft-F3 Find Previous
Ctrl-Shft-F Find in Files
Ctrl-F3 Find (volatil) Next
Ctrl-Shft-F3    Find (volatil) Previous
Ctrl-Shft-I Incremental Search
Ctrl-S  Save File
Ctrl-Alt-S  Save As
Ctrl-Shft-S Save All
Ctrl-O  Open File
Ctrl-N  New File
Ctrl-F2 Toggle Bookmark
F2  Go To Next Bookmark
Shft-F2 Go To Previous Bookmark
Ctrl-G  Launch GoToLine Dialog
Ctrl-W  Close Current Document
Alt-Shft-Arrow keys or Alt + Left mouse click   Column Mode Select
F5  Launch Run Dialog
Ctrl-Space  Launch CallTip ListBox
Alt-Space   Launch Word Completion ListBox
Tab (selection of several lines)    Insert Tabulation or Space (Indent)
Shft-Tab (selection of several lines)   Remove Tabulation or Space (outdent)
Ctrl-(Keypad-/Keypad+) or Ctrl + mouse wheel butto  Zoom in (+ or up) and Zoom out (- or down)
Ctrl-Keypad/    Restore the original size from zoom
F11 Toggle Full Screen Mode
Ctrl-Tab    Next Document
Ctrl-Shft-Tab   Previous Document
Ctrl-Shft-Up    Move Current Line Up
Ctrl-Shft-Down  Move Current Line Down
Ctrl-Alt-F  Collapse the Current Level
Ctrl-Alt-Shft-F Uncollapse the Current Level
Alt-0   Fold All
Alt-(1~8)   Collapse the Level (1~8)
Alt-Shft-0  Unfold All
Alt-Shft-(1~8)  Uncollapse the Level (1~8)
Ctrl-BackSpace  Delete to start of word
Ctrl-Delete Delete to end of word
Ctrl-Shft-BackSpace Delete to start of line
Ctrl-Shft-Delete    Delete to end of line
Ctrl-U  Convert to lower case
Ctrl-Shft-U Convert to UPPER CASE
Ctrl-B  Go to matching brace
Ctrl-Shft-R Start to record /Stop recording the macro
Ctrl-Shft-P Play recorded macro
Ctrl-Q  Block comment/uncomment
Ctrl-Shft-Q Stream comment
Ctrl-Shft-T Copy current line to clipboard
Ctrl-P  Print
Alt-F4  Exit
Ctrl-I  Split Lines
Ctrl-J  Join Lines
Ctrl-Alt-R  Text Direction RTL
Ctrl-Alt-L  Text Direction LT
``````

### Why can't I declare static methods in an interface?

There's a very nice and concise answer to your question here. (It struck me as such a nicely straightforward way of explaining it that I want to link it from here.)

### Undefined variable: \$_SESSION

Turned out there was some extra code in the AppModel that was messing things up:

in `beforeFind` and `afterFind`:

``````App::Import("Session");
\$session = new CakeSession();
``````

I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.

### Difference between git pull and git pull --rebase

For this is important to understand the difference between Merge and Rebase.

Rebases are how changes should pass from the top of hierarchy downwards and merges are how they flow back upwards.

For details refer - http://www.derekgourlay.com/archives/428

### Error: vector does not name a type

You forgot to add `std::` namespace prefix to `vector` class name.

### What is the difference between UTF-8 and Unicode?

Unicode is just a standard that defines a character set (UCS) and encodings (UTF) to encode this character set. But in general, Unicode is refered to the character set and not the standard.

### installing requests module in python 2.7 windows

There are four options here:

1. Get `virtualenv` set up. Each virtual environment you create will automatically have `pip`.

2. Get `pip` set up globally.

3. Learn how to install Python packages manually—in most cases it's as simple as download, unzip, `python setup.py install`, but not always.

### How to disable back swipe gesture in UINavigationController on iOS 7

This works in `viewDidLoad:` for iOS 8:

``````  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
});
``````

Lots of the problems could be solved with help of the good ol' `dispatch_after`.

#### Update

For iOS 8.1 delay time should be 0.5 seconds

On iOS 9.3 no delay needed anymore, it works just by placing this in your `viewDidLoad`:
(TBD if works on iOS 9.0-9.3)

``````navigationController?.interactivePopGestureRecognizer?.enabled = false
``````

### Correct MySQL configuration for Ruby on Rails Database.yml file

If you can have an empty config/database.yml file then define ENV['DATABASE_URL'] variable, then It will work

``````\$ cat config/database.yml

\$ echo \$DATABASE_URL
mysql://root:[email protected]:3306/my_db_name
``````

for Heroku: heroku config:set `DATABASE_URL='mysql://root:[email protected]/my_db_name'`

### How do you check "if not null" with Eloquent?

Eloquent has a method for that (Laravel 4.*/5.*);

``````Model::whereNotNull('sent_at')
``````

Laravel 3:

``````Model::where_not_null('sent_at')
``````

### \$(form).ajaxSubmit is not a function

Drupal 8

Drupal 8 does not include JS-libraries to pages automaticly. So most probably if you meet this error you need to attach 'core/jquery.form' library to your page (or form). Add something like this to your render array:

``````\$form['#attached']['library'][] = 'core/jquery.form';
``````

### How do I return an int from EditText? (Android)

For now, use an `EditText`. Use `android:inputType="number"` to force it to be numeric. Convert the resulting string into an integer (e.g., `Integer.parseInt(myEditText.getText().toString())`).

In the future, you might consider a `NumberPicker` widget, once that becomes available (slated to be in Honeycomb).

### How to generate random number in Bash?

You can also use `shuf` (available in coreutils).

``````shuf -i 1-100000 -n 1
``````

### How do I write JSON data to a file?

The accepted answer is fine. However, I ran into "is not json serializable" error using that.

Here's how I fixed it with `open("file-name.json", 'w')` as output:

`output.write(str(response))`

Although it is not a good fix as the json file it creates will not have double quotes, however it is great if you are looking for quick and dirty.

### Edit and Continue: "Changes are not allowed when..."

I did all the changes mentioned in every other answer and none worked. What did I learn? Enable and Continue exists in both the Tools > Options > Debugging menu and also in the Project settings. After I checked both, Enable and Continue worked for me.

### How to return multiple rows from the stored procedure? (Oracle PL/SQL)

Here is how to build a function that returns a result set that can be queried as if it were a table:

``````SQL> create type emp_obj is object (empno number, ename varchar2(10));
2  /

Type created.

SQL> create type emp_tab is table of emp_obj;
2  /

Type created.

SQL> create or replace function all_emps return emp_tab
2  is
3     l_emp_tab emp_tab := emp_tab();
4     n integer := 0;
5  begin
6     for r in (select empno, ename from emp)
7     loop
8        l_emp_tab.extend;
9        n := n + 1;
10       l_emp_tab(n) := emp_obj(r.empno, r.ename);
11     end loop;
12     return l_emp_tab;
13  end;
14  /

Function created.

SQL> select * from table (all_emps);

EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7902 FORD
7934 MILLER
``````

### CSS border less than 1px

It's impossible to draw a line on screen that's thinner than one pixel. Try using a more subtle color for the border instead.

### jQuery select element in parent window

why not both to be sure?

``````if(opener.document){
\$("#testdiv",opener.document).doStuff();
}else{
\$("#testdiv",window.opener).doStuff();
}
``````

### Serializing an object to JSON

Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):

``````function winHasJSON(){
json_data = JSON.stringify(obj);
// ... (do stuff with json_data)
}
if(typeof JSON === 'object' && typeof JSON.stringify === 'function'){
winHasJSON();
} else {
\$.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}
``````

### How to run code after some delay in Flutter?

Trigger actions after countdown

``````Timer(Duration(seconds: 3), () {
print("Yeah, this line is printed after 3 seconds");
});
``````

Repeat actions

``````Timer.periodic(Duration(seconds: 5), (timer) {
print(DateTime.now());
});
``````

Trigger timer immediately

``````Timer(Duration(seconds: 0), () {
print("Yeah, this line is printed immediately");
});
``````

### oracle SQL how to remove time from date

We can use TRUNC function in Oracle DB. Here is an example.

``````SELECT TRUNC(TO_DATE('01 Jan 2018 08:00:00','DD-MON-YYYY HH24:MI:SS')) FROM DUAL
``````

Output: 1/1/2018

### How to run Node.js as a background process and never die?

another solution disown the job

``````\$ nohup node server.js &
[1] 1711
\$ disown -h %1
``````

### Using jquery to get all checked checkboxes with a certain class name

`\$('.theClass:checkbox:checked')` will give you all the checked checkboxes with the class `theClass`.

### Arrays vs Vectors: Introductory Similarities and Differences

Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:

``````int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;
``````

for vectors, you just declare it and add elements

``````vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...
``````

at times you wont know the number of elements needed so a vector would be ideal for such a situation.

### Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

You need just to follow those steps:

1. Right Click on your project: Run (As) -> Maven clean
2. Right Click on your project: Run (As) -> Maven install

After which, if the build fails when you do Maven Install, it means there is no web.xml file under WEB-INF or some problem associated with it. it really works

### What is the difference between git pull and git fetch + git rebase?

#### TLDR:

`git pull` is like running `git fetch` then `git merge`
`git pull --rebase` is like `git fetch` then `git rebase`

`git pull` is like a `git fetch` + `git merge`.

"In its default mode, git pull is shorthand for `git fetch` followed by `git merge` FETCH_HEAD" More precisely, `git pull` runs `git fetch` with the given parameters and then calls `git merge` to merge the retrieved branch heads into the current branch"

'But what is the difference between `git pull` VS `git fetch` + `git rebase`'

Again, from same source:
`git pull --rebase`

"With --rebase, it runs git rebase instead of git merge."

#### Now, if you wanted to ask

'the difference between `merge` and `rebase`'

https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)

### How to implement the factory method pattern in C++ correctly

I mostly agree with the accepted answer, but there is a C++11 option that has not been covered in existing answers:

• Return factory method results by value, and
• Provide a cheap move constructor.

Example:

``````struct sandwich {
// Factory methods.
static sandwich ham();
static sandwich spam();
// Move constructor.
sandwich(sandwich &&);
// etc.
};
``````

Then you can construct objects on the stack:

``````sandwich mine{sandwich::ham()};
``````

As subobjects of other things:

``````auto lunch = std::make_pair(sandwich::spam(), apple{});
``````

Or dynamically allocated:

``````auto ptr = std::make_shared<sandwich>(sandwich::ham());
``````

When might I use this?

If, on a public constructor, it is not possible to give meaningful initialisers for all class members without some preliminary calculation, then I might convert that constructor to a static method. The static method performs the preliminary calculations, then returns a value result via a private constructor which just does a member-wise initialisation.

I say 'might' because it depends on which approach gives the clearest code without being unnecessarily inefficient.

### javascript: get a function's variable's value within another function

the OOP way to do this in ES5 is to make that variable into a property using the this keyword.

``````function first(){
this.nameContent=document.getElementById('full_name').value;
}

function second() {
y=new first();
}
``````

### Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that `flex: 1` sets `flex-basis: 0`. Instead, you need

``````.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
``````

_x000D_
_x000D_
``````.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}``````
_x000D_
``````<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table>    _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table>    _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table>    _x000D_
</div>_x000D_
</div>``````
_x000D_
_x000D_
_x000D_

### What's the difference between SCSS and Sass?

I'm one of the developers who helped create Sass.

The difference is UI. Underneath the textual exterior they are identical. This is why sass and scss files can import each other. Actually, Sass has four syntax parsers: scss, sass, CSS, and less. All of these convert a different syntax into an Abstract Syntax Tree which is further processed into CSS output or even onto one of the other formats via the sass-convert tool.

Use the syntax you like the best, both are fully supported and you can change between them later if you change your mind.

### Count number of occurrences for each unique value

Yes, you can use `GROUP BY`:

``````SELECT time,
activities,
COUNT(*)
FROM table
GROUP BY time, activities;
``````

### How to run single test method with phpunit?

The following command runs the test on a single method:

``````phpunit --filter testSaveAndDrop EscalationGroupTest escalation/EscalationGroupTest.php

phpunit --filter methodName ClassName path/to/file.php
``````

For newer versions of phpunit, it is just:

``````phpunit --filter methodName path/to/file.php
``````

### Encrypt and Decrypt in Java

Here is a sample I made a couple of months ago The class encrypt and decrypt data

``````import java.security.*;
import java.security.spec.*;

import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class TestEncryptDecrypt {

private final String ALGO = "DES";
private final String MODE = "ECB";
private static int mode = 0;

public static void main(String args[]) {
TestEncryptDecrypt me = new TestEncryptDecrypt();
if(args.length == 0) mode = 2;
else mode = Integer.parseInt(args[0]);
switch (mode) {
case 0:
me.encrypt();
break;
case 1:
me.decrypt();
break;
default:
me.encrypt();
me.decrypt();
}
}

public void encrypt() {
try {
System.out.println("Start encryption ...");

/* Get Input Data */
String input = getInputData();
System.out.println("Input data : "+input);

/* Create Secret Key */
KeyGenerator keyGen = KeyGenerator.getInstance(ALGO);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.init(56,random);
Key sharedKey = keyGen.generateKey();

/* Create the Cipher and init it with the secret key */
//System.out.println("\n" + c.getProvider().getInfo());
c.init(Cipher.ENCRYPT_MODE,sharedKey);
byte[] ciphertext = c.doFinal(input.getBytes());
System.out.println("Input Encrypted : "+new String(ciphertext,"UTF8"));

/* Save key to a file */
save(sharedKey.getEncoded(),"shared.key");

/* Save encrypted data to a file */
save(ciphertext,"encrypted.txt");
} catch (Exception e) {
e.printStackTrace();
}
}

public void decrypt() {
try {
System.out.println("Start decryption ...");

/* Get encoded shared key from file*/
SecretKeyFactory kf = SecretKeyFactory.getInstance(ALGO);
KeySpec ks = new DESKeySpec(encoded);
SecretKey ky = kf.generateSecret(ks);

/* Get encoded data */
System.out.println("Encoded data = " + new String(ciphertext,"UTF8"));

/* Create a Cipher object and initialize it with the secret key */
c.init(Cipher.DECRYPT_MODE,ky);

/* Update and decrypt */
byte[] plainText = c.doFinal(ciphertext);
System.out.println("Plain Text : "+new String(plainText,"UTF8"));
} catch (Exception e) {
e.printStackTrace();
}
}

private String getInputData() {
String id = "owner.id=...";
String name = "owner.name=...";
String contact = "owner.contact=...";
String tel = "owner.tel=...";
final String rc = System.getProperty("line.separator");
StringBuffer buf = new StringBuffer();
buf.append(id);
buf.append(rc);
buf.append(name);
buf.append(rc);
buf.append(contact);
buf.append(rc);
buf.append(tel);
return buf.toString();
}

private void save(byte[] buf, String file) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
fos.write(buf);
fos.close();
}

private byte[] load(String file) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream(file);
byte[] buf = new byte[fis.available()];
fis.close();
return buf;
}
}
``````

### how to remove the first two columns in a file using shell (awk, sed, whatever)

You can do it with `cut`:

``````cut -d " " -f 3- input_filename > output_filename
``````

Explanation:

• `cut`: invoke the cut command
• `-d " "`: use a single space as the delimiter (`cut` uses TAB by default)
• `-f`: specify fields to keep
• `3-`: all the fields starting with field 3
• `input_filename`: use this file as the input
• `> output_filename`: write the output to this file.

Alternatively, you can do it with `awk`:

``````awk '{\$1=""; \$2=""; sub("  ", " "); print}' input_filename > output_filename
``````

Explanation:

• `awk`: invoke the awk command
• `\$1=""; \$2="";`: set field 1 and 2 to the empty string
• `sub(...);`: clean up the output fields because fields 1 & 2 will still be delimited by " "
• `print`: print the modified line
• `input_filename > output_filename`: same as above.

### List of zeros in python

``````\$python 2.7.8

from timeit import timeit
import numpy

timeit("list(0 for i in xrange(0, 100000))", number=1000)
> 8.173301935195923

timeit("[0 for i in xrange(0, 100000)]", number=1000)
> 4.881675958633423

timeit("[0] * 100000", number=1000)
> 0.6624710559844971

timeit('list(itertools.repeat(0, 100000))', 'import itertools', number=1000)
> 1.0820629596710205
``````

You should use `[0] * n` to generate a list with `n` zeros.

See why [] is faster than list()

There is a gotcha though, both `itertools.repeat` and `[0] * n` will create lists whose elements refer to same `id`. This is not a problem with immutable objects like integers or strings but if you try to create list of mutable objects like a list of lists (`[[]] * n`) then all the elements will refer to the same object.

``````a = [[]] * 10
a[0].append(1)
a
> [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
``````

`[0] * n` will create the list immediately while `repeat` can be used to create the list lazily when it is first accessed.

If you're dealing with really large amount of data and your problem doesn't need variable length of list or multiple data types within the list it is better to use `numpy` arrays.

``````timeit('numpy.zeros(100000, numpy.int)', 'import numpy', number=1000)
> 0.057849884033203125
``````

`numpy` arrays will also consume less memory.

### Different font size of strings in the same TextView

The best way to do that is Html without substring your text and fully dynamique For example :

``````  public static String getTextSize(String text,int size) {
return "<span style=\"size:"+size+"\" >"+text+"</span>";

}
``````

and you can use color attribut etc... if the other hand :

``````size.setText(Html.fromHtml(getTextSize(ls.numProducts,100) + " " + mContext.getString(R.string.products));
``````

### Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

In our case, we had dropped support for SSL3, TLS1.0, and TLS1.1 for PCI-DSS compliance on our origin servers. However, you have to manually add support for TLS 1.1+ on your CloudFront origin server config. The AWS console displays the client-to-CF SSL settings, but does not easily show you CF-to-origin settings until you drill down. To fix, in the AWS console under CloudFront:

1. Click DISTRIBUTIONS.
3. Click ORIGINS tab.
5. Click EDIT.
6. Select all protocols that your origin supports under "Origin SSL Protocols"

### Is it possible to have empty RequestParam values use the defaultValue?

You can also do something like this -

`````` @RequestParam(value= "i", defaultValue = "20") Optional<Integer> i
``````

### How to tell if string starts with a number with Python?

Use Regular Expressions, if you are going to somehow extend method's functionality.

### No grammar constraints (DTD or XML schema) detected for the document

This worked for me in Eclipse 3.7.1: Go to the Preferences window, then XML -> XML Files -> Validation. Then in the Validating files section of the preferences panel on the right, choose Ignore in the drop down box for the "No grammar specified" preference. You may need to close the file and then reopen it to make the warning go away.

(I know this question is old but it was the first one I found when searching on the warning, so I'm posting the answer here for other searchers.)

### How may I align text to the left and text to the right in the same line?

``````<h1> left <span> right </span></h1>
``````

css:

``````h1{text-align:left; width:400px; text-decoration:underline;}
span{float:right; text-decoration:underline;}
``````

### .htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

``````Allow From All
``````

This is because `Order Deny,Allow` makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

``````#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
``````

The equivalent Apache 2.4 configuration should look like:

``````<Files ~ "^\.ht">
Require all denied
</Files>
``````

### Create a temporary table in a SELECT statement without a separate CREATE TABLE

``````CREATE TEMPORARY TABLE IF NOT EXISTS
temp_table ( INDEX(col_2) )
ENGINE=MyISAM
AS (
SELECT col_1, coll_2, coll_3
FROM mytable
)
``````

It also works with `PRIMARY KEY`

### Changing datagridview cell color dynamically

Considere use DataBindingComplete event for update the style. The next code change the style of the cell:

``````    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
}
``````

### Deep copy, shallow copy, clone

The terms "shallow copy" and "deep copy" are a bit vague; I would suggest using the terms "memberwise clone" and what I would call a "semantic clone". A "memberwise clone" of an object is a new object, of the same run-time type as the original, for every field, the system effectively performs "newObject.field = oldObject.field". The base Object.Clone() performs a memberwise clone; memberwise cloning is generally the right starting point for cloning an object, but in most cases some "fixup work" will be required following a memberwise clone. In many cases attempting to use an object produced via memberwise clone without first performing the necessary fixup will cause bad things to happen, including the corruption of the object that was cloned and possibly other objects as well. Some people use the term "shallow cloning" to refer to memberwise cloning, but that's not the only use of the term.

A "semantic clone" is an object which is contains the same data as the original, from the point of view of the type. For examine, consider a BigList which contains an Array> and a count. A semantic-level clone of such an object would perform a memberwise clone, then replace the Array> with a new array, create new nested arrays, and copy all of the T's from the original arrays to the new ones. It would not attempt any sort of deep-cloning of the T's themselves. Ironically, some people refer to the of cloning "shallow cloning", while others call it "deep cloning". Not exactly useful terminology.

While there are cases where truly deep cloning (recursively copying all mutable types) is useful, it should only be performed by types whose constituents are designed for such an architecture. In many cases, truly deep cloning is excessive, and it may interfere with situations where what's needed is in fact an object whose visible contents refer to the same objects as another (i.e. a semantic-level copy). In cases where the visible contents of an object are recursively derived from other objects, a semantic-level clone would imply a recursive deep clone, but in cases where the visible contents are just some generic type, code shouldn't blindly deep-clone everything that looks like it might possibly be deep-clone-able.

### SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

``````=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)
``````

Same way for tolerance

``````=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")
``````

### Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

just copy " _CRT_SECURE_NO_WARNINGS " paste it on projects->properties->c/c++->preprocessor->preprocessor definitions click ok.it will work

### Convert a CERT/PEM certificate to a PFX certificate

If you have a self-signed certificate generated by `makecert.exe` on a Windows machine, you will get two files: `cert.pvk` and `cert.cer`. These can be converted to a pfx using `pvk2pfx`

`pvk2pfx` is found in the same location as `makecert` (e.g. `C:\Program Files (x86)\Windows Kits\10\bin\x86` or similar)

``````pvk2pfx -pvk cert.pvk -spc cert.cer -pfx cert.pfx
``````

### How can I regenerate ios folder in React Native project?

Remove the ios folder first

`````` react-native eject
cd ios/
pod init
pod install
cd ..
cd ios
open *.xcworkspace/
``````

### How to get HttpClient to pass credentials along with the request?

I was also having this same problem. I developed a synchronous solution thanks to the research done by @tpeczek in the following SO article: Unable to authenticate to ASP.NET Web Api service with HttpClient

My solution uses a `WebClient`, which as you correctly noted passes the credentials without issue. The reason `HttpClient` doesn't work is because of Windows security disabling the ability to create new threads under an impersonated account (see SO article above.) `HttpClient` creates new threads via the Task Factory thus causing the error. `WebClient` on the other hand, runs synchronously on the same thread thereby bypassing the rule and forwarding its credentials.

Although the code works, the downside is that it will not work async.

``````var wi = (System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity;

var wic = wi.Impersonate();
try
{
var data = JsonConvert.SerializeObject(new
{
Property1 = 1,
Property2 = "blah"
});

using (var client = new WebClient { UseDefaultCredentials = true })
{
}
}
catch (Exception exc)
{
// handle exception
}
finally
{
wic.Undo();
}
``````

Note: Requires NuGet package: Newtonsoft.Json, which is the same JSON serializer WebAPI uses.

### How to use ng-repeat for dictionaries in AngularJs?

In Angular 7, the following simple example would work (assuming dictionary is in a variable called `d`):

my.component.ts:

``````keys: string[] = [];  // declaration of class member 'keys'
// component code ...

this.keys = Object.keys(d);
``````

my.component.html: (will display list of key:value pairs)

``````<ul *ngFor="let key of keys">
{{key}}: {{d[key]}}
</ul>
``````

### How to get the hours difference between two date objects?

The simplest way would be to directly subtract the date objects from one another.

For example:

``````var hours = Math.abs(date1 - date2) / 36e5;
``````

The subtraction returns the difference between the two dates in milliseconds. `36e5` is the scientific notation for `60*60*1000`, dividing by which converts the milliseconds difference into hours.

### Formatting a Date String in React Native

The beauty of the React Native is that it supports lots of JS libraries like Moment.js. Using moment.js would be a better/easier way to handle date/time instead coding from scratch

just run this in the terminal (`yarn add moment` also works if using React's built-in package manager):

``````npm install moment --save
``````

And in your React Native js page:

``````import Moment from 'moment';

render(){
Moment.locale('en');
var dt = '2016-05-02T00:00:00';
return(<View> {Moment(dt).format('d MMM')} </View>) //basically you can do all sorts of the formatting and others
}
``````

You may check the moment.js official docs here https://momentjs.com/docs/

### Difference between a virtual function and a pure virtual function

You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.

### Error sending json in POST to web API service

I had all my settings covered in the accepted answer. The problem I had was that I was trying to update the Entity Framework entity type "Task" like:

``````public IHttpActionResult Post(Task task)
``````

What worked for me was to create my own entity "DTOTask" like:

``````public IHttpActionResult Post(DTOTask task)
``````

### <button> vs. <input type="button" />. Which to use?

``````<button>
``````
• by default behaves like if it had a "type="submit" attribute
• can be used without a form as well as in forms.
• text or html content allowed
• css pseudo elements allowed (like :before)
• tag name is usually unique to a single form

vs.

``````<input type='button'>
``````
• type should be set to 'submit' to behave as a submitting element
• can only be used in forms.
• only text content allowed
• no css pseudo elements
• same tag name as most of the forms elements (inputs)

--
in modern browsers, both elements are easily styleable with css but in most cases, `button` element is preferred as you can style more with inner html and pseudo elements

### Defining a HTML template to append using JQuery

Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.

While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (`<% for`), conditionals (`<% if`) and transforms (`<%= myString | uppercase %>`) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).

# Templates Inside HTML

One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing `<script>` `type`, e.g. `<script type="text/template">`. For your case:

``````<script type="text/template" data-template="listitem">
<a href="\${url}" class="list-group-item">
<table>
<tr>
<td><img src="\${img}"></td>
<td><p class="list-group-item-text">\${title}</p></td>
</tr>
</table>
</a>
</script>
``````

On document load, read your template and tokenize it using a simple `String#split`

``````var itemTpl = \$('script[data-template="listitem"]').text().split(/\\$\{(.+?)\}/g);
``````

Notice that with our token, you get it in the alternating `[text, property, text, property]` format. This lets us nicely map it using an `Array#map`, with a mapping function:

``````function render(props) {
return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}
``````

Where `props` could look like `{ url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }`.

Putting it all together assuming you've parsed and loaded your `itemTpl` as above, and you have an `items` array in-scope:

``````\$('.search').keyup(function () {
\$('.list-items').append(items.map(function (item) {
return itemTpl.map(render(item)).join('');
}));
});
``````

This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with `document.querySelector` and `.innerHTML`.

jsfiddle

# Templates inside JS

A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.

In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the `\$.fn.html` method above.

``````const Item = ({ url, img, title }) => `
<a href="\${url}" class="list-group-item">
<div class="image">
<img src="\${img}" />
</div>
<p class="list-group-item-text">\${title}</p>
</a>
`;
``````

Then you could easily render it, even mapped from an array, like so:

``````\$('.list-items').html([
{ url: '/foo', img: 'foo.png', title: 'Foo item' },
{ url: '/bar', img: 'bar.png', title: 'Bar item' },
].map(Item).join(''));
``````

Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.

The order of declaring:

• Driver
• Connection string

If we declaring in order

• Connection string
• Driver

the application will fail

### Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

``````pl.xlabel("...", labelpad=20)
``````

or set it after:

``````ax.xaxis.labelpad = 20
``````

### Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

VBA subs are no macros. A VBA sub can be a macro, but it is not a must.

The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.

The more elegant way is, to design and write your own VBA code without using the macro features!

VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.

If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".

In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.

It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.

In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.

### Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

You should use "merge a range of revision".

To merge changes from the trunk to a branch, inside the branch working copy choose "merge range of revisions" and enter the trunk URL and the start and end revisions to merge.

The same in the opposite way to merge a branch in the trunk.

About the --reintegrate flag, check the manual here: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-merge.html#tsvn-dug-merge-reintegrate

### How do I use ROW_NUMBER()?

If you need to return the table's total row count, you can use an alternative way to the `SELECT COUNT(*)` statement.

Because `SELECT COUNT(*)` makes a full table scan to return the row count, it can take very long time for a large table. You can use the `sysindexes` system table instead in this case. There is a `ROWS` column that contains the total row count for each table in your database. You can use the following select statement:

``````SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2
``````

This will drastically reduce the time your query takes.

### Getting RAW Soap Data from a Web Reference Client running in ASP.net

Not sure why all the fuss with web.config or a serializer class. The below code worked for me:

``````XmlSerializer xmlSerializer = new XmlSerializer(myEnvelope.GetType());

using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, myEnvelope);
return textWriter.ToString();
}
``````

### Open Sublime Text from Terminal in macOS

Try this.

``````ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
``````

I was trying to do the same thing and this is what worked for me (ES6/ES2015):

``````import myData from './data.json';
``````

### Error: stray '\240' in program

It appears you have illegal characters in your source. I cannot figure out what character `\240` should be but apparently it is around the start of line 10

In the code you posted, the issue does not exist: Live On Coliru

### DateTimeFormat in TypeScript

This should work...

``````var displayDate = new Date().toLocaleDateString();

``````

But I suspect you are trying it on something else, for example:

``````var displayDate = Date.now.toLocaleDateString(); // No!

``````

### How to iterate over a JavaScript object?

You can try using lodash- A modern JavaScript utility library delivering modularity, performance & extras js to fast object iterate:-

_x000D_
_x000D_
``````var  users  =   {_x000D_
'fred':     { _x000D_
'user':   'fred',_x000D_
'age':  40 _x000D_
},_x000D_
'pebbles':  { _x000D_
'user':   'pebbles',_x000D_
'age':  1 _x000D_
}_x000D_
}; _x000D_
_.mapValues(users,  function(o)  { _x000D_
return  o.age; _x000D_
});_x000D_
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)_x000D_
// The `_.property` iteratee shorthand._x000D_
console.log(_.mapValues(users,  'age')); // returns age property & value _x000D_
console.log(_.mapValues(users,  'user')); // returns user property & value _x000D_
console.log(_.mapValues(users)); // returns all objects _x000D_
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)``````
_x000D_
``<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.js"></script>``
_x000D_
_x000D_
_x000D_

### How to trigger checkbox click event even if it's checked through Javascript code?

You can use `.change()` function too

E.g.:

``````\$('form input[type=checkbox]').change(function() { console.log('hello') });
``````

### How can I get the order ID in WooCommerce?

As of woocommerce 3.0

``````\$order->id;
``````

will not work, it will generate notice, use getter function:

``````\$order->get_id();
``````

The same applies for other woocommerce objects like procut.

### Git fatal: protocol 'https' is not supported

#### Problem is probably this.

You tried to paste it using

• CTRL +V

before and it didn't work so you went ahead and pasted it with classic

• Right Click - Paste**.

• a hidden ^?

(at least on my machine it encoded like that).

the character that you only appears after you

• backspace

(go ahead an try it on git bash).

So your link becomes `^?https://...`

which is invalid.

### Set ANDROID_HOME environment variable in mac

As a noob I was struggling a lot with setting up the variable.I was creating copies of .bash_profile files, the text in file was not saving etc ..

So I documented the the steps that worked for me. It is simple and foolproof( but little lengthy ) way to do it ?

Step1. Go to Finder >Go(on top) , click on users, then your user account you will see something like this :

Step2. Now hold down ⌘ + ? + . (dot) , this will now display hidden files and folders. It will look something like this:

PS: If the ⌘ + ? +. does not work, please look up the keyboard shortcut relevant for your Mac Operating system name

Step3.

Scenario A :If `.bash_profile` already exists

Step3.A.1 :Double click the .bash_profile. It should open up with TextEdit ( or alternatively right click >open with >TextEdit)

Step3.A.2 : Paste the variable text in the .bash_profile file using ⌘ + V

Step3.A.3 :Save the .bash_profile file using ⌘ + S

Scenario B :If `.bash_profile` does NOT exist This is kind silly way of doing it , but it worked perfectly for noob like me

Step3.B.1 : Download free BBEdit text editor which is pretty light weight. Whats special about this editor is that it lets you save file that starts with ". "

Step3.B.2 : Create a new file

Step3.B.3 : Save the file in your account folder . A warning will pop up , which looks something like this:

Click Use"." button. Then the blank .bash_profile file will be saved

Step3.B.4 : Paste the variable text in the .bash_profile file using ⌘ + V

Step3.B.5 :Save the .bash_profile file using ⌘ + S

Step 4: Last and final step is to check if the above steps worked. Open the bash and type `echo \$ANDROID_HOME`

Your ANDROID_HOME variable should be now set.

### How to concatenate string and int in C?

Use `sprintf` (or `snprintf` if like me you can't count) with format string `"pre_%d_suff"`.

For what it's worth, with itoa/strcat you could do:

``````char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");
``````

### CSS I want a div to be on top of everything

You need to add `position:relative;` to the menu. Z-index only works when you have a non static positioning scheme.

### How to compare data between two table in different databases using Sql Server 2008?

Comparing the two Databases in SQL Database. Try this Query it may help.

``````SELECT T.[name] AS [table_name], AC.[name] AS [column_name],  TY.[name] AS
system_data_type FROM    [***Database Name 1***].sys.[tables] AS T
INNER JOIN [***Database Name 1***].sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
INNER JOIN [***Database Name 1***].sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id]
EXCEPT SELECT T.[name] AS [table_name], AC.[name] AS [column_name], TY.[name] AS system_data_type FROM    ***Database Name 2***.sys.[tables] AS T
INNER JOIN ***Database Name 2***.sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
INNER JOIN ***Database Name 2***.sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id]
``````

### Using GregorianCalendar with SimpleDateFormat

A `SimpleDateFormat`, as its name indicates, formats `Date`s. Not a `Calendar`. So, if you want to format a `GregorianCalendar` using a `SimpleDateFormat`, you must convert the `Calendar` to a `Date` first:

``````dateFormat.format(calendar.getTime());
``````

And what you see printed is the `toString()` representation of the calendar. It's intended usage is debugging. It's not intended to be used to display a date in a GUI. For that, use a (`Simple`)`DateFormat`.

Finally, to convert from a `String` to a `Date`, you should also use a (`Simple`)`DateFormat` (its `parse()` method), rather than splitting the `String` as you're doing. This will give you a `Date` object, and you can create a `Calendar` from the `Date` by instanciating it (`Calendar.getInstance()`) and setting its time (`calendar.setTime()`).

My advice would be: Googling is not the solution here. Reading the API documentation is what you need to do.

### Where does MAMP keep its php.ini?

I have checked all answers and of course I have used phpinfo() to check the exact location of php.ini. I don't see a File option in the menu bar on my mac. I changed both php.ini and php.ini.temp files in that folder. No vail.

Until I realized that I forgot to uncomment the modified always_populate_raw_post_data line.

### How can I combine flexbox and vertical scroll in a full-height app?

Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.

The solution is setting a height to the vertical scrollable element. For example:

``````#container article {
flex: 1 1 auto;
overflow-y: auto;
height: 0px;
}
``````

The element will have height because flexbox recalculates it unless you want a min-height so you can use `height: 100px;` that it is exactly the same as: `min-height: 100px;`

``````#container article {
flex: 1 1 auto;
overflow-y: auto;
height: 100px; /* == min-height: 100px*/
}
``````

So the best solution if you want a `min-height` in the vertical scroll:

``````#container article {
flex: 1 1 auto;
overflow-y: auto;
min-height: 100px;
}
``````

If you just want full vertical scroll in case there is no enough space to see the article:

``````#container article {
flex: 1 1 auto;
overflow-y: auto;
min-height: 0px;
}
``````

The final code: http://jsfiddle.net/ch7n6/867/

### Adding an onclick function to go to url in JavaScript?

In case you're dealing with `<a>` tag, and you want to interrupt going to the default `href` you should use `this` instead.

Go to default url (yahoo):

``````<a href="https://yahoo.com" onclick="location.href='https://google.com';">
``````

Go to new url (google) `onclick`:

``````<a href="https://yahoo.com" onclick="this.href='https://google.com';">
``````

By using `this` you're interrupting the current browser `onclick` event and changing `href` before continuing to default behaviour of `<a href='...`

### Can you explain the HttpURLConnection connection process?

``````String message = URLEncoder.encode("my message", "UTF-8");

try {
// instantiate the URL object with the target URL of the resource to
// request
URL url = new URL("http://www.example.com/comment");

// instantiate the HttpURLConnection with the URL object - A new
// connection is opened every time by calling the openConnection
// method of the protocol handler for this URL.
// 1. This is the point where the connection is opened.
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// set connection output to true
connection.setDoOutput(true);
// instead of a GET, we're going to send using method="POST"
connection.setRequestMethod("POST");

// instantiate OutputStreamWriter using the output stream, returned
// from getOutputStream, that writes to this connection.
// 2. This is the point where you'll know if the connection was
// successfully established. If an I/O error occurs while creating
// the output stream, you'll see an IOException.
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());

// write data to the connection. This is data that you are sending
// to the server
// 3. No. Sending the data is conducted here. We established the
// connection with getOutputStream
writer.write("message=" + message);

// Closes this output stream and releases any system resources
// associated with this stream. At this point, we've sent all the
// data. Only the outputStream is closed at this point, not the
// actual connection
writer.close();
// if there is a response code AND that response code is 200 OK, do
// stuff in the first if block
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK

// otherwise, if any other status code is returned, or no status
// code is returned, do stuff in the else block
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
``````

The first 3 answers to your questions are listed as inline comments, beside each method, in the example HTTP POST above.

From getOutputStream:

Returns an output stream that writes to this connection.

Basically, I think you have a good understanding of how this works, so let me just reiterate in layman's terms. `getOutputStream` basically opens a connection stream, with the intention of writing data to the server. In the above code example "message" could be a comment that we're sending to the server that represents a comment left on a post. When you see `getOutputStream`, you're opening the connection stream for writing, but you don't actually write any data until you call `writer.write("message=" + message);`.

From getInputStream():

Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.

`getInputStream` does the opposite. Like `getOutputStream`, it also opens a connection stream, but the intent is to read data from the server, not write to it. If the connection or stream-opening fails, you'll see a `SocketTimeoutException`.

How about the getInputStream? Since I'm only able to get the response at getInputStream, then does it mean that I didn't send any request at getOutputStream yet but simply establishes a connection?

Keep in mind that sending a request and sending data are two different operations. When you invoke getOutputStream or getInputStream `url.openConnection()`, you send a request to the server to establish a connection. There is a handshake that occurs where the server sends back an acknowledgement to you that the connection is established. It is then at that point in time that you're prepared to send or receive data. Thus, you do not need to call getOutputStream to establish a connection open a stream, unless your purpose for making the request is to send data.

In layman's terms, making a `getInputStream` request is the equivalent of making a phone call to your friend's house to say "Hey, is it okay if I come over and borrow that pair of vice grips?" and your friend establishes the handshake by saying, "Sure! Come and get it". Then, at that point, the connection is made, you walk to your friend's house, knock on the door, request the vice grips, and walk back to your house.

Using a similar example for `getOutputStream` would involve calling your friend and saying "Hey, I have that money I owe you, can I send it to you"? Your friend, needing money and sick inside that you kept it for so long, says "Sure, come on over you cheap bastard". So you walk to your friend's house and "POST" the money to him. He then kicks you out and you walk back to your house.

Now, continuing with the layman's example, let's look at some Exceptions. If you called your friend and he wasn't home, that could be a 500 error. If you called and got a disconnected number message because your friend is tired of you borrowing money all the time, that's a 404 page not found. If your phone is dead because you didn't pay the bill, that could be an IOException. (NOTE: This section may not be 100% correct. It's intended to give you a general idea of what's happening in layman's terms.)

Question #5:

Yes, you are correct that openConnection simply creates a new connection object but does not establish it. The connection is established when you call either getInputStream or getOutputStream.

`openConnection` creates a new connection object. From the URL.openConnection javadocs:

A new connection is opened every time by calling the openConnection method of the protocol handler for this URL.

The connection is established when you call openConnection, and the InputStream, OutputStream, or both, are called when you instantiate them.

Question #6:

To measure the overhead, I generally wrap some very simple timing code around the entire connection block, like so:

``````long start = System.currentTimeMillis();
log.info("Time so far = " + new Long(System.currentTimeMillis() - start) );

// run the above example code here
log.info("Total time to send/receive data = " + new Long(System.currentTimeMillis() - start) );
``````

I'm sure there are more advanced methods for measuring the request time and overhead, but this generally is sufficient for my needs.

For information on closing connections, which you didn't ask about, see In Java when does a URL connection close?.

### What does AND 0xFF do?

if `byte1` is an 8-bit integer type then it's pointless - if it is more than 8 bits it will essentially give you the last 8 bits of the value:

``````    0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
&  0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
-------------------------------
0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1
``````

### Which comment style should I use in batch files?

There are a number of ways to comment in a batch file

1)Using rem

This is the official way. It apparently takes longer to execute than `::`, although it apparently stops parsing early, before the carets are processed. Percent expansion happens before rem and `::` are identified, so incorrect percent usage i.e. `%~` will cause errors if percents are present. Safe to use anywhere in code blocks.

2)Using labels `:`, `::` or `:;` etc.

For `:: comment`, ': comment' is an invalid label name because it begins with an invalid character. It is okay to use a colon in the middle of a label though. If a space begins at the start of label, it is removed `: label` becomes `:label`. If a space or a colon appears in the middle of the label, the rest of the name is not interpreted meaning that if there are two labels `:f:oo` and `:f rr`, both will be interpreted as `:f` and only the later defined label in the file will be jumped to. The rest of the label is effectively a comment. There are multiple alternatives to `::`, listed here. You can never `goto` or `call` a `::foo` label. `goto :foo` and `goto ::foo` will not work.

They work fine outside of code blocks but after a label in a code block, invalid or not, there has to be a valid command line. `:: comment` is indeed another valid command. It interprets it as a command and not a label; the command has precedence. Which is the command to cd to the `::` volume, which will work if you have executed `subst :: C:\`, otherwise you get a cannot find the volume error. That's why `:;` is arguably better because it cannot be interpreted in this way, and therefore is interpreted as a label instead, which serves as the valid command. This is not recursive, i.e, the next label does not need a command after it. That's why they come in twos.

You need to provide a valid command after the label e.g. `echo something`. A label in a code block has to come with at least one valid command, so the lines come in pairs of two. You will get an unexpected `)` error if there is a space or a closing parenthesis on the next line. If there is a space between the two `::` lines you will get an invalid syntax error.

You can also use the caret operator in the `::` comment like so:

``````@echo off

echo hello
(
:;(^
this^
is^
a^
comment^
)
:;
)
:;^
this^
is^
a^
comment
:;
)
``````

But you need the trailing `:;` for the reason stated above.

``````@echo off

(
echo hello
:;
:; comment
:; comment
:;
)
echo hello

``````

It is fine as long as there is an even number. This is undoubtedly the best way to comment -- with 4 lines and `:;`. With `:;` you don't get any errors that need to be suppressed using `2> nul` or `subst :: C:\`. You could use `subst :: C:\` to make the volume not found error go away but it means you will have to also put C: in the code to prevent your working directory from becoming `::\`.

To comment at the end of a line you can do `command &::` or `command & rem comment`, but there still has to be an even number, like so:

``````@echo off

(
echo hello & :;yes
echo hello & :;yes
:;
)

echo hello
``````

The first `echo hello & :;yes` has a valid command on the next line but the second `& :;yes` does not, so it needs one i.e. the `:;`.

3)Using an invalid environment variable

`%= comment =%`. In a batch file, environment variables that are not defined are removed from the script. This makes it possible to use them at the end of a line without using `&`. It is custom to use an invalid environment variable i.e. one that contains an equals sign. The extra equals is not required but makes it look symmetrical. Also, variable names starting with "=" are reserved for undocumented dynamic variables. Those dynamic variables never end with "=", so by using an "=" at both the start and end of the comment, there is no possibility of a name clash. The comment cannot contain `%` or `:`.

``````@echo off
echo This is an example of an %= Inline Comment =% in the middle of a line.
``````

4)As a command, redirecting stderr to nul

``````@echo off
(
echo hello
;this is a comment 2> nul
;this is another comment  2> nul
)
``````

5)At the end of a file, everything after an unclosed parenthesis is a comment

``````@echo off
(
echo hello
)

(this is a comment
this is a comment
this is a comment
``````

### How do I join two SQLite tables in my Android application?

"Ambiguous column" usually means that the same column name appears in at least two tables; the database engine can't tell which one you want. Use full table names or table aliases to remove the ambiguity.

Here's an example I happened to have in my editor. It's from someone else's problem, but should make sense anyway.

``````select P.*
from product_has_image P
inner join highest_priority_images H
on (H.id_product = P.id_product and H.priority = p.priority)
``````

### CSS - make div's inherit a height

The negative margin trick:

http://pastehtml.com/view/1dujbt3.html

Not elegant, I suppose, but it works in some cases.

### How to Use Order By for Multiple Columns in Laravel 4?

Use order by like this:

``````return User::orderBy('name', 'DESC')
->orderBy('surname', 'DESC')
->orderBy('email', 'DESC')
...
->get();
``````

### How do I make a semi transparent background?

``````div.main{
width:100%;
height:550px;
background: url('https://images.unsplash.com/photo-1503135935062-
b7d1f5a0690f?ixlib=rb-enter code here0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=cf4d0c234ecaecd14f51a2343cc89b6c&dpr=1&auto=format&fit=crop&w=376&h=564&q=60&cs=tinysrgb') no-repeat;
background-position:center;
background-size:cover
}
div.main>div{
width:100px;
height:320px;
background:transparent;
background-attachment:fixed;
border-top:25px solid orange;
border-left:120px solid orange;
border-bottom:25px solid orange;
border-right:10px solid orange;
margin-left:150px
}
``````

### Make footer stick to bottom of page correctly

Use this one. It will fix it.

``````#ibox_footer {
position: absolute;
height: 20px;
margin-bottom: 0;
bottom: 0;
width: 100%;
}
``````

### How to loop backwards in python?

``````for x in reversed(whatever):
do_something()
``````

This works on basically everything that has a defined order, including `xrange` objects and lists.

### Including JavaScript class definition from another file in Node.js

Using ES6, you can have `user.js`:

``````export default class User {
constructor() {
...
}
}
``````

And then use it in `server.js`

``````const User = require('./user.js').default;
const user = new User();
``````

### Check if my SSL Certificate is SHA1 or SHA2

Update: The site below is no longer running because, as they say on the site:

As of January 1, 2016, no publicly trusted CA is allowed to issue a SHA-1 certificate. In addition, SHA-1 support was removed by most modern browsers and operating systems in early 2017. Any new certificate you get should automatically use a SHA-2 algorithm for its signature.

Legacy clients will continue to accept SHA-1 certificates, and it is possible to have requested a certificate on December 31, 2015 that is valid for 39 months. So, it is possible to see SHA-1 certificates in the wild that expire in early 2019.

You can also use https://shaaaaaaaaaaaaa.com/ - set up to make this particular task easy. The site has a text box - you type in your site domain name, click the Go button and it then tells you whether the site is using SHA1 or SHA2.

Background

### How to increase the max connections in postgres?

change max_connections variable in postgresql.conf file located in /var/lib/pgsql/data or /usr/local/pgsql/data/

### How to automatically generate unique id in SQL like UID12345678?

Table Creating

``````create table emp(eno int identity(100001,1),ename varchar(50))
``````

Values inserting

``````insert into emp(ename)values('narendra'),('ajay'),('anil'),('raju')
``````

Select Table

``````select * from emp
``````

Output

``````eno     ename
100001  narendra
100002  rama
100003  ajay
100004  anil
100005  raju
``````

### vertical-align: middle with Bootstrap 2

i use this

``````<style>
.row-fluid{height:100%;display:table-cell;vertical-align:middle;width:100%}
.centering{float:none;margin:0 auto}
</style>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="offset3 span6 centering">
content here
</div>
</div>
</div>
</body>
``````

### How to unzip gz file using Python

It is very simple.. Here you go !!

``````import gzip

#path_to_file_to_be_extracted

ip = sample.gzip

#output file to be filled

op = open("output_file","w")

with gzip.open(ip,"rb") as ip_byte:
wf.close()
``````

### Import Google Play Services library in Android Studio

I followed setup guide http://developer.android.com/google/play-services/setup.html and it works!

Summary:

2. Added dependency in build.gradle: `compile 'com.google.android.gms:play-services:4.0.30'`
3. Updated AndroidManifest.xml with `<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />`

### How to Get Element By Class in JavaScript?

Of course, all modern browsers now support the following simpler way:

``````var elements = document.getElementsByClassName('someClass');
``````

but be warned it doesn't work with IE8 or before. See http://caniuse.com/getelementsbyclassname

Also, not all browsers will return a pure `NodeList` like they're supposed to.

You're probably still better off using your favorite cross-browser library.

### Get GPS location via a service in Android

``````public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private LocationRequest mLocationRequest;
private static final String LOGSERVICE = "#######";

@Override
public void onCreate() {
super.onCreate();
Log.i(LOGSERVICE, "onCreate");

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOGSERVICE, "onStartCommand");

return START_STICKY;
}

@Override
public void onConnected(Bundle bundle) {
Log.i(LOGSERVICE, "onConnected" + bundle);

if (l != null) {
Log.i(LOGSERVICE, "lat " + l.getLatitude());
Log.i(LOGSERVICE, "lng " + l.getLongitude());

}

startLocationUpdate();
}

@Override
public void onConnectionSuspended(int i) {
Log.i(LOGSERVICE, "onConnectionSuspended " + i);

}

@Override
public void onLocationChanged(Location location) {
Log.i(LOGSERVICE, "lat " + location.getLatitude());
Log.i(LOGSERVICE, "lng " + location.getLongitude());
LatLng mLocation = (new LatLng(location.getLatitude(), location.getLongitude()));
EventBus.getDefault().post(mLocation);

}

@Override
public void onDestroy() {
super.onDestroy();
Log.i(LOGSERVICE, "onDestroy - Estou sendo destruido ");

}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(LOGSERVICE, "onConnectionFailed ");

}

private void initLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(2000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

}

private void startLocationUpdate() {
initLocationRequest();

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
}

private void stopLocationUpdate() {

}

.build();
}

}
``````

### Using %s in C correctly - very basic level

``````void myfunc(void)
{
char* text = "Hello World";
char  aLetter = 'C';

printf("%s\n", text);
printf("%c\n", aLetter);
}
``````

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

``````Dir[File.join(__dir__, "/app/**/*.rb")].each do |file|
require file
end
``````

This will work recursively on your local machine and a remote (Like Heroku) which does not use relative paths.

### Constant pointer vs Pointer to constant

``````const int* ptr;
``````

declares `ptr` a pointer to `const int` type. You can modify `ptr` itself but the object pointed to by `ptr` shall not be modified.

``````const int a = 10;
const int* ptr = &a;
*ptr = 5; // wrong
ptr++;    // right
``````

While

``````int * const ptr;
``````

declares `ptr` a `const` pointer to `int` type. You are not allowed to modify `ptr` but the object pointed to by `ptr` can be modified.

``````int a = 10;
int *const ptr = &a;
*ptr = 5; // right
ptr++;    // wrong
``````

Generally I would prefer the declaration like this which make it easy to read and understand (read from right to left):

``````int const  *ptr; // ptr is a pointer to constant int
int *const ptr;  // ptr is a constant pointer to int
``````

### How to replace a substring of a string

You are probably not assigning it after doing the replacement or replacing the wrong thing. Try :

``````String haystack = "abcd=0; efgh=1";
String result = haystack.replaceAll("abcd","dddd");
``````

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

In your application android manifest file, under the application tag you can try several of these themes.

Replace

``````<application
android:theme="@style/AppTheme" >
``````

with different themes defined by the android system. They can be like:-

``````android:theme="@android:style/Theme.Black"
android:theme="@android:style/Theme.DeviceDefault"
android:theme="@android:style/Theme.DeviceDefault.Dialog"
android:theme="@android:style/Theme.Holo"
android:theme="@android:style/Theme.Translucent"
``````

Each of these themes will have a different effect on your application like the DeviceDefault.Dialog will make your application look like a dialog box. You should try more of these. You can have a look from the android sdk or simply use auto complete in Eclipse IDE to explore the various available options.

A correct way to define your own theme would be to edit the `styles.xml` file present in the resources folder of your application.

### Creating a list of pairs in java

Similar to what Mark E has proposed, you have to come up with your own. Just to help you a bit, there is a neat article http://gleichmann.wordpress.com/2008/01/15/building-your-own-literals-in-java-tuples-and-maps/ which gives you a really neat way of creating tuples and maps that might be something you might want to consider.

### How do you add a timed delay to a C++ program?

You can also use select(2) if you want microsecond precision (this works on platform that don't have usleep(3))

The following code will wait for 1.5 second:

``````#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>`

int main() {
struct timeval t;
t.tv_sec = 1;
t.tv_usec = 500000;
select(0, NULL, NULL, NULL, &t);
}
``````

`

### Best way to check if a Data Table has a null value in it

``````foreach(DataRow row in dataTable.Rows)
{
if(row.IsNull("myColumn"))
throw new Exception("Empty value!")
}
``````

### How to convert ZonedDateTime to Date?

If you are using the ThreeTen backport for Android and can't use the newer `Date.from(Instant instant)` (which requires minimum of API 26) you can use:

``````ZonedDateTime zdt = ZonedDateTime.now();
Date date = new Date(zdt.toInstant().toEpochMilli());
``````

or:

``````Date date = DateTimeUtils.toDate(zdt.toInstant());
``````

``````\$email_to1 = "[email protected]";