# Programs & Examples On #Array difference

### Difference between two numpy arrays in python

You can also use `numpy.subtract`

It has the advantage over the difference operator, `-`, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

``````array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])
``````

Example: (Python 3.5)

``````import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)
``````

which gives you

``````the difference = [ 0.1  0.2  0.3]
``````

Remember, however, that if you try to subtract sequences (lists or tuples) with the `-` operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

Wrong Code:

``````print([1.1, 2.2, 3.3] - [1, 2, 3])
``````

### How to get the difference between two arrays in JavaScript?

It feels easier to process this as partial functions to me. Quite surprised not to see a functional programming solution, here is mine in ES6:

``````const arrayDiff = (a, b) => {
return diff(b)(a);
}

const contains = (needle) => (array) => {
for (let i=0; i < array.length; i++) {
if (array[i] == needle) return true;
}

return false;
}

const diff = (compare) => {
return (array) => array.filter((elem) => !contains(elem)(compare))
}
``````

### Compare 2 arrays which returns difference

The short version can be like this:

``````const diff = (a, b) => b.filter((i) => a.indexOf(i) === -1);
``````

result:

``````diff(['a', 'b'], ['a', 'b', 'c', 'd']);

["c", "d"]
``````

### How to add a boolean datatype column to an existing table in sql?

In SQL SERVER it is `BIT`, though it allows `NULL` to be stored

``````ALTER TABLE person add  [AdminApproved] BIT default 'FALSE';
``````

Also there are other mistakes in your query

1. When you alter a table to add column no need to mention `column` keyword in `alter` statement

2. For adding default constraint no need to use `SET` keyword

3. Default value for a `BIT` column can be `('TRUE' or '1')` / `('FALSE' or 0)`. `TRUE` or `FALSE` needs to mentioned as `string` not as Identifier

### How to redirect in a servlet filter?

If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):

``````String uri = request.getRequestURI();

String[] uriParts = uri.split("[#?]");
String path = uriParts[0];
String rest = uri.substring(uriParts[0].length());

if(redirectMap.containsKey(path)) {
response.sendRedirect(redirectMap.get(path) + rest);
} else {
chain.doFilter(request, response);
}
``````

### Hive: Convert String to Integer

It would return NULL but if taken as BIGINT would show the number

### bootstrap 4 row height

Use the sizing utility classes...

• `h-50` = height 50%
• `h-100` = height 100%

http://www.codeply.com/go/Y3nG0io2uE

`````` <div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">

</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">

</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">

</div>
</div>
</div>
</div>
</div>
</div>
``````

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the `d-flex flex-column` on the `row`, and `h-100` on the child cols.

``````<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">

</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">

</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">

</div>
</div>
</div>
</div>
</div>
</div>
``````

https://www.codeply.com/go/tgzFAH8vaW

### What is DOM Event delegation?

DOM event delegation is a mechanism of responding to ui-events via a single common parent rather than each child, through the magic of event "bubbling" (aka event propagation).

When an event is triggered on an element, the following occurs:

The event is dispatched to its target `EventTarget` and any event listeners found there are triggered. Bubbling events will then trigger any additional event listeners found by following the `EventTarget`'s parent chain upward, checking for any event listeners registered on each successive EventTarget. This upward propagation will continue up to and including the `Document`.

Event bubbling provides the foundation for event delegation in browsers. Now you can bind an event handler to a single parent element, and that handler will get executed whenever the event occurs on any of its child nodes (and any of their children in turn). This is event delegation. Here's an example of it in practice:

``````<ul onclick="alert(event.type + '!')">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
``````

With that example if you were to click on any of the child `<li>` nodes, you would see an alert of `"click!"`, even though there is no click handler bound to the `<li>` you clicked on. If we bound `onclick="..."` to each `<li>` you would get the same effect.

So what's the benefit?

Imagine you now have a need to dynamically add new `<li>` items to the above list via DOM manipulation:

``````var newLi = document.createElement('li');
newLi.innerHTML = 'Four';
myUL.appendChild(newLi);
``````

Without using event delegation you would have to "rebind" the `"onclick"` event handler to the new `<li>` element, in order for it to act the same way as its siblings. With event delegation you don't need to do anything. Just add the new `<li>` to the list and you're done.

This is absolutely fantastic for web apps with event handlers bound to many elements, where new elements are dynamically created and/or removed in the DOM. With event delegation the number of event bindings can be drastically decreased by moving them to a common parent element, and code that dynamically creates new elements on the fly can be decoupled from the logic of binding their event handlers.

Another benefit to event delegation is that the total memory footprint used by event listeners goes down (since the number of event bindings go down). It may not make much of a difference to small pages that unload often (i.e. user's navigate to different pages often). But for long-lived applications it can be significant. There are some really difficult-to-track-down situations when elements removed from the DOM still claim memory (i.e. they leak), and often this leaked memory is tied to an event binding. With event delegation you're free to destroy child elements without risk of forgetting to "unbind" their event listeners (since the listener is on the ancestor). These types of memory leaks can then be contained (if not eliminated, which is freaking hard to do sometimes. IE I'm looking at you).

Here are some better concrete code examples of event delegation:

### Ball to Ball Collision - Detection and Handling

Improving the solution to detect circle with circle collision detection given within the question:

``````float dx = circle1.x - circle2.x,
dy = circle1.y - circle2.y,
r = circle1.r + circle2.r;
return (dx * dx + dy * dy <= r * r);
``````

It avoids the unnecessary "if with two returns" and the use of more variables than necessary.

### Is it possible to start a shell session in a running container (without ssh)

Keep an eye on this pull request: https://github.com/docker/docker/pull/7409

Which implements the forthcoming `docker exec <container_id> <command>` utility. When this is available it should be possible to e.g. start and stop the ssh service inside a running container.

There is also `nsinit` to do this: "nsinit provides a handy way to access a shell inside a running container's namespace", but it looks difficult to get running. https://gist.github.com/ubergarm/ed42ebbea293350c30a6

### How to find if a given key exists in a C++ std::map

I think you want `map::find`. If `m.find("f")` is equal to `m.end()`, then the key was not found. Otherwise, find returns an iterator pointing at the element found.

The error is because `p.first` is an iterator, which doesn't work for stream insertion. Change your last line to `cout << (p.first)->first;`. `p` is a pair of iterators, `p.first` is an iterator, `p.first->first` is the key string.

A map can only ever have one element for a given key, so `equal_range` isn't very useful. It's defined for map, because it's defined for all associative containers, but it's a lot more interesting for multimap.

### What does "Could not find or load main class" mean?

Use this command:

``````java -cp . [PACKAGE.]CLASSNAME
``````

Example: If your classname is Hello.class created from Hello.java then use the below command:

``````java -cp . Hello
``````

If your file Hello.java is inside package com.demo then use the below command

``````java -cp . com.demo.Hello
``````

With JDK 8 many times it happens that the class file is present in the same folder, but the `java` command expects classpath and for this reason we add `-cp .` to take the current folder as reference for classpath.

### SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

In my case I searched for services. Then found a service called "SQL Server(SQLEXPRESS). Then right click on that. Select properties. Then click start. That's all. Solved the issue.

### Binding a WPF ComboBox to a custom list

To bind the data to ComboBox

``````List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });

cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";

cbotest.SelectedValue = "2";
``````

`ComboData` looks like:

``````public class ComboData
{
public int Id { get; set; }
public string Value { get; set; }
}
``````

(note that `Id` and `Value` have to be properties, not class fields)

### How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

### What does "javax.naming.NoInitialContextException" mean?

It basically means that the application wants to perform some "naming operations" (e.g. JNDI or LDAP lookups), and it didn't have sufficient information available to be able to create a connection to the directory server. As the docs for the exception state,

This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

And if you dutifully have a look at the javadocs for InitialContext, they describe quite well how the initial context is constructed, and what your options are for supplying the address/credentials/etc.

If you have a go at creating the context and get stuck somewhere else, please post back explaining what you've done so far and where you're running aground.

### How can I use a C++ library from node.js?

Look at node-ffi.

node-ffi is a Node.js addon for loading and calling dynamic libraries using pure JavaScript. It can be used to create bindings to native libraries without writing any C++ code.

### HTML select form with option to enter custom value

You can't really. You'll have to have both the drop down, and the text box, and have them pick or fill in the form. Without javascript you could create a separate radio button set where they choose dropdown or text input, but this seems messy to me. With some javascript you could toggle disable one or the other depending on which one they choose, for instance, have an 'other' option in the dropdown that triggers the text field.

### Detect click inside/outside of element with single event handler

``````<style type="text/css">
div {border: 1px solid red; color: black; background-color: #9999DD;
width: 20em; height: 40em;}
</style>

<script type="text/javascript">
function sayLoc(e) {
e = e || window.event;
var tgt = e.target || e.srcElement;

// Get top lef co-ords of div
var divX = findPosX(tgt);
var divY = findPosY(tgt);

// Workout if page has been scrolled
var pXo = getPXoffset();
var pYo = getPYoffset();

// Subtract div co-ords from event co-ords
var clickX = e.clientX - divX + pXo;
var clickY = e.clientY - divY + pYo;

alert('Co-ords within div (x, y): '
+ clickX + ', ' + clickY);
}

function findPosX(obj) {
var curleft = 0;
if (obj.offsetParent) {
while (obj.offsetParent) {
curleft += obj.offsetLeft
obj = obj.offsetParent;
}
} else if (obj.x) {
curleft += obj.x;
}
return curleft;
}

function findPosY(obj) {
var curtop = 0;
if (obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop
obj = obj.offsetParent;
}
} else if (obj.y) {
curtop += obj.y;
}
return curtop;
}

function getPXoffset(){
if (self.pageXOffset) { // all except Explorer
return self.pageXOffset;
} else if (document.documentElement
&& document.documentElement.scrollTop) {// Explorer 6 Strict
return document.documentElement.scrollLeft;
} else if (document.body) { // all other Explorers
return document.body.scrollLeft;
}
}

function getPYoffset(){
if (self.pageYOffset) { // all except Explorer
return self.pageYOffset;
} else if (document.documentElement
&& document.documentElement.scrollTop) {// Explorer 6 Strict
return document.documentElement.scrollTop;
} else if (document.body) { // all other Explorers
return document.body.scrollTop;
}
}
</script>

<div onclick="sayLoc(event);"></div>
``````

### No Exception while type casting with a null in java

Casting null values is required for following construct where a method is overloaded and if null is passed to these overloaded methods then the compiler does not know how to clear up the ambiguity hence we need to typecast null in these cases:

``````class A {
public void foo(Long l) {
// do something with l
}
public void foo(String s) {
// do something with s
}
}
new A().foo((String)null);
new A().foo((Long)null);
``````

Otherwise you couldn't call the method you need.

### JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

Quick fix that worked for me:

``````for file in \$(find "\$JAVA_HOME" -name "*pack")
do
unpack200 "\${file}" "\${test_file/%pack/jar}";
done
``````

### AngularJS - Animate ng-view transitions

Check this code:

Javascript:

``````app.config( ["\$routeProvider"], function(\$routeProvider){
\$routeProvider.when("/part1", {"templateUrl" : "part1"});
\$routeProvider.when("/part2", {"templateUrl" : "part2"});
\$routeProvider.otherwise({"redirectTo":"/part1"});
}]
);

function HomeFragmentController(\$scope) {
\$scope.\$on("\$routeChangeSuccess", function (scope, next, current) {
\$scope.transitionState = "active"
});
}
``````

CSS:

``````.fragmentWrapper {
overflow: hidden;
}

.fragment {
position: relative;
-moz-transition-property: left;
-o-transition-property: left;
-webkit-transition-property: left;
transition-property: left;
-moz-transition-duration: 0.1s;
-o-transition-duration: 0.1s;
-webkit-transition-duration: 0.1s;
transition-duration: 0.1s
}

.fragment:not(.active) {
left: 540px;
}

.fragment.active {
left: 0px;
}
``````

Main page HTML:

``````<div class="fragmentWrapper" data-ng-view data-ng-controller="HomeFragmentController">
</div>
``````

Partials HTML example:

``````<div id="part1" class="fragment {{transitionState}}">
</div>
``````

### How do I use a custom deleter with a std::unique_ptr member?

You know, using a custom deleter isn't the best way to go, as you will have to mention it all over your code.
Instead, as you are allowed to add specializations to namespace-level classes in `::std` as long as custom types are involved and you respect the semantics, do that:

Specialize `std::default_delete`:

``````template <>
struct ::std::default_delete<Bar> {
default_delete() = default;
template <class U>
constexpr default_delete(default_delete<U>) noexcept {}
void operator()(Bar* p) const noexcept { destroy(p); }
};
``````

And maybe also do `std::make_unique()`:

``````template <>
inline ::std::unique_ptr<Bar> ::std::make_unique<Bar>() {
auto p = create();
if (!p)
throw std::runtime_error("Could not `create()` a new `Bar`.");
return { p };
}
``````

### How to solve error message: "Failed to map the path '/'."

restarting IIS solved the same issue in my case. Seems like something fails in IIS. Didn't worth my panic, either.

IIS 7.5, btw.

### Count distinct value pairs in multiple columns in SQL

Having to return the count of a unique Bill of Materials (BOM) where each BOM have multiple positions, I dd something like this:

``````select t_item, t_pono, count(distinct ltrim(rtrim(t_item)) + cast(t_pono as varchar(3))) as [BOM Pono Count]
from BOMMaster
where t_pono = 1
group by t_item, t_pono
``````

Given t_pono is a smallint datatype and t_item is a varchar(16) datatype

### Numpy - Replace a number with NaN

``````A[A==NDV]=numpy.nan
``````

A==NDV will produce a boolean array that can be used as an index for A

### How do I convert a PDF document to a preview image in PHP?

You can also try executing the 'convert' utility that comes with imagemagick.

``````exec("convert pdf_doc.pdf image.jpg");
echo 'image-0.jpg';
``````

### What happened to Lodash _.pluck?

If you really want `_.pluck` support back, you can use a mixin:

``````const _ = require("lodash")

_.mixin({
pluck: _.map
})
``````

Because `map` now supports a string (the "iterator") as an argument instead of a function.

### How do I convert between big-endian and little-endian values in C++?

If a big-endian 32-bit unsigned integer looks like 0xAABBCCDD which is equal to 2864434397, then that same 32-bit unsigned integer looks like 0xDDCCBBAA on a little-endian processor which is also equal to 2864434397.

If a big-endian 16-bit unsigned short looks like 0xAABB which is equal to 43707, then that same 16-bit unsigned short looks like 0xBBAA on a little-endian processor which is also equal to 43707.

Here are a couple of handy #define functions to swap bytes from little-endian to big-endian and vice-versa -->

``````// can be used for short, unsigned short, word, unsigned word (2-byte types)
#define BYTESWAP16(n) (((n&0xFF00)>>8)|((n&0x00FF)<<8))

// can be used for int or unsigned int or float (4-byte types)
#define BYTESWAP32(n) ((BYTESWAP16((n&0xFFFF0000)>>16))|((BYTESWAP16(n&0x0000FFFF))<<16))

// can be used for unsigned long long or double (8-byte types)
#define BYTESWAP64(n) ((BYTESWAP32((n&0xFFFFFFFF00000000)>>32))|((BYTESWAP32(n&0x00000000FFFFFFFF))<<32))
``````

### How can I change default dialog button text color in android 5

Using styles.xml (value)

Very Easy solution , change colorPrimary as your choice and it will change color of button text of alert box.

``````<style name="MyAlertDialogStyle" parent="android:Theme.Material.Dialog.Alert">

<!-- Used for the buttons -->
<item name="colorAccent">@android:color/white</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">@color/black</item>

<!-- Used for the background -->
<item name="android:background">#ffffff</item>
<item name="android:colorPrimary">@color/white</item>
<item name="android:colorAccent">@color/white</item>
<item name="android:windowEnterAnimation">@anim/bottom_left_enter</item>
</style>
``````

Alternative (Using Java)

`````` @SuppressLint("ResourceAsColor")
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

.setTitle("Royal Frolics")
.setIcon(R.mipmap.ic_launcher)
.setMessage(message)
.setPositiveButton("OK", (dialog1, which) -> {
//do nothing
result.confirm();
}).create();

dialog.show();

return true;

}
``````

### Python datetime - setting fixed hour and minute after using strptime to get day,month,year

``````from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)
``````

### Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use `CallableStatementCreator` to declare parameters, you will be using Java's standard interface of `CallableStatement`, i.e register out parameters and set them separately. Using `SqlParameter` abstraction will make your code cleaner.

I recommend you looking at `SimpleJdbcCall`. It may be used like this:

``````SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
...
jdbcCall.execute(callParams);
``````

For simple procedures you may use `jdbcTemplate`'s `update` method:

``````jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
``````

### What is ".NET Core"?

.NET Core is an open source and cross platform version of .NET Framework.

### What is the difference between null=True and blank=True in Django?

Null is purely database-related, whereas blank is validation-related. If a field has blank=True , validation on Django's admin site will allow entry of an empty value. If a field has blank=False , the field will be required

### Directory.GetFiles: how to get only filename, not full path?

Have a look at using FileInfo.Name Property

something like

``````string[] files = Directory.GetFiles(dir);

for (int iFile = 0; iFile < files.Length; iFile++)
string fn = new FileInfo(files[iFile]).Name;
``````

Also have a look at using DirectoryInfo Class and FileInfo Class

### Converting a string to a date in a cell

Have you tried the `=DateValue()` function?

To include time value, just add the functions together:

`=DateValue(A1)+TimeValue(A1)`

My fav in "checkout to edit an item and prevent -wild wild west clicks to anywhere- while in a checkout" functions

``````\$('a').click(function(e) {
var = \$(this).attr('disabled');
if (var === 'disabled') {
e.preventDefault();
}
});
``````

So if i want that all external links in a second action toolbar should be disabled while in the "edit-mode" as described above, i'll add in the edit function

``````\$('#actionToolbar .external').attr('disabled', true);
``````

``````<a href="http://goo.gl" target="elsewhere" class="external" disabled="disabled">Google</a>
``````

And now you CAN use disabled property for links

Cheers!

### How to get the HTML's input element of "file" type to only accept pdf files?

Not with the HTML file control, no. A flash file uploader can do that for you though. You could use some client-side code to check for the PDF extension after they select, but you cannot directly control what they can select.

### End of File (EOF) in C

EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.

The code isn't wrong[*], it just doesn't do what you seem to expect. It reads to the end of the input, but you seem to want to read only to the end of a line.

The value of EOF is -1 because it has to be different from any return value from `getchar` that is an actual character. So `getchar` returns any character value as an unsigned char, converted to int, which will therefore be non-negative.

If you're typing at the terminal and you want to provoke an end-of-file, use CTRL-D (unix-style systems) or CTRL-Z (Windows). Then after all the input has been read, `getchar()` will return `EOF`, and hence `getchar() != EOF` will be false, and the loop will terminate.

[*] well, it has undefined behavior if the input is more than LONG_MAX characters due to integer overflow, but we can probably forgive that in a simple example.

### \r\n, \r and \n what is the difference between them?

All 3 of them represent the end of a line. But...

• `\r` (Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line
• `\n` (Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment `\n` moves to the beginning of the line.
• `\r\n` (End Of Line) → a combination of `\r` and `\n`

### How to recursively delete an entire directory with PowerShell 2.0?

I took another approach inspired by @john-rees above - especially when his approach started to fail for me at some point. Basically recurse the subtree and sort files by their path-length - delete from longest to the shortest

``````Get-ChildItem \$tfsLocalPath -Recurse |  #Find all children
Select-Object FullName,@{Name='PathLength';Expression={(\$_.FullName.Length)}} |  #Calculate the length of their path
Sort-Object PathLength -Descending | #sort by path length descending
%{ Get-Item -LiteralPath \$_.FullName } |
Remove-Item -Force
``````

Regarding the -LiteralPath magic, here's another gotchya that may be hitting you: https://superuser.com/q/212808

### How do I create a new line in Javascript?

To create a new line, symbol is '\n'

``````var i;
for(i=10; i>=0; i= i-1){
var s;
for(s=0; s<i; s = s+1){
document.write("*");
}
//i want this to print a new line
document.write('\n');

}
``````

If you are outputting to the page, you'll want to use `"<br/>"` instead of `'/n'`;

Escape characters in JavaScript

### "An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Windows Firewall was creating this error for me. SMTP was trying to post to GMAIL at port 587. Adding port 587 to the Outbound rule [Outbound HTTP/SMTP/RDP] resolved the issue.

### INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

In my case I was using a third party library (i.e. vendor) and the library comes with a sample app which I already had install on my device. So that sample app was now conflicting each time I try to install my own app implementing the library. So I just uninstalled the vendor's sample app and it works afterwards.

### javac not working in windows command prompt

Okay this can not be the case always but many of us have done this mistake in the past and few out of those are still not aware of it, which is, every time you append a path (any path) of any environment variable, you're likely to hit the space bar right after the "semicolon" (as you normally would, after the "period" while typing in an editor).

This will create a leading space in the path e.g " C:\Program Files\Java\jdk1.6.0\bin" and therefore "javac.exe" won't be found by the system.

### Is it possible to use 'else' in a list comprehension?

If you want an `else` you don't want to filter the list comprehension, you want it to iterate over every value. You can use `true-value if cond else false-value` as the statement instead, and remove the filter from the end:

``````table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
``````

### What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: `End` and `End Sub` are not the same. They don't perform the same task.

`End` puts a stop to ALL code execution and you should almost always use `Exit Sub` (or `Exit Function`, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

When executed, the `End` statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the `Stop` statement instead. You can then resume execution while preserving the value of those variables.

Note The `End` statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is `End Sub` and `Exit Sub` the same. `End Sub` can't be called in the same way `Exit Sub` can be, because the compiler doesn't allow it.

This again means you have to `Exit Sub`, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, `End Sub` does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

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

Very probable that your `VISUAL` environment variable is set to something else. Try:

``````export VISUAL=vi
``````

### json Uncaught SyntaxError: Unexpected token :

You've told jQuery to expect a JSONP response, which is why jQuery has added the `callback=jQuery16406345664265099913_1319854793396&_=1319854793399` part to the URL (you can see this in your dump of the request).

What you're returning is JSON, not JSONP. Your response looks like

``````{"red" : "#f00"}
``````

and jQuery is expecting something like this:

``````jQuery16406345664265099913_1319854793396({"red" : "#f00"})
``````

If you actually need to use JSONP to get around the same origin policy, then the server serving `colors.json` needs to be able to actually return a JSONP response.

If the same origin policy isn't an issue for your application, then you just need to fix the `dataType` in your `jQuery.ajax` call to be `json` instead of `jsonp`.

### Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

DO NOT Use GUID For Key

``````ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel)
Guid.NewGuid().ToString(), myScript, true);
``````

and if you want to do that , call Something Like this function

`````` public static string GetGuidClear(string x)
{
return x.Replace("-", "").Replace("0", "").Replace("1", "")
.Replace("2",  "").Replace("3", "").Replace("4", "")
.Replace("5", "").Replace("6", "").Replace("7", "")
.Replace("8", "").Replace("9", "");
}
``````

### map function for objects (instead of arrays)

If you're interested in `map`ping not only values but also keys, I have written `Object.map(valueMapper, keyMapper)`, that behaves this way:

``````var source = { a: 1, b: 2 };
function sum(x) { return x + x }

source.map(sum);            // returns { a: 2, b: 4 }
source.map(undefined, sum); // returns { aa: 1, bb: 2 }
source.map(sum, sum);       // returns { aa: 2, bb: 4 }
``````

### Select only rows if its value in a particular column is less than the value in the other column

If you use `dplyr` package you can do:

``````library(dplyr)
filter(df, aged <= laclen)
``````

### Could not open ServletContext resource

Are you having Tomcat unpack the WAR file? It seems that the files cannot be found on the classpath when a WAR file is loaded and it is not being unpacked.

### How to see local history changes in Visual Studio Code?

I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.

### Use querystring variables in MVC controller

I figured it out...finally found another article on it.

``````string start = Request.QueryString["start"];

string end = Request.QueryString["end"];
``````

### What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

When user press F5 although new request goes to web server and get a responce for the request as well. But when the responce header is Parsed it check the required information in browser cache. If the required information in cache has not expired then that information is restored from in cache itself.

When user click on CTRL-F5 even then new request goes to web server and get a responce. But this time when the responce header is Parsed it do not check any required information in cache, and bring all updated information form server only.

### How to save all console output to file in R?

To save text from the console: run the analysis and then choose (Windows) "File>Save to File".

### Accessing @attribute from SimpleXML

It helped me to convert the result of simplexml_load_file(\$file) into a JSON Structure and decode it back:

``````\$xml = simplexml_load_file("\$token.xml");
\$json = json_encode(\$xml);
\$xml_fixed = json_decode(\$json);

\$try1 = \$xml->structure->{"@attributes"}['value'];
print_r(\$try1);

>> result: SimpleXMLElement Object
(
)

\$try2 = \$xml_fixed->structure->{"@attributes"}['value'];
print_r(\$try2);

>> result: stdClass Object
(
[key] => value
)
``````

### Check if url contains string with JQuery

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

``````if (window.location.href.indexOf("?added-to-cart=555") > -1) {
}
``````

### Using node.js as a simple web server

Rather than dealing with a switch statement, I think it's neater to lookup the content type from a dictionary:

``````var contentTypesByExtension = {
'html': "text/html",
'js':   "text/javascript"
};

...

var contentType = contentTypesByExtension[fileExtension] || 'text/plain';
``````

### Regular expression to match balanced parentheses

I want to add this answer for quickreference. Feel free to update.

.NET Regex using balancing groups.

``````\((?>\((?<c>)|[^()]+|\)(?<-c>))*(?(c)(?!))\)
``````

Where `c` is used as the depth counter.

Demo at Regexstorm.com

PCRE using a recursive pattern.

``````\((?:[^)(]+|(?R))*+\)
``````

Demo at regex101; Or without alternation:

``````\((?:[^)(]*(?R)?)*+\)
``````

Demo at regex101; Or unrolled for performance:

``````\([^)(]*+(?:(?R)[^)(]*)*+\)
``````

Demo at regex101; The pattern is pasted at `(?R)` which represents `(?0)`.

Perl, PHP, Notepad++, R: perl=TRUE, Python: Regex package with `(?V1)` for Perl behaviour.

Ruby using subexpression calls.

With Ruby 2.0 `\g<0>` can be used to call full pattern.

``````\((?>[^)(]+|\g<0>)*\)
``````

Demo at Rubular; Ruby 1.9 only supports capturing group recursion:

``````(\((?>[^)(]+|\g<1>)*\))
``````

Demo at Rubular  (atomic grouping since Ruby 1.9.3)

JavaScript  API :: XRegExp.matchRecursive

``````XRegExp.matchRecursive(str, '\\(', '\\)', 'g');
``````

JS, Java and other regex flavors without recursion up to 2 levels of nesting:

``````\((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)
``````

Demo at regex101. Deeper nesting needs to be added to pattern.
To fail faster on unbalanced parenthesis drop the `+` quantifier.

Java: An interesting idea using forward references by @jaytea.

### Sql Query to list all views in an SQL Server 2005 database

Some time you need to access with `schema` name,as an example you are using AdventureWorks Database you need to access with schemas.

`````` SELECT s.name +'.'+v.name FROM sys.views v inner join sys.schemas s on s.schema_id = v.schema_id
``````

### How can I make a JPA OneToOne relation lazy

If the child entity is used readonly, then it's possible to simply lie and set `optional=false`. Then ensure that every use of that mapped entity is preloaded via queries.

``````public class App {
...
@OneToOne(mappedBy = "app", fetch = FetchType.LAZY, optional = false)
``````

and

``````String sql = " ... FROM App a LEFT JOIN FETCH a.additional aa ...";
``````

... maybe even persisting would work...

### How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., `position: absolute/relative` on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
``````#outer {_x000D_
min-width: 2000px; _x000D_
min-height: 1000px; _x000D_
background: #3e3e3e; _x000D_
position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
left: 1%; _x000D_
top: 45px; _x000D_
width: 50%; _x000D_
height: auto; _x000D_
position: absolute; _x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
background: #efffef;_x000D_
position: absolute; _x000D_
height: 400px; _x000D_
right: 0px; _x000D_
left: 0px;_x000D_
}``````
_x000D_
``````<div id="outer">_x000D_
<div id="inner">_x000D_
<div id="inner-inner"></div>_x000D_
</div>_x000D_
</div>``````
_x000D_
_x000D_
_x000D_

### How to do a background for a label will be without color?

Generally, labels and textboxes that appear in front of an image is best organized in a panel. When rendering, if labels need to be transparent to an image within the panel, you can switch to image as parent of labels in Form initiation like this:

``````var oldParent = panel1;
var newParent = pictureBox1;

foreach (var label in oldParent.Controls.OfType<Label>())
{
label.Location = newParent.PointToClient(label.Parent.PointToScreen(label.Location));
label.Parent = newParent;
label.BackColor = Color.Transparent;
}
``````

I also want to contribute to this answer. I was looking for something similar in jQuery and this what I eventually ended up using.

Basically your HTML markup and CSS would look like this:

``````<style>
#ajaxSpinnerImage {
display: none;
}
</style>

<div id="ajaxSpinnerContainer">
</div>
``````

And then you code for jQuery would look something like this:

``````<script>
\$(document)
.ajaxStart(function () {
\$("#ajaxSpinnerImage").show();
})
.ajaxStop(function () {
\$("#ajaxSpinnerImage").hide();
});

var owmAPI = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=YourAppID";
\$.getJSON(owmAPI)
.done(function (data) {
})
.fail(function () {
});
});
</script>
``````

It is as simple as that :)

### Unable to convert MySQL date/time value to System.DateTime

Let MySql convert your unix timestamp to string. Use the mysql function FROM_UNIXTIME( 113283901 )

### How to insert an element after another element in JavaScript without using a library?

``````referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
``````

Where `referenceNode` is the node you want to put `newNode` after. If `referenceNode` is the last child within its parent element, that's fine, because `referenceNode.nextSibling` will be `null` and `insertBefore` handles that case by adding to the end of the list.

So:

``````function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
``````

You can test it using the following snippet:

_x000D_
_x000D_
``````function insertAfter(referenceNode, newNode) {_x000D_
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);_x000D_
}_x000D_
_x000D_
var el = document.createElement("span");_x000D_
el.innerHTML = "test";_x000D_
var div = document.getElementById("foo");_x000D_
insertAfter(div, el);``````
_x000D_
``<div id="foo">Hello</div>``
_x000D_
_x000D_
_x000D_

### Differences between Emacs and Vim

If you are looking for an objective analysis of both the editors, look at their origins and the philosophy behind their respective designs. Think, which one would suit you better and learn it (and learn it and learn it, because it takes time before you being to discover its true utility as against any IDE). An Introduction to Display Editing with Vi was written by Bill Joy and Mark Horton and he explains why he choose modal design and rationale for various key strokes ( it helps me to remember that CTRL-W +W (will switch to next Window and it will same for CTRL W+ CTRL W, just in case you held the CTRL key for a longer duration.

Here is a link to Emacs timeline and has the reference to Multics Emacs paper. Hereis RMS paper on Emacs, where I see the stress is on a programmable text editor (even way back in 1981 and before).

I have not read the emacs papers, but have read Bill Joy's vi paper a couple of times. Both are old, but still you will get the philosophy and you might choose to use the current tool (vim 7.x or emacs 25?)

Edit: I forgot to mention that it takes patience and imagination to read both these papers as it takes you back in time while reading it. But it is worth.

### Can I underline text in an Android layout?

If you want to achieve this in XML, declare your string in resource and put that resource value into underline tag (<u></u>) of HTML. in TextView, add

``````android:text="@string/your_text_reference"
``````

And in string resource value,

``````<string name="your_text_reference"><u>Underline me</u></string>
``````

If you want to achieve this programmatically, for Kotlin use

``````textView.paintFlags = textView.paintFlags or Paint.UNDERLINE_TEXT_FLAG
``````

or,

``````textView.text = Html.fromHtml("<p><u>Underline me</u></p>")
``````

### Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

``````{{range \$index, \$element := .}}{{\$index}}
{{range \$element}}{{.Value}}
{{end}}
{{end}}
``````

Working example:

``````package main

import (
"html/template"
"os"
)

type EntetiesClass struct {
Name string
Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range \$index, \$element := .}}{{\$index}}
{{range \$element}}{{.Value}}
{{end}}
{{end}}`

func main() {
data := map[string][]EntetiesClass{
"Yoga": {{"Yoga", 15}, {"Yoga", 51}},
"Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
}

t := template.New("t")
t, err := t.Parse(htmlTemplate)
if err != nil {
panic(err)
}

err = t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}

}
``````

Output:

``````Pilates
3
6
9

Yoga
15
51
``````

Playground: http://play.golang.org/p/4ISxcFKG7v

### Regex to check whether a string contains only numbers

Number only regex (Updated)

`````` var reg = new RegExp('[^0-9]','g');
``````

### What does Include() do in LINQ?

The Query EF is sending to the database will yield a larger result at first, but on access no follow-up queries will be made when accessing the included items.

On the other hand, without it, EF would execute separte queries later, when you first access the sub-items.

### How to find elements with 'value=x'?

``````\$('#attached_docs [value="123"]').find ... .remove();
``````

it should do your need however, you cannot duplicate id! remember it

### Is there a way to 'pretty' print MongoDB shell output to a file?

Just put the commands you want to run into a file, then pass it to the shell along with the database name and redirect the output to a file. So, if your find command is in `find.js` and your database is `foo`, it would look like this:

``````./mongo foo find.js >> out.json
``````

### How to send a pdf file directly to the printer using JavaScript?

It's called Print.js

First Include

``````<script src="print.js"></script>
``````

It's basic usage is to call `printJS()` and just pass in a PDF document url: `printJS('docs/PrintJS.pdf')`

What I did was something like this, this will also show "Loading...." if PDF document is too large.

``````<button type="button" onclick="printJS({printable:'docs/xx_large_printjs.pdf', type:'pdf', showModal:true})">
Print PDF with Message
</button>
``````

However keep in mind that:

Firefox currently doesn't allow printing PDF documents using iframes. There is an open bug in Mozilla's website about this. When using Firefox, Print.js will open the PDF file into a new tab.

### How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

``````ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
``````

This is all you need to:

1. Add the `id` column
2. Populate it with a sequence from 1 to count(*).
3. Set it as primary key / not null.

Credit is given to @resnyanskiy who gave this answer in a comment.

### What is the Java equivalent of PHP var_dump?

Your alternatives are to override the `toString()` method of your object to output its contents in a way that you like, or to use reflection to inspect the object (in a way similar to what debuggers do).

The advantage of using reflection is that you won't need to modify your individual objects to be "analysable", but there is added complexity and if you need nested object support you'll have to write that.

This code will list the fields and their values for an `Object` "o"

``````Field[] fields = o.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
System.out.println(fields[i].getName() + " - " + fields[i].get(o));
}
``````

### Android Recyclerview GridLayoutManager column spacing

``````class VerticalGridSpacingDecoration(private val spacing: Int) : RecyclerView.ItemDecoration() {

override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: State
) {
val layoutManager = parent.layoutManager as? GridLayoutManager
if (layoutManager == null || layoutManager.orientation != VERTICAL) {
return super.getItemOffsets(outRect, view, parent, state)
}

val spanCount = layoutManager.spanCount
val column = position % spanCount
with(outRect) {
left = if (column == 0) 0 else spacing / 2
right = if (column == spanCount.dec()) 0 else spacing / 2
top = if (position < spanCount) 0 else spacing
}
}
}
``````

### Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

``````CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
.select(root)
.where(predicateResult);

List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
``````

### How to access site through IP address when website is on a shared host?

Include the port number with the IP address.

For example:

``````http://19.18.20.101:5566
``````

where 5566 is the port number.

### How to remove leading and trailing zeros in a string? Python

`str.strip` is the best approach for this situation, but `more_itertools.strip` is also a general solution that strips both leading and trailing elements from an iterable:

Code

``````import more_itertools as mit

iterables = ["231512-n\n","  12091231000-n00000","alphanum0000", "00alphanum"]
pred = lambda x: x in {"0", "\n", " "}
list("".join(mit.strip(i, pred)) for i in iterables)
# ['231512-n', '12091231000-n', 'alphanum', 'alphanum']
``````

Details

Notice, here we strip both leading and trailing `"0"`s among other elements that satisfy a predicate. This tool is not limited to strings.

`more_itertools` is a third-party library installable via `> pip install more_itertools`.

### Transfer data between databases with PostgreSQL

Just like leonbloy suggested, using two schemas in a database is the way to go. Suppose a source schema (old DB) and a target schema (new DB), you can try something like this (you should consider column names, types, etc.):

``````INSERT INTO target.Awards SELECT * FROM source.Nominations;
``````

### Socket.IO - how do I get a list of connected sockets/clients?

After socket.io 1.0 we cannot use

``````io.sockets.clients();
or
io.sockets.clients('room');
``````

anymore. Instead you can use the following

``````var clients_in_the_room = io.sockets.adapter.rooms[roomId];
for (var clientId in clients_in_the_room ) {
console.log('client: %s', clientId); //Seeing is believing
var client_socket = io.sockets.connected[clientId];//Do whatever you want with this
}
``````

### How to calculate the number of occurrence of a given character in each row of a column of strings?

Another good option, using charToRaw:

``````sum(charToRaw("abc.d.aa") == charToRaw('.'))
``````

### Error 1053 the service did not respond to the start or control request in a timely fashion

After spending too much time on this issue. I found the `EventLog` cause all that mess although I used it properly.

Whoever tackle this issue, I would suggest you to get rid of the `EventLog`. Use better tools like "log4net".

### Setting custom UITableViewCells height

in a custom UITableViewCell -controller add this

``````-(void)layoutSubviews {

CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);

self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
self.frame = newCellViewFrame;

[super layoutSubviews];
}
``````

In the UITableView -controller add this

``````- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [indexPath row] * 1.5; // your dynamic height...
}
``````

### Change location of log4j.properties

Refer to this example taken from - http://www.dzone.com/tutorials/java/log4j/sample-log4j-properties-file-configuration-1.html

``````import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class HelloWorld {

static final Logger logger = Logger.getLogger(HelloWorld.class);
static final String path = "src/resources/log4j.properties";

public static void main(String[] args) {

PropertyConfigurator.configure(path);
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
``````

To change the logger levels - `Logger.getRootLogger().setLevel(Level.INFO);`

### Get push notification while App in foreground iOS

For swift 5 to parse PushNotification dictionary

``````    func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
if application.applicationState == .active {
if let aps1 = data["aps"] as? NSDictionary {
if let dict = aps1["alert"] as? NSDictionary {
if let strTitle = dict["title"] as? String , let strBody = dict["body"] as? String {
if let topVC = UIApplication.getTopViewController() {
//Apply your own logic as per requirement
print("strTitle ::\(strTitle) , strBody :: \(strBody)")
}
}
}
}
}
}
``````

To fetch top viewController on which we show topBanner

``````extension UIApplication {

class func getTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {

if let nav = base as? UINavigationController {
return getTopViewController(base: nav.visibleViewController)

} else if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
return getTopViewController(base: selected)

} else if let presented = base?.presentedViewController {
return getTopViewController(base: presented)
}
return base
}
}
``````

### Fastest way to reset every value of std::vector<int> to 0

``````std::fill(v.begin(), v.end(), 0);
``````

### ImportError: No module named model_selection

do you have sklearn? if not, do the following:

``````sudo pip install sklearn
``````

After installing sklearn

``````from sklearn.model_selection import train_test_split
``````

works fine

### How to parse XML using jQuery?

There is the `\$.parseXML` function for this: http://api.jquery.com/jQuery.parseXML/

You can use it like this:

``````var xml = \$.parseXML(yourfile.xml),
\$xml = \$( xml ),
\$test = \$xml.find('test');

console.log(\$test.text());
``````

If you really want an object, you need a plugin for that. This plugin for instance, will convert your XML to JSON: http://www.fyneworks.com/jquery/xml-to-json/

### Show div on scrollDown after 800px

SCROLLBARS & `\$(window).scrollTop()`

What I have discovered is that calling such functionality as in the solution thankfully provided above, (there are many more examples of this throughout this forum - which all work well) is only successful when scrollbars are actually visible and operating.

If (as I have maybe foolishly tried), you wish to implement such functionality, and you also wish to, shall we say, implement a minimalist "clean screen" free of scrollbars, such as at this discussion, then `\$(window).scrollTop()` will not work.

It may be a programming fundamental, but thought I'd offer the heads up to any fellow newbies, as I spent a long time figuring this out.

If anyone could offer some advice as to how to overcome this or a little more insight, feel free to reply, as I had to resort to show/hide onmouseover/mouseleave instead here

Live long and program, CollyG.

### No server in windows>preferences

You did not install the correct Eclipse distribution. Try install the one labeled "Eclipse IDE for Java EE Developers".

### Why does intellisense and code suggestion stop working when Visual Studio is open?

What worked for me is by disabling and then re-enabling the Resharper

Goto
`Tools -> Options-> Resharper ->General`

Click
`Suspend` -> This disables the resharper

Then check your Intellisense is working or not. In my case, it did and then I resumed the Resharper.

If this does not work, you might need to Goto
`Resharper -> Options-> Environment -> Intellisense -> General`

And
Change Intellisense to `Visual Studio`

### Easiest way to convert a Blob into a byte array

the mySql blob class has the following function :

blob.getBytes

use it like this:

``````//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0)
blob.free();
``````

### How to make primary key as autoincrement for Room Persistence lib

This works for me:

``````@Entity(tableName = "note_table")
data class Note(
@ColumnInfo(name="title") var title: String,
@ColumnInfo(name="description") var description: String = "",
@ColumnInfo(name="priority") var priority: Int,
@PrimaryKey(autoGenerate = true) var id: Int = 0//last so that we don't have to pass an ID value or named arguments
)
``````

Note that the id is last to avoid having to use named arguments when creating the entity, before inserting it into Room. Once it's been added to room, use the id when updating the entity.

### Viewing local storage contents on IE

Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".

### Java sending and receiving file (byte[]) over sockets

Thanks for the help. I've managed to get it working now so thought I would post so that the others can use to help them.

Server:

``````public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;

try {
serverSocket = new ServerSocket(4444);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}

Socket socket = null;
InputStream in = null;
OutputStream out = null;

try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}

try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}

try {
out = new FileOutputStream("M:\\test2.xml");
} catch (FileNotFoundException ex) {
}

byte[] bytes = new byte[16*1024];

int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}

out.close();
in.close();
socket.close();
serverSocket.close();
}
}
``````

and the Client:

``````public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
String host = "127.0.0.1";

socket = new Socket(host, 4444);

File file = new File("M:\\test.xml");
// Get the size of the file
long length = file.length();
byte[] bytes = new byte[16 * 1024];
InputStream in = new FileInputStream(file);
OutputStream out = socket.getOutputStream();

int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}

out.close();
in.close();
socket.close();
}
}
``````

### How to disable scientific notation?

``````format(99999999,scientific = F)
``````

gives

``````99999999
``````

``````<system.web>
<trust level="Full" />
``````

### How to get file name when user select a file via <input type="file" />?

You can get the file name, but you cannot get the full client file-system path.

Try to access to the `value` attribute of your file `input` on the `change` event.

Most browsers will give you only the file name, but there are exceptions like IE8 which will give you a fake path like: `"C:\fakepath\myfile.ext"` and older versions (IE <= 6) which actually will give you the full client file-system path (due its lack of security).

``````document.getElementById('fileInput').onchange = function () {
};
``````

### how do I get eclipse to use a different compiler version for Java?

Eclipse uses it's own internal compiler that can compile to several Java versions.

From Eclipse Help > Java development user guide > Concepts > Java Builder

The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.

For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.

When you configure a project:

``````[project-name] > Properties > Java Compiler > Compiler compliance level
``````

This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.

Host environment variables, eg JAVA_HOME etc, are not used.

The Oracle/Sun JDK compiler is not used.

### Linux Process States

A normal, blocking disc read causes the task to enter the "D" state (as others have noted). Such tasks contribute to the load average, even though they're not consuming the CPU.

Some other types of IO, especially ttys and network, do not behave quite the same - the process ends up in "S" state and can be interrupted and doesn't count against the load average.

### Override browser form-filling and input highlighting with HTML/CSS

Simple javascript solution for all browser:

``````setTimeout(function() {
\$(".parent input").each(function(){
parent = \$(this).parents(".parent");
\$(this).clone().appendTo(parent);
\$(this).attr("id","").attr("name","").hide();
});
}, 300 );
``````

Clone input, reset attribute and hide original input. Timeout is needed for iPad

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

``````public static void main(String... args) throws IOException {
final int runs = 5 * 1000 * 1000;

final ServerSocket ss = new ServerSocket(0);
@Override
public void run() {
try {
Socket serverConn = ss.accept();
String line = "Hello World!\n";
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
for (int count = 0; count < runs; count++)
br.write(line);
serverConn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

Socket conn = new Socket("localhost", ss.getLocalPort());

long start = System.nanoTime();
String line;

List<String> responseData = new ArrayList<String>();
while ((line = in.readLine()) != null) {
}
long time = System.nanoTime() - start;
System.out.println("Average time to read a line was " + time / runs + " ns.");
conn.close();
ss.close();
}
``````

prints

``````Average time to read a line was 158 ns.
``````

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

``````Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
sb.append(chars, 0, len);
}
``````

Still prints

``````Average time to read a line was 159 ns.
``````

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

### Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

I solved it this way:

• Settings ->
• Apps ->
• All Apps ->
• Delete Cache ->
• Force Stop ->
• Delete Data ->
• Force Stop

Then restart your device. Now enjoy...

It's 100% working.

### Android ADB device offline, can't issue commands

In my case, I was running into this problem with a 1st gen Asus Nexus 7. I had increased the logging buffer size from 256K to 4M. As soon as I restored it to the default value (Settings>Developer Settings>Logger buffer sizes), unplugged and plugged the tablet back in, it worked perfectly.

### How to Convert double to int in C?

``````int b;
double a;
a=3669.0;
b=a;
printf("b=%d",b);
``````

this code gives the output as b=3669 only you check it clearly.

### jQuery get the location of an element relative to window

``````    function trbl(e, relative) {
var r = \$(e).get(0).getBoundingClientRect(); relative = \$(relative);

return {
t : r.top    + relative['scrollTop'] (),
r : r.right  + relative['scrollLeft'](),
b : r.bottom + relative['scrollTop'] (),
l : r.left   + relative['scrollLeft']()

}
}

// Example
trbl(e, window);
``````

### Write to custom log file from a Bash script

I did it by using a filter. Most linux systems use rsyslog these days. The config files are located at `/etc/rsyslog.conf` and `/etc/rsyslog.d`.

Whenever I run the command `logger -t SRI some message`, I want "some message" to only show up in `/var/log/sri.log`.

To do this I added the file `/etc/rsyslog.d/00-sri.conf` with the following content.

``````# Filter all messages whose tag starts with SRI
# Note that 'isequal, "SRI:"' or 'isequal "SRI"' will not work.
#
:syslogtag, startswith, "SRI" /var/log/sri.log

# The stop command prevents this message from getting processed any further.
# Thus the message will not show up in /var/log/messages.
#
& stop
``````

Then restart the rsyslogd service:

``````systemctl restart rsyslog.service
``````

Here is a shell session showing the results:

``````[root@rpm-server html]# logger -t SRI Hello World!
[root@rpm-server html]# cat /var/log/sri.log
Jun  5 10:33:01 rpm-server SRI[11785]: Hello World!
[root@rpm-server html]#
[root@rpm-server html]# # see that nothing shows up in /var/log/messages
[root@rpm-server html]# tail -10 /var/log/messages | grep SRI
[root@rpm-server html]#
``````

### Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

You might want to use your local file as a last resort.

Seems as of now jQuery's own CDN does not support https. If it did you then might want to load from there first.

So here's the sequence: Google CDN => Microsoft CDN => Your local copy.

``````<!-- load jQuery from Google's CDN -->
<!-- fallback to Microsoft's Ajax CDN -->
<script> window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js">\x3C/script>')</script>
<!-- fallback to local file -->
<script> window.jQuery || document.write('<script src="Assets/jquery-1.8.3.min.js">\x3C/script>')</script>
``````

### Maximum length of HTTP GET request

Yes. There isn't any limit on a GET request.

I am able to send ~4000 characters as part of the query string using both the Chrome browser and curl command.

I am using Tomcat 8.x server which has returned the expected 200 OK response.

Here is the screenshot of a Google Chrome HTTP request (hiding the endpoint I tried due to security reasons):

RESPONSE

### Google Maps API v3: Can I setZoom after fitBounds?

I use this to ensure the zoom level does not exceed a set level so that I know satellite images will be available.

Add a listener to the `zoom_changed` event. This has the added benefit of controlling the zoom control on the UI also.

Only execute `setZoom` if you need to, so an `if` statement is preferable to `Math.max` or to `Math.min`

``````   google.maps.event.addListener(map, 'zoom_changed', function() {
if ( map.getZoom() > 19 ) {
map.setZoom(19);
}
});
map.fitBounds(bounds);
``````

To prevent zooming out too far:

``````   google.maps.event.addListener(map, 'zoom_changed', function() {
if ( map.getZoom() < 6 ) {
map.setZoom(6);
}
});
map.fitBounds(bounds);
``````

### Are table names in MySQL case sensitive?

Table names in MySQL are file system entries, so they are case insensitive if the underlying file system is.

### Get the string within brackets in Python

``````f = open('abc.log','r')
for line in content:
m = re.search(r"\[(.*?)\]", line)
print m.group(1)

``````

Hope this helps:

``````Magic regex : \[(.*?)\]
``````

Explanation:

`\[` : `[` is a meta char and needs to be escaped if you want to match it literally.

`(.*?)` : match everything in a non-greedy way and capture it.

`\]` : `]` is a meta char and needs to be escaped if you want to match it literally.

### How to declare and initialize a static const array as a class member?

``````// in foo.h
class Foo {
static const unsigned char* Msg;
};

// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;
``````

### RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

``protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } ``

### Create Test Class in IntelliJ

Use the menu selection Navigate -> Test, or Ctrl+Shift+T (Shift+?+T on Mac). This will go to the existing test class, or offer to generate it for you through a little wizard.

### Selecting a Record With MAX Value

What do you mean costs too much? Too much what?

``````SELECT MAX(Balance) AS MaxBalance, CustomerID FROM CUSTOMERS GROUP BY CustomerID
``````

If your table is properly indexed (Balance) and there has got to be an index on the PK than I am not sure what you mean about costs too much or seems unreliable? There is nothing unreliable about an aggregate that you are using and telling it to do. In this case, `MAX()` does exactly what you tell it to do - there's nothing magical about it.

Take a look at `MAX()` and if you want to filter it use the `HAVING` clause.

### How to use Servlets and Ajax?

Indeed, the keyword is "ajax": Asynchronous JavaScript and XML. However, last years it's more than often Asynchronous JavaScript and JSON. Basically, you let JS execute an asynchronous HTTP request and update the HTML DOM tree based on the response data.

Since it's pretty a tedious work to make it to work across all browsers (especially Internet Explorer versus others), there are plenty of JavaScript libraries out which simplifies this in single functions and covers as many as possible browser-specific bugs/quirks under the hoods, such as jQuery, Prototype, Mootools. Since jQuery is most popular these days, I'll use it in the below examples.

# Kickoff example returning `String` as plain text

Create a `/some.jsp` like below (note: the code snippets in this answer doesn't expect the JSP file being placed in a subfolder, if you do so, alter servlet URL accordingly from `"someservlet"` to `"\${pageContext.request.contextPath}/someservlet"`; it's merely omitted from the code snippets for brevity):

``````<!DOCTYPE html>
<html lang="en">
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
\$(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
\$.get("someservlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
\$("#somediv").text(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
<body>
<button id="somebutton">press here</button>
<div id="somediv"></div>
</body>
</html>
``````

Create a servlet with a `doGet()` method which look like this:

``````@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "some text";

response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(text);       // Write response body.
}
``````

Map this servlet on an URL pattern of `/someservlet` or `/someservlet/*` as below (obviously, the URL pattern is free to your choice, but you'd need to alter the `someservlet` URL in JS code examples over all place accordingly):

``````package com.example;

@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
// ...
}
``````

Or, when you're not on a Servlet 3.0 compatible container yet (Tomcat 7, Glassfish 3, JBoss AS 6, etc or newer), then map it in `web.xml` the old fashioned way (see also our Servlets wiki page):

``````<servlet>
<servlet-name>someservlet</servlet-name>
<servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>someservlet</servlet-name>
<url-pattern>/someservlet/*</url-pattern>
</servlet-mapping>
``````

Now open the http://localhost:8080/context/test.jsp in the browser and press the button. You'll see that the content of the div get updated with the servlet response.

# Returning `List<String>` as JSON

With JSON instead of plaintext as response format you can even get some steps further. It allows for more dynamics. First, you'd like to have a tool to convert between Java objects and JSON strings. There are plenty of them as well (see the bottom of this page for an overview). My personal favourite is Google Gson. Download and put its JAR file in `/WEB-INF/lib` folder of your webapplication.

Here's an example which displays `List<String>` as `<ul><li>`. The servlet:

``````@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> list = new ArrayList<>();
String json = new Gson().toJson(list);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
``````

The JS code:

``````\$(document).on("click", "#somebutton", function() {  // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
\$.get("someservlet", function(responseJson) {    // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
var \$ul = \$("<ul>").appendTo(\$("#somediv")); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
\$.each(responseJson, function(index, item) { // Iterate over the JSON array.
\$("<li>").text(item).appendTo(\$ul);      // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
});
});
});
``````

Do note that jQuery automatically parses the response as JSON and gives you directly a JSON object (`responseJson`) as function argument when you set the response content type to `application/json`. If you forget to set it or rely on a default of `text/plain` or `text/html`, then the `responseJson` argument wouldn't give you a JSON object, but a plain vanilla string and you'd need to manually fiddle around with `JSON.parse()` afterwards, which is thus totally unnecessary if you set the content type right in first place.

# Returning `Map<String, String>` as JSON

Here's another example which displays `Map<String, String>` as `<option>`:

``````@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> options = new LinkedHashMap<>();
options.put("value1", "label1");
options.put("value2", "label2");
options.put("value3", "label3");
String json = new Gson().toJson(options);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
``````

And the JSP:

``````\$(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
\$.get("someservlet", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
var \$select = \$("#someselect");                           // Locate HTML DOM element with ID "someselect".
\$select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
\$.each(responseJson, function(key, value) {               // Iterate over the JSON object.
\$("<option>").val(key).text(value).appendTo(\$select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
});
});
});
``````

with

``````<select id="someselect"></select>
``````

# Returning `List<Entity>` as JSON

Here's an example which displays `List<Product>` in a `<table>` where the `Product` class has the properties `Long id`, `String name` and `BigDecimal price`. The servlet:

``````@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = someProductService.list();
String json = new Gson().toJson(products);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
``````

The JS code:

``````\$(document).on("click", "#somebutton", function() {        // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
\$.get("someservlet", function(responseJson) {          // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
var \$table = \$("<table>").appendTo(\$("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
\$.each(responseJson, function(index, product) {    // Iterate over the JSON array.
\$("<tr>").appendTo(\$table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
.append(\$("<td>").text(product.id))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
.append(\$("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
.append(\$("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
});
});
});
``````

# Returning `List<Entity>` as XML

Here's an example which does effectively the same as previous example, but then with XML instead of JSON. When using JSP as XML output generator you'll see that it's less tedious to code the table and all. JSTL is this way much more helpful as you can actually use it to iterate over the results and perform server side data formatting. The servlet:

``````@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = someProductService.list();

request.setAttribute("products", products);
request.getRequestDispatcher("/WEB-INF/xml/products.jsp").forward(request, response);
}
``````

The JSP code (note: if you put the `<table>` in a `<jsp:include>`, it may be reusable elsewhere in a non-ajax response):

``````<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="application/xml" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
<table>
<c:forEach items="\${products}" var="product">
<tr>
<td>\${product.id}</td>
<td><c:out value="\${product.name}" /></td>
<td><fmt:formatNumber value="\${product.price}" type="currency" currencyCode="USD" /></td>
</tr>
</c:forEach>
</table>
</data>
``````

The JS code:

``````\$(document).on("click", "#somebutton", function() {             // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
\$.get("someservlet", function(responseXml) {                // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response XML...
\$("#somediv").html(\$(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "somediv".
});
});
``````

You'll by now probably realize why XML is so much more powerful than JSON for the particular purpose of updating a HTML document using Ajax. JSON is funny, but after all generally only useful for so-called "public web services". MVC frameworks like JSF use XML under the covers for their ajax magic.

# Ajaxifying an existing form

You can use jQuery `\$.serialize()` to easily ajaxify existing POST forms without fiddling around with collecting and passing the individual form input parameters. Assuming an existing form which works perfectly fine without JavaScript/jQuery (and thus degrades gracefully when enduser has JavaScript disabled):

``````<form id="someform" action="someservlet" method="post">
<input type="text" name="foo" />
<input type="text" name="bar" />
<input type="text" name="baz" />
<input type="submit" name="submit" value="Submit" />
</form>
``````

You can progressively enhance it with ajax as below:

``````\$(document).on("submit", "#someform", function(event) {
var \$form = \$(this);

\$.post(\$form.attr("action"), \$form.serialize(), function(response) {
// ...
});

event.preventDefault(); // Important! Prevents submitting the form.
});
``````

You can in the servlet distinguish between normal requests and ajax requests as below:

``````@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
String baz = request.getParameter("baz");

// ...

if (ajax) {
// Handle ajax (JSON or XML) response.
} else {
// Handle regular (JSP) response.
}
}
``````

The jQuery Form plugin does less or more the same as above jQuery example, but it has additional transparent support for `multipart/form-data` forms as required by file uploads.

# Manually sending request parameters to servlet

If you don't have a form at all, but just wanted to interact with the servlet "in the background" whereby you'd like to POST some data, then you can use jQuery `\$.param()` to easily convert a JSON object to an URL-encoded query string.

``````var params = {
foo: "fooValue",
bar: "barValue",
baz: "bazValue"
};

\$.post("someservlet", \$.param(params), function(response) {
// ...
});
``````

The same `doPost()` method as shown here above can be reused. Do note that above syntax also works with `\$.get()` in jQuery and `doGet()` in servlet.

# Manually sending JSON object to servlet

If you however intend to send the JSON object as a whole instead of as individual request parameters for some reason, then you'd need to serialize it to a string using `JSON.stringify()` (not part of jQuery) and instruct jQuery to set request content type to `application/json` instead of (default) `application/x-www-form-urlencoded`. This can't be done via `\$.post()` convenience function, but needs to be done via `\$.ajax()` as below.

``````var data = {
foo: "fooValue",
bar: "barValue",
baz: "bazValue"
};

\$.ajax({
type: "POST",
url: "someservlet",
contentType: "application/json", // NOT dataType!
data: JSON.stringify(data),
success: function(response) {
// ...
}
});
``````

Do note that a lot of starters mix `contentType` with `dataType`. The `contentType` represents the type of the request body. The `dataType` represents the (expected) type of the response body, which is usually unnecessary as jQuery already autodetects it based on response's `Content-Type` header.

Then, in order to process the JSON object in the servlet which isn't being sent as individual request parameters but as a whole JSON string the above way, you only need to manually parse the request body using a JSON tool instead of using `getParameter()` the usual way. Namely, servlets don't support `application/json` formatted requests, but only `application/x-www-form-urlencoded` or `multipart/form-data` formatted requests. Gson also supports parsing a JSON string into a JSON object.

``````JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
String foo = data.get("foo").getAsString();
String bar = data.get("bar").getAsString();
String baz = data.get("baz").getAsString();
// ...
``````

Do note that this all is more clumsy than just using `\$.param()`. Normally, you want to use `JSON.stringify()` only if the target service is e.g. a JAX-RS (RESTful) service which is for some reason only capable of consuming JSON strings and not regular request parameters.

# Sending a redirect from servlet

Important to realize and understand is that any `sendRedirect()` and `forward()` call by the servlet on an ajax request would only forward or redirect the ajax request itself and not the main document/window where the ajax request originated. JavaScript/jQuery would in such case only retrieve the redirected/forwarded response as `responseText` variable in the callback function. If it represents a whole HTML page and not an ajax-specific XML or JSON response, then all you could do is to replace the current document with it.

``````document.open();
document.write(responseText);
document.close();
``````

Note that this doesn't change the URL as enduser sees in browser's address bar. So there are issues with bookmarkability. Therefore, it's much better to just return an "instruction" for JavaScript/jQuery to perform a redirect instead of returning the whole content of the redirected page. E.g. by returning a boolean, or an URL.

``````String redirectURL = "http://example.com";

Map<String, String> data = new HashMap<>();
data.put("redirect", redirectURL);
String json = new Gson().toJson(data);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
``````
``````function(responseJson) {
if (responseJson.redirect) {
window.location = responseJson.redirect;
return;
}

// ...
}
``````

### How to make zsh run as a login shell on Mac OS X (in iTerm)?

``````chsh -s \$(which zsh)
``````

You'll be prompted for your password, but once you update your settings any new iTerm/Terminal sessions you start on that machine will default to zsh.

### Internet Explorer 11 detection

And how I implemented this

``````<script type="text/javascript">
!(window.ActiveXObject) && "ActiveXObject"
function isIE11(){
return !!navigator.userAgent.match(/Trident.*rv[ :]*11\./);
}
</script>
``````

### UITextView that expands to text using auto layout

You can do it through storyboard, just disable "Scrolling Enabled":)

``````<?xml version="1.0" encoding="utf-8"?>
<item
android:id="@+id/play"
android:titleCondensed="Speak"
android:showAsAction="always"
android:title="Speak"
android:icon="@drawable/ic_play">
</item>
<item
android:id="@+id/pause"
android:titleCondensed="Stop"
android:title="Stop"
android:showAsAction="always"
android:icon="@drawable/ic_pause">
</item>
``````

Activity code:

``````@Override
return true;
}

@Override
switch (item.getItemId()) {

case R.id.play:
Toast.makeText(getApplicationContext(), "speaking....", Toast.LENGTH_LONG).show();
return false;

case R.id.pause:
Toast.makeText(getApplicationContext(), "stopping....", Toast.LENGTH_LONG).show();
return false;

default:
break;
}

return false;
}
``````

Fragment code:

``````@Override

public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}

@Override
switch (item.getItemId()) {

case R.id.play:
text = page.getText().toString();
speakOut(text);

// Do Activity menu item stuff here
return true;

case R.id.pause:
speakOf();

// Not implemented here
return true;

default:
break;
}
return false;
}
``````

### Callback when CSS3 transition finishes

The accepted answer currently fires twice for animations in Chrome. Presumably this is because it recognizes `webkitAnimationEnd` as well as `animationEnd`. The following will definitely only fires once:

``````/* From Modernizr */
function whichTransitionEvent(){

var el = document.createElement('fakeelement');
var transitions = {
'animation':'animationend',
'OAnimation':'oAnimationEnd',
'MSAnimation':'MSAnimationEnd',
'WebkitAnimation':'webkitAnimationEnd'
};

for(var t in transitions){
if( transitions.hasOwnProperty(t) && el.style[t] !== undefined ){
return transitions[t];
}
}
}

\$("#elementToListenTo")
.on(whichTransitionEvent(),
function(e){
console.log('Transition complete!  This is the callback!');
\$(this).off(e);
});
``````

### how to display a javascript var in html body

``````<html>
<script type="text/javascript">
var number = 123;
var string = "abcd";

function docWrite(variable) {
document.write(variable);
}
</script>

<body>
<h1>the value for number is: <script>docWrite(number)</script></h1>

<h2>the text is: <script>docWrite(string)</script> </h2>
</body>
</html>
``````

You can shorten `document.write` but can't avoid `<script>` tag

### Implement paging (skip / take) functionality with this query

The fix is to modify your EDMX file, using the XML editor, and change the value of ProviderManifestToken from 2012 to 2008. I found that on line 7 in my EDMX file. After saving that change, the paging SQL will be generated using the “old”, SQL Server 2008 compatible syntax.

My apologies for posting an answer on this very old thread. Posting it for the people like me, I solved this issue today.

### Authenticating against Active Directory with Java on Linux

As ioplex and others have said, there are many options. To authenticate using LDAP (and the Novell LDAP API), I have used something like:

``````
LDAPConnection connection = new LDAPConnection( new LDAPJSSEStartTLSFactory() );
connection.connect(hostname, port);
connection.startTLS();
``````

As a "special feature", Active Directory allows LDAP binds against "user@domain" without using the distinguished name of the account. This code uses StartTLS to enable TLS encryption on the connection; the other alternative is LDAP over SSL, which is not supported by my AD servers.

The real trick is in locating the server and host; the official way is to use a DNS SRV (service) record lookup to locate a bundle of candidate hosts, then do a UDP-based LDAP "ping" (in a particular Microsoft format) to locate the correct server. If you are interested, I've posted some blog articles about my journey of adventure and discovery in that area.

If you want to do Kerberos-based username/password authentication, you are looking at another kettle of fish; it is doable with the Java GSS-API code, although I am not sure it performs the final step to validate the authentication. (The code doing the validation can contact the AD server to check the username and password, which results in a ticket granting ticket for the user, but to ensure the AD server is not being impersonated, it also needs to try to get a ticket for the user to itself, which is somewhat more complicated.)

If you want to do Kerberos-based single sign-on, assuming your users are authenticated to the domain, you can do that as well with the Java GSS-API code. I would post a code sample, but I still need to turn my hideous prototype into something fit for human eyes. Check out some code from SpringSource for some inspiration.

If you are looking for NTLM (which I was given to understand is less secure) or something else, well, good luck.

### Get a list of all functions and procedures in an Oracle database

``````SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
``````

The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.

### Octave/Matlab: Adding new elements to a vector

`x(end+1) = newElem` is a bit more robust.

`x = [x newElem]` will only work if `x` is a row-vector, if it is a column vector `x = [x; newElem]` should be used. `x(end+1) = newElem`, however, works for both row- and column-vectors.

In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)

### Arduino error: does not name a type?

I got the `does not name a type` error when installing the NeoMatrix library.

Solution: the `.cpp` and `.h` files need to be in the top folder when you copy it, e.g:

``````myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp
``````

When I used the default Windows unzip program, it nested the contents inside another folder:

``````myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp
``````

I moved the files up, so it was:

``````myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp
``````

This fixed the `does not name a type` problem.

### How do I delete everything below row X in VBA/Excel?

Another option is `Sheet1.Rows(x & ":" & Sheet1.Rows.Count).ClearContents` (or `.Clear`). The reason you might want to use this method instead of `.Delete` is because any cells with dependencies in the deleted range (e.g. formulas that refer to those cells, even if empty) will end up showing `#REF`. This method will preserve formula references to the cleared cells.

### React-router v4 this.props.history.push(...) not working

For me (react-router v4, react v16) the problem was that I had the navigation component all right:

``````import { Link, withRouter } from 'react-router-dom'

render() {
return (
...
...
);
}
}

``````

Both using either

``````to="/contact"
``````

or

``````OnClick={() => this.props.history.push('/contact')};
``````

The behavior was still the same - the URL in browser changed but wrong components were rendered, the router was called with the same old URL.

The culprit was in the router definition. I had to move the MainMenu component as a child of the Router component!

``````// wrong placement of the component that calls the router
<Router>
<div>
// this is the right place for the component!
<Route path="/" exact component={MainPage} />
<Route path="/contact/" component={MainPage} />
</div>
</Router>
``````

### Stop absolutely positioned div from overlapping text

_x000D_
_x000D_
``````<div style="position: relative; width:600px;">_x000D_
<p>Content of unknown length</p>_x000D_
<div>Content of unknown height</div>_x000D_
<div id="spacer" style="width: 200px; height: 100px; float:left; display:inline-block"></div>_x000D_
<div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;"></div>_x000D_
</div>``````
_x000D_
_x000D_
_x000D_

This should be a comment but I don't have enough reputation yet. The solution works, but visual studio code told me the following putting it into a css sheet:

inline-block is ignored due to the float. If 'float' has a value other than 'none', the box is floated and 'display' is treated as 'block'

So I did it like this

``````.spacer {
float: left;
height: 20px;
width: 200px;
}
``````

And it works just as well.

### How can I select rows with most recent timestamp for each key value?

There is one common answer I haven't see here yet, which is the Window Function. It is an alternative to the correlated sub-query, if your DB supports it.

``````SELECT sensorID,timestamp,sensorField1,sensorField2
FROM (
SELECT sensorID,timestamp,sensorField1,sensorField2
, ROW_NUMBER() OVER(
PARTITION BY sensorID
ORDER BY timestamp
) AS rn
FROM sensorTable s1
WHERE rn = 1
ORDER BY sensorID, timestamp;
``````

I acually use this more than correlated sub-queries. Feel free to bust me in the comments over effeciancy, I'm not too sure how it stacks up in that regard.

### Concatenate string with field value in MySQL

Have you tried using the concat() function?

``````ON tableTwo.query = concat('category_id=',tableOne.category_id)
``````

### Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I had the same issue with my MySQL database but finally, I got a solution which worked for me.
Since in my table everything was fine from the mysql point of view(both tables should use InnoDB engine and the datatype of each column should be of the same type which takes part in foreign key constraint).
The only thing that I did was to disable the foreign key check and later on enabled it after performing the foreign key operation.
Steps that I took:

``````SET foreign_key_checks = 0;
``````
``````alter table tblUsedDestination add constraint f_operatorId foreign key(iOperatorId) references tblOperators (iOperatorId); Query
OK, 8 rows affected (0.23 sec) Records: 8  Duplicates: 0  Warnings: 0
``````
``````SET foreign_key_checks = 1;
``````

### Generate a random letter in Python

``````import random
def guess_letter():
return random.choice('abcdefghijklmnopqrstuvwxyz')
``````

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

``````SELECT COLUMN_NAME,
DATA_TYPE,
CHARACTER_MAXIMUM_LENGTH
FROM information_schema.columns
WHERE TABLE_NAME = 'YOUR_TABLE_NAME'
``````

You can use columns aliases for better looking output.

### Determine the process pid listening on a certain port

Since sockstat wasn't natively installed on my machine I hacked up stanwise's answer to use netstat instead..

``````netstat -nlp | grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:2000" | awk '{print \$7}' | sed -e "s/\/.*//g""
``````

### What is the use of "using namespace std"?

When you make a call to `using namespace <some_namespace>;` all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add `using namespace std;` you can write just `cout` instead of `std::cout` when calling the operator `cout` defined in the namespace `std`.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing `using namespace` you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

``````#include <iostream>
using std::cout;

int main() {
cout << "Hello world!";
return 0;
}
``````

### SQL Server: use CASE with LIKE

This is the syntax you need:

``````CASE WHEN countries LIKE '%'+@selCountry+'%' THEN 'national' ELSE 'regional' END
``````

Although, as per your original problem, I'd solve it differently, splitting the content of @selcountry int a table form and joining to it.

### Why is the jquery script not working?

Use `noConflict()` method

ex:`jQuery.noConflict()`

and Use jQuery via jQuery() instead of via \$()

Ex:`jQuery('#id').val()`; instead of `\$('#id').val()`;

### Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

The accepted answer of how to create an Index inline a Table creation script did not work for me. This did:

``````CREATE TABLE [dbo].[TableToBeCreated]
(
[Id] BIGINT IDENTITY(1, 1) NOT NULL PRIMARY KEY
,[ForeignKeyId] BIGINT NOT NULL
,CONSTRAINT [FK_TableToBeCreated_ForeignKeyId_OtherTable_Id] FOREIGN KEY ([ForeignKeyId]) REFERENCES [dbo].[OtherTable]([Id])
,INDEX [IX_TableToBeCreated_ForeignKeyId] NONCLUSTERED ([ForeignKeyId])
)
``````

Remember, Foreign Keys do not create Indexes, so it is good practice to index them as you will more than likely be joining on them.

### How to delete columns in numpy.array

Given its name, I think the standard way should be `delete`:

``````import numpy as np

A = np.delete(A, 1, 0)  # delete second row of A
B = np.delete(B, 2, 0)  # delete third row of B
C = np.delete(C, 1, 1)  # delete second column of C
``````

According to numpy's documentation page, the parameters for `numpy.delete` are as follow:

`numpy.delete(arr, obj, axis=None)`

• `arr` refers to the input array,
• `obj` refers to which sub-arrays (e.g. column/row no. or slice of the array) and
• `axis` refers to either column wise (`axis = 1`) or row-wise (`axis = 0`) delete operation.

### How to permanently set \$PATH on Linux/Unix?

I think the most elegant way is:

1.add this in ~/.bashrc file Run this command

gedit ~/.bashrc

export PATH=\$PATH:/opt/node/bin

2.source ~/.bashrc

(Ubuntu)

### C++ Array of pointers: delete or delete []?

It would make sens if your code was like this:

``````#include <iostream>

using namespace std;

class Monster
{
public:
Monster() { cout << "Monster!" << endl; }
virtual ~Monster() { cout << "Monster Died" << endl; }
};

int main(int argc, const char* argv[])
{
Monster *mon = new Monster[6];

delete [] mon;

return 0;
}
``````

### Parse JSON in TSQL

``````CREATE FUNCTION dbo.parseJSON( @JSON NVARCHAR(MAX))
RETURNS @hierarchy TABLE
(
element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
sequenceNo [int] NULL, /* the place in the sequence for the element */
parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
NAME NVARCHAR(2000),/* the name of the object */
StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
)
AS
BEGIN
DECLARE
@FirstObject INT, --the index of the first open bracket found in the JSON string
@OpenDelimiter INT,--the index of the next open bracket found in the JSON string
@NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
@NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
@Type NVARCHAR(10),--whether it denotes an object or an array
@NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
@Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
@Start INT, --index of the start of the token that you are parsing
@end INT,--index of the end of the token that you are parsing
@param INT,--the parameter at the end of the next Object/Array token
@EndOfName INT,--the index of the start of the parameter at end of Object/Array token
@token NVARCHAR(200),--either a string or object
@value NVARCHAR(MAX), -- the value as a string
@SequenceNo int, -- the sequence number within a list
@name NVARCHAR(200), --the name as a string
@parent_ID INT,--the next parent ID to allocate
@lenJSON INT,--the current length of the JSON String
@characters NCHAR(36),--used to convert hex to decimal
@result BIGINT,--the value of the hex symbol being parsed
@index SMALLINT,--used for parsing the hex value
@Escape INT --the index of the next escape character

DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
(
String_ID INT IDENTITY(1, 1),
StringValue NVARCHAR(MAX)
)
SELECT--initialise the characters to convert hex to ascii
@characters='0123456789abcdefghijklmnopqrstuvwxyz',
@SequenceNo=0, --set the sequence no. to something sensible.
/* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
@parent_ID=0;
WHILE 1=1 --forever until there is nothing more to do
BEGIN
SELECT
@start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
IF @start=0 BREAK --no more so drop through the WHILE loop
IF SUBSTRING(@json, @start+1, 1)='"'
BEGIN --Delimited Name
SET @start=@Start+1;
SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);
END
IF @end=0 --no end delimiter to last string
BREAK --no more
SELECT @token=SUBSTRING(@json, @start+1, @end-1)
--now put in the escaped control characters
SELECT @token=REPLACE(@token, FROMString, TOString)
FROM
(SELECT
'\"' AS FromString, '"' AS ToString
UNION ALL SELECT '\\', '\'
UNION ALL SELECT '\/', '/'
UNION ALL SELECT '\b', CHAR(08)
UNION ALL SELECT '\f', CHAR(12)
UNION ALL SELECT '\n', CHAR(10)
UNION ALL SELECT '\r', CHAR(13)
UNION ALL SELECT '\t', CHAR(09)
) substitutions
SELECT @result=0, @escape=1
--Begin to take out any hex escape codes
WHILE @escape>0
BEGIN
SELECT @index=0,
--find the next hex escape sequence
@escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
IF @escape>0 --if there is one
BEGIN
WHILE @index<4 --there are always four digits to a \x sequence
BEGIN
SELECT --determine its value
@result=@result+POWER(16, @index)
*(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
@characters)-1), @index=@index+1 ;

END
-- and replace the hex sequence by its unicode value
SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
END
END
--now store the string away
INSERT INTO @Strings (StringValue) SELECT @token
-- and replace the string with a token
SELECT @JSON=STUFF(@json, @start, @end+1,
'@string'+CONVERT(NVARCHAR(5), @@identity))
END
-- all strings are now removed. Now we find the first leaf.
WHILE 1=1  --forever until there is nothing more to do
BEGIN

SELECT @parent_ID=@parent_ID+1
--find the first object or list by looking for the open bracket
SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array
IF @FirstObject = 0 BREAK
IF (SUBSTRING(@json, @FirstObject, 1)='{')
SELECT @NextCloseDelimiterChar='}', @type='object'
ELSE
SELECT @NextCloseDelimiterChar=']', @type='array'
SELECT @OpenDelimiter=@firstObject

WHILE 1=1 --find the innermost object or list...
BEGIN
SELECT
@lenJSON=LEN(@JSON+'|')-1
--find the matching close-delimiter proceeding after the open-delimiter
SELECT
@NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,
@OpenDelimiter+1)
--is there an intervening open-delimiter of either type
SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
IF @NextOpenDelimiter=0
BREAK
SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
IF @NextCloseDelimiter<@NextOpenDelimiter
BREAK
IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'
SELECT @NextCloseDelimiterChar='}', @type='object'
ELSE
SELECT @NextCloseDelimiterChar=']', @type='array'
SELECT @OpenDelimiter=@NextOpenDelimiter
END
---and parse out the list or name/value pairs
SELECT
@contents=SUBSTRING(@json, @OpenDelimiter+1,
@NextCloseDelimiter-@OpenDelimiter-1)
SELECT
@JSON=STUFF(@json, @OpenDelimiter,
@NextCloseDelimiter-@OpenDelimiter+1,
'@'+@type+CONVERT(NVARCHAR(5), @parent_ID))
WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0
BEGIN
IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null
BEGIN
SELECT
@SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.
SELECT  @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA
SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),
@endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),
@param=RIGHT(@token, LEN(@token)-@endofname+1)
SELECT
@token=LEFT(@token, @endofname-1),
@Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)
SELECT  @name=stringvalue FROM @strings
WHERE string_id=@param --fetch the name
END
ELSE
SELECT @Name=null,@SequenceNo=@SequenceNo+1
SELECT
@end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
IF @end=0
SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin)
+1
SELECT
@start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)
--select @start,@end, LEN(@contents+'|'), @contents
SELECT
@Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
@Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
IF SUBSTRING(@value, 1, 7)='@object'
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),
SUBSTRING(@value, 8, 5), 'object'
ELSE
IF SUBSTRING(@value, 1, 6)='@array'
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),
SUBSTRING(@value, 7, 5), 'array'
ELSE
IF SUBSTRING(@value, 1, 7)='@string'
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
FROM @strings
WHERE string_id=SUBSTRING(@value, 8, 5)
ELSE
IF @value IN ('true', 'false')
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
ELSE
IF @value='null'
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
ELSE
IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
ELSE
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
if @Contents=' ' Select @SequenceNo=0
END
END
INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
SELECT '-',1, NULL, '', @parent_id-1, @type
--
RETURN
END
GO
``````

---Pase JSON

``````Declare @pars varchar(MAX) =
' {"shapes":[{"type":"polygon","geofenceName":"","geofenceDescription":"",
"geofenceCategory":"1","color":"#1E90FF","paths":[{"path":[{
"lat":"26.096254906968525","lon":"65.709228515625"}
,{"lat":"28.38173504322308","lon":"66.741943359375"}
,{"lat":"26.765230565697482","lon":"68.983154296875"}
,{"lat":"26.254009699865737","lon":"68.609619140625"}
,{"lat":"25.997549919572112","lon":"68.104248046875"}
,{"lat":"26.843677401113002","lon":"67.115478515625"}
,{"lat":"25.363882272740255","lon":"65.819091796875"}]}]}]}'
Select * from parseJSON(@pars) AS MyResult
``````

### How to get an input text value in JavaScript

``````<script>
}
</script>

<body>
<form>
<input type="text" >+
<input type="text" >
</form>
</body>
``````

### IO Error: The Network Adapter could not establish the connection

Another thing you might want to check that the listener.ora file matches the way you are trying to connect to the DB. If you were connecting via a localhost reference and your listener.ora file got changed from:

``````HOST = localhost
``````

to

``````HOST = 192.168.XX.XX
``````

then this can cause the error that you had unless you update your hosts file to accommodate for this. Someone might have made this change to allow for remote connections to the DB from other machines.

### get string from right hand side

``````SQL> select substr('999123456789', greatest (-9, -length('999123456789')), 9) as value from dual;

VALUE
---------
123456789

SQL> select substr('12345', greatest (-9,  -length('12345')), 9) as value from dual;

VALUE
----
12345
``````

The call to `greatest (-9, -length(string))` limits the starting offset either 9 characters left of the end or the beginning of the string.

### Multiple conditions in an IF statement in Excel VBA

In VBA we can not use `if jj = 5 or 6 then` we must use `if jj = 5 or jj = 6 then`

maybe this:

``````If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then
``````

### How to install APK from PC?

Just connect the device to the PC with a USB cable, then copy the .apk file to the device. On the device, touch the APK file in the file explorer to install it.

You could also offer the .apk on your website. People can download it, then touch it to install.

### ScrollIntoView() causing the whole page to move

``````var el = document.querySelector("yourElement");
window.scroll({top: el.offsetTop, behavior: 'smooth'});
``````

### Authentication issue when debugging in VS2013 - iis express

I had just upgraded to VS 2013 from VS 2012 and the current user identity (HttpContext.User.Identity) was coming through as anonymous.

I tried changing the IIS express applicationhost.config, no difference.

The solution was to look at the properties of the web project, hit F4 to get the project properties when you have the top level of the project selected. Do not right click on the project and select properties, this is something entirely different.

Change Anonymous Authentication to be Disabled and Windows Authentication to be Enabled.

Works like gravy :)

### How do I output coloured text to a Linux terminal?

I use the following solution, it's quite simple and elegant, can be easily pasted into source, and works on Linux/Bash:

``````const std::string red("\033[0;31m");
const std::string green("\033[1;32m");
const std::string yellow("\033[1;33m");
const std::string cyan("\033[0;36m");
const std::string magenta("\033[0;35m");
const std::string reset("\033[0m");

std::cout << "Measured runtime: " << yellow << timer.count() << reset << std::endl;
``````

### Python TypeError must be str not int

`print("the furnace is now " + str(temperature) + "degrees!")`

cast it to `str`

### How to change colors of a Drawable in Android?

Short example to change drawable color according to `isWorking` field.

My shape xml:

``````<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@android:color/holo_blue_bright" />
<size
android:height="15dp"
android:width="15dp" />
</shape>
``````

My method to change:

``````private Drawable getColoredDrawable(int drawableResId, boolean isworking) {
Drawable d = getResources().getDrawable(R.drawable.shape);
ColorFilter filter = new LightingColorFilter(
isworking ? Color.GREEN : Color.RED,
isworking ? Color.GREEN : Color.RED);
d.setColorFilter(filter);
return d;
}
``````

Example of usage:

``````text1.setCompoundDrawablesWithIntrinsicBounds(getColoredDrawable(R.drawable.shape, isworking()), null, null, null);
``````

# Vue 2.x

For Official information:

https://vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced

A simple Example:

On any Element you have to add an attribute `ref` with a unique value

``````<input ref="foo" type="text" >
``````

To target that elemet use `this.\$refs.foo`

``````this.\$refs.foo.focus(); // it will focus the input having ref="foo"
``````

### The data-toggle attributes in Twitter Bootstrap

The purpose of data-toggle in bootstrap is so you can use jQuery to find all tags of a certain type. For example, you put data-toggle="popover" in all popover tags and then you can use a JQuery selector to find all those tags and run the popover() function to initialize them. You could just as well put class="myPopover" on the tag and use the .myPopover selector to do the same thing. The documentation is confusing, because it makes it appear that something special is going on with that attribute.

This

``````<div class="container">
<h3>Popover Example</h3>
<a href="#" class="myPop" title="Popover1 Header" data-content="Some content inside the popover1">Toggle popover1</a>
<a href="#" class="myPop" title="Popover2 Header" data-content="Some content inside the popover2">Toggle popover2</a>
</div>

<script>
\$('.myPop').popover();
});
</script>
``````

works just fine.

### How to select following sibling/xml tag using xpath

For completeness - adding to accepted answer above - in case you are interested in any sibling regardless of the element type you can use variation:

`following-sibling::*`

### Swift Beta performance: sorting arrays

The Sort Function Swift’s standard library provides a function called sort, which sorts an array of values of a known type, based on the output of a sorting closure that you provide. Once it completes the sorting process, the sort function returns a new array of the same type and size as the old one, with its elements in the correct sorted order.

The `sort` function has two declarations.

The default declaration which allows you to specify a comparison closure:

``````func sort<T>(array: T[], pred: (T, T) -> Bool) -> T[]
``````

And a second declaration that only take a single parameter (the array) and is "hardcoded to use the less-than comparator."

``````func sort<T : Comparable>(array: T[]) -> T[]

Example:
sort( _arrayToSort_ ) { \$0 > \$1 }
``````

I tested a modified version of your code in a playground with the closure added on so I could monitor the function a little more closely, and I found that with n set to 1000, the closure was being called about 11,000 times.

``````let n = 1000
let x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
x[i] = random()
}
let y = sort(x) { \$0 > \$1 }
``````

It is not an efficient function, an I would recommend using a better sorting function implementation.

EDIT:

I took a look at the Quicksort wikipedia page and wrote a Swift implementation for it. Here is the full program I used (in a playground)

``````import Foundation

func quickSort(inout array: Int[], begin: Int, end: Int) {
if (begin < end) {
let p = partition(&array, begin, end)
quickSort(&array, begin, p - 1)
quickSort(&array, p + 1, end)
}
}

func partition(inout array: Int[], left: Int, right: Int) -> Int {
let numElements = right - left + 1
let pivotIndex = left + numElements / 2
let pivotValue = array[pivotIndex]
swap(&array[pivotIndex], &array[right])
var storeIndex = left
for i in left..right {
let a = 1 // <- Used to see how many comparisons are made
if array[i] <= pivotValue {
swap(&array[i], &array[storeIndex])
storeIndex++
}
}
swap(&array[storeIndex], &array[right]) // Move pivot to its final place
return storeIndex
}

let n = 1000
var x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
x[i] = Int(arc4random())
}

quickSort(&x, 0, x.count - 1) // <- Does the sorting

for i in 0..n {
x[i] // <- Used by the playground to display the results
}
``````

Using this with n=1000, I found that

1. quickSort() got called about 650 times,
3. and there are about 10,000 comparisons

It seems that the built-in sort method is (or is close to) quick sort, and is really slow...

### Checking if an object is a given type in Swift

If you don't know that you will get an array of dictionaries or single dictionary in the response from server you need to check whether the result contains an array or not.
In my case always receiving an array of dictionaries except once. So, to handle that I used the below code for swift 3.

``````if let str = strDict["item"] as? Array<Any>
``````

Here as? Array checks whether the obtained value is array (of dictionary items). In else case you can handle if it is single dictionary item which is not kept inside an array.

### How to remove an iOS app from the App Store

Step 1 :- GO to My Apps App in iTunes Connect

Here you can see your all app which are currently on Appstore.

Step 2 :- Select your app which you want to delete.(click on app-name)

Step 3 :- Select Pricing and Availability Tab.

Step 4 :- Select Remove from sale option.

Step 5 :- Click on save Button.

Now you will see below your app like , Developer Removed it from sale in Red Symbol in place of Green.

Step 6 :- Now again Select your app and Go to App information Tab. you will see Delete App option. (need to scroll bit bottom)

Step 7 :- After clicking on Delete button you will get warning like this ,

Step 8 :- Click on Delete button.

Congratulation , You have Permanently deleted your app successfully from appstore. Now , you cant able to see app on appstore aswellas in your developer account.

Note :-

When you have selected only Remove from sale option you have not deleted app permanently. You can able to make your app live again by clicking on Available in all territories option Again.

### How to dynamically change header based on AngularJS partial view?

You could define controller at the `<html>` level.

`````` <html ng-app="app" ng-controller="titleCtrl">
<title>{{ Page.title() }}</title>
...
``````

You create service: `Page` and modify from controllers.

``````myModule.factory('Page', function() {
var title = 'default';
return {
title: function() { return title; },
setTitle: function(newTitle) { title = newTitle }
};
});
``````

Inject `Page` and Call 'Page.setTitle()' from controllers.

Here is the concrete example: http://plnkr.co/edit/0e7T6l

### Typing the Enter/Return key using Python and Selenium

Try to use an XPath expression for searching the element and then, the following code works:

``````driver.findElement(By.xpath(".//*[@id='txtFilterContentUnit']")).sendKeys(Keys.ENTER);
``````

### How do I determine the size of my array in C?

The best way is you save this information, for example, in a structure:

``````typedef struct {
int *array;
int elements;
} list_s;
``````

Implement all necessary functions such as create, destroy, check equality, and everything else you need. It is easier to pass as a parameter.

### How can I find the first and last date in a month using PHP?

To get the first and last date of `Last Month`;

``````\$dateBegin = strtotime("first day of last month");
\$dateEnd = strtotime("last day of last month");

echo date("D-F-Y", \$dateBegin);
echo "<br>";
echo date("D-F-Y", \$dateEnd);
``````

### In Firebase, is there a way to get the number of children of a node without loading all the node data?

Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).

The 'trick' here is to use the node priority to as the vote count...

The data is:

``````,"vote": {
,".write" : true
,"\$issue" : {
"user" : {
"\$user" : {
".validate" : "!data.exists() &&
newData.val()==data.parent().parent().child('count').getPriority()+1 &&
newData.val()==newData.GetPriority()"
``````

user can only vote once && count must be one higher than current count && data value must be same as priority.

``````      }
}
,"count" : {
".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
newData.getPriority()==data.getPriority()+1 "
}
``````

count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.

``````  }
}
``````

Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.

``````<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
window.fb = new Firebase('https:...vote/iss1/');
window.fb.child('count').once('value', function (dss) {
} );

function vote(dss,count)
{
var user='user/zz' + count; // replace with auth.id or whatever
window.fb.child(user).setWithPriority(count,count);
window.fb.child('count').setWithPriority(user,count);
}
</script>
``````

The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)

The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).

### Convert Go map to json

If you had caught the error, you would have seen this:

``````jsonString, err := json.Marshal(datas)
fmt.Println(err)

// [] json: unsupported type: map[int]main.Foo
``````

The thing is you cannot use integers as keys in JSON; it is forbidden. Instead, you can convert these values to strings beforehand, for instance using `strconv.Itoa`.

See this post for more details: https://stackoverflow.com/a/24284721/2679935

### Inserting line breaks into PDF

The solution I've found was:

``````\$text = 'Line one\n\nLine two');
\$text = explode('\n', \$text);

foreach (\$text as \$txt){
\$pdf->Write(\$txt);
\$pdf->Ln();
}
``````

So this way, you may have any number of \n in any position, if you're getting this text dinamically from the database, it will break lines correctrly.

### how to set the background color of the whole page in css

I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added `background-color:white` to the HTML element. I overwrote that and everything was easy to handle from there.

### 'str' object has no attribute 'decode'. Python 3 error?

Use it by this Method:

``````str.encode().decode()
``````

### How can I change the color of pagination dots of UIPageControl?

It's not possible using the iPhone SDK from an official standpoint. You might be able to do it using private methods, but that will be a barrier to getting onto the app store.

The only other safe solution is to create yout own page control which shpuldnt be too difficult given that the page control simply displays what page is currently shown in a scroll view.

### How do I check in JavaScript if a value exists at a certain array index?

``````if(arrayName.length > index && arrayName[index] !== null) {
//arrayName[index] has a value
}
``````

### Python list directory, subdirectory, and files

Use `os.path.join` to concatenate the directory and file name:

``````for path, subdirs, files in os.walk(root):
for name in files:
print(os.path.join(path, name))
``````

Note the usage of `path` and not `root` in the concatenation, since using `root` would be incorrect.

In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to `os.path.join` would be:

``````pathlib.PurePath(path, name)
``````

The advantage of `pathlib` is that you can use a variety of useful methods on paths. If you use the concrete `Path` variant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.

### Update multiple rows with different values in a single SQL query

Use a comma ","

``````eg:
UPDATE my_table SET rowOneValue = rowOneValue + 1, rowTwoValue  = rowTwoValue + ( (rowTwoValue / (rowTwoValue) ) + ?) * (v + 1) WHERE value = ?
``````

### Flatten List in LINQ

With query syntax:

``````var values =
from inner in outer
from value in inner
select value;
``````

### Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

try

``````var lst= (from char c in source select c.ToString()).ToList();
``````

### How to replace specific values in a oracle database column?

In Oracle, there is the concept of schema name, so try using this

``````update schemname.tablename t
set t.columnname = replace(t.columnname, t.oldvalue, t.newvalue);
``````

### How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

Return a generic 400 status code, and then process that client-side.

Or you can keep the 401, and not return the WWW-Authenticate header, which is really what the browser is responding to with the authentication popup. If the WWW-Authenticate header is missing, then the browser won't prompt for credentials.

### How do I calculate the percentage of a number?

``````\$percentage = 50;
\$totalWidth = 350;

\$new_width = (\$percentage / 100) * \$totalWidth;
``````

### Java random number with given length

``````int rand = (new Random()).getNextInt(900000) + 100000;
``````

EDIT: Fixed off-by-1 error and removed invalid solution.

### How to generate java classes from WSDL file

i founded a great toool to auto parse and connect to web services

http://www.wsdl2code.com

http://www.wsdl2code.com/pages/Example.aspx

`````` SampleService srv1 = new SampleService();
req = new Request();
req.companyId = "1";
Response response =    srv1.ServiceSample(req);
``````

### Combine Points with lines with ggplot2

The following example using the iris dataset works fine:

``````dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
id.vars = "Species")
ggplot(aes(x = 1:nrow(iris), y = value, color = variable), data = dat) +
geom_point() + geom_line()
``````

### Undefined function mysql_connect()

My guess is your PHP installation wasn't compiled with MySQL support.

Check your configure command (`php -i | grep mysql`). You should see something like `'--with-mysql=shared,/usr'`.

You can check for complete instructions at http://php.net/manual/en/mysql.installation.php. Although, I would rather go with the solution proposed by @wanovak.

Still, I think you need MySQL support in order to use PDO.

### Vertical line using XML drawable

``````<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item
android:bottom="-3dp"
android:left="-3dp"
android:top="-3dp">

<shape android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
<stroke
android:width="2dp"
android:color="#1fc78c" />
</shape>

</item>

</layer-list>
``````

### How can I capture the result of var_dump to a string?

Also `echo json_encode(\$dataobject);` might be helpful

### Is it possible to format an HTML tooltip (title attribute)?

Mootools also has a nice 'Tips' class available in their 'more builder'.

### Disable scrolling when touch moving certain element

I found that `ev.stopPropagation();` worked for me.

### Deploying just HTML, CSS webpage to Tomcat

There is no real need to create a war to run it from Tomcat. You can follow these steps

1. Create a folder in webapps folder e.g. MyApp

2. Put your html and css in that folder and name the html file, which you want to be the starting page for your application, index.html

3. Start tomcat and point your browser to url "http://localhost:8080/MyApp". Your index.html page will pop up in the browser

### Convert string to float?

Try this:

``````String numberStr = "3.5";
Float number = null;
try {
number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
System.out.println("numberStr is not a number");
}
``````

### Using %f with strftime() in Python to get microseconds

This should do the work

``````import datetime
datetime.datetime.now().strftime("%H:%M:%S.%f")
``````

It will print

`HH:MM:SS.microseconds` like this e.g `14:38:19.425961`

### pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

Use the valgrind option `--track-origins=yes` to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.

Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:

It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.

From the Valgrind FAQ:

As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.

### How to execute UNION without sorting? (SQL)

I notice this question gets quite a lot of views so I'll first address a question you didn't ask!

Regarding the title. To achieve a "Sql Union All with “distinct”" then simply replace `UNION ALL` with `UNION`. This has the effect of removing duplicates.

For your specific question, given the clarification "The first query should have "priority", so duplicates should be removed from bottom" you can use

``````SELECT col1,
col2,
MIN(grp) AS source_group
FROM   (SELECT 1 AS grp,
col1,
col2
FROM   t1
UNION ALL
SELECT 2 AS grp,
col1,
col2
FROM   t2) AS t
GROUP  BY col1,
col2
ORDER  BY MIN(grp),
col1
``````

### Choosing a jQuery datagrid plugin?

The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.

### How to find and replace with regex in excel

As an alternative to Regex, running:

``````Sub Replacer()
Dim N As Long, i As Long
N = Cells(Rows.Count, "A").End(xlUp).Row

For i = 1 To N
If Left(Cells(i, "A").Value, 9) = "texts are" Then
Cells(i, "A").Value = "texts are replaced"
End If
Next i
End Sub
``````

will produce:

### default select option as blank

For those who are using `<select multiple>` (combobox; no dropdown), this worked for me:

_x000D_
_x000D_
``````<select size=1 disabled multiple>
<option hidden selected></option>
<option>My Option</option>
</select>``````
_x000D_
_x000D_
_x000D_