# Programs & Examples On #Register transfer level

Register-transfer-level (RTL) abstraction is used in hardware description languages like Verilog and VHDL. *Don't use this tag for right-to-left.*

### How do I compare two columns for equality in SQL Server?

Regarding David Elizondo's answer, this can give false positives. It also does not give zeroes where the values don't match.

#### Code

``````DECLARE @t1 TABLE (
ColID   int     IDENTITY,
Col2    int
)

DECLARE @t2 TABLE (
ColID   int     IDENTITY,
Col2    int
)

INSERT INTO @t1 (Col2) VALUES (123)
INSERT INTO @t1 (Col2) VALUES (234)
INSERT INTO @t1 (Col2) VALUES (456)
INSERT INTO @t1 (Col2) VALUES (1)

INSERT INTO @t2 (Col2) VALUES (123)
INSERT INTO @t2 (Col2) VALUES (345)
INSERT INTO @t2 (Col2) VALUES (456)
INSERT INTO @t2 (Col2) VALUES (2)

SELECT
t1.Col2 AS t1Col2,
t2.Col2 AS t2Col2,
ISNULL(NULLIF(t1.Col2, t2.Col2), 1) AS MyDesiredResult
FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID
``````

#### Results

``````     t1Col2      t2Col2 MyDesiredResult
----------- ----------- ---------------
123         123               1
234         345             234 <- Not a zero
456         456               1
1           2               1 <- Not a match
``````

### HashMap get/put complexity

In practice, it is O(1), but this actually is a terrible and mathematically non-sense simplification. The O() notation says how the algorithm behaves when the size of the problem tends to infinity. Hashmap get/put works like an O(1) algorithm for a limited size. The limit is fairly large from the computer memory and from the addressing point of view, but far from infinity.

When one says that hashmap get/put is O(1) it should really say that the time needed for the get/put is more or less constant and does not depend on the number of elements in the hashmap so far as the hashmap can be presented on the actual computing system. If the problem goes beyond that size and we need larger hashmaps then, after a while, certainly the number of the bits describing one element will also increase as we run out of the possible describable different elements. For example, if we used a hashmap to store 32bit numbers and later we increase the problem size so that we will have more than 2^32 bit elements in the hashmap, then the individual elements will be described with more than 32bits.

The number of the bits needed to describe the individual elements is log(N), where N is the maximum number of elements, therefore get and put are really O(log N).

If you compare it with a tree set, which is O(log n) then hash set is O(long(max(n)) and we simply feel that this is O(1), because on a certain implementation max(n) is fixed, does not change (the size of the objects we store measured in bits) and the algorithm calculating the hash code is fast.

Finally, if finding an element in any data structure were O(1) we would create information out of thin air. Having a data structure of n element I can select one element in n different way. With that, I can encode log(n) bit information. If I can encode that in zero bit (that is what O(1) means) then I created an infinitely compressing ZIP algorithm.

### regex string replace

Just change `+` to `-`:

``````str = str.replace(/[^a-z0-9-]/g, "");
``````

1. `[^ ]`: match NOT from the set
2. `[^a-z0-9-]`: match if not `a-z`, `0-9` or `-`
3. `/ /g`: do global match

### C# How to determine if a number is a multiple of another?

followings programs will execute,"one number is multiple of another" in

``````#include<stdio.h>
int main
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0)
printf("this is  multiple number");
else if (b%a==0);
printf("this is multiple number");
else
printf("this is not multiple number");
return 0;
}
``````

### jquery <a> tag click event

That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like `.uid` and grab them via:

``````var uids = \$(".uid").map(function() {
return this.value;
}).get();
``````

EDIT: say your output looks like the following (notice, IDs have changed to classes)

``````<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<input name="uid" type="hidden" value='<?php echo \$row->uid;?>' class="uid">
</fieldset>
``````

You can target the 'uid' relative to the clicked anchor like this:

``````\$("a.aaf").click(function() {
});
``````

Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.

### Python: Removing list element while iterating over list

You can make a generator that returns everything that isn't removed:

``````def newlist(somelist):
for element in somelist:
do_action(element)
if not check(element):
yield element
``````

### Efficient way of having a function only execute once in a loop

Here's an explicit way to code this up, where the state of which functions have been called is kept locally (so global state is avoided). I don't much like the non-explicit forms suggested in other answers: it's too surprising to see f() and for this not to mean that f() gets called.

This works by using dict.pop which looks up a key in a dict, removes the key from the dict, and takes a default value to use in case the key isn't found.

``````def do_nothing(*args, *kwargs):
pass

# A list of all the functions you want to run just once.
actions = [
my_function,
other_function
]
actions = dict((action, action) for action in actions)

while True:
if some_condition:
actions.pop(my_function, do_nothing)()
if some_other_condition:
actions.pop(other_function, do_nothing)()
``````

### Read Excel sheet in Powershell

There is the possibility of making something really more cool!

``````# Powershell
\$xl = new-object -ComObject excell.application
\$doc=\$xl.workbooks.open("Filepath")
\$doc.Sheets.item(1).rows |
% { (\$_.value2 | Select-Object -first 3 | Select-Object -last 2) -join "," }
``````

### ES6 exporting/importing in index file

Too late but I want to share the way that I resolve it.

Having `model` file which has two named export:

``````export { Schema, Model };
``````

and having `controller` file which has the default export:

``````export default Controller;
``````

I exposed in the `index` file in this way:

``````import { Schema, Model } from './model';
import Controller from './controller';

export { Schema, Model, Controller };
``````

and assuming that I want import all of them:

``````import { Schema, Model, Controller } from '../../path/';
``````

### How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

``````t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()
``````

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

``````t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
``````

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

### How to solve a pair of nonlinear equations using Python?

Try this one, I assure you that it will work perfectly.

``````    import scipy.optimize as opt
from numpy import exp
import timeit

st1 = timeit.default_timer()

def f(variables) :
(x,y) = variables

first_eq = x + y**2 -4
second_eq = exp(x) + x*y - 3
return [first_eq, second_eq]

solution = opt.fsolve(f, (0.1,1) )
print(solution)

st2 = timeit.default_timer()
print("RUN TIME : {0}".format(st2-st1))

->

[ 0.62034452  1.83838393]
RUN TIME : 0.0009331008900937708
``````

FYI. as mentioned above, you can also use 'Broyden's approximation' by replacing 'fsolve' with 'broyden1'. It works. I did it.

I don't know exactly how Broyden's approximation works, but it took 0.02 s.

And I recommend you do not use Sympy's functions <- convenient indeed, but in terms of speed, it's quite slow. You will see.

### What exactly is std::atomic?

`std::atomic` exists because many ISAs have direct hardware support for it

What the C++ standard says about `std::atomic` has been analyzed in other answers.

So now let's see what `std::atomic` compiles to to get a different kind of insight.

The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and `std::atomic` basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.

This support allows for faster alternatives to more general methods such as `std::mutex`, which can make more complex multi-instruction sections atomic, at the cost of being slower than `std::atomic` because `std::mutex` it makes `futex` system calls in Linux, which is way slower than the userland instructions emitted by `std::atomic`, see also: Does std::mutex create a fence?

Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.

main.cpp

``````#include <atomic>
#include <iostream>
#include <vector>

size_t niters;

#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif

for (size_t i = 0; i < niters; ++i) {
#if LOCK
__asm__ __volatile__ (
"lock incq %0;"
: "+m" (global),
"+g" (i) // to prevent loop unrolling
:
:
);
#else
__asm__ __volatile__ (
""
: "+g" (i) // to prevent he loop from being optimized to a single add
: "g" (global)
:
);
global++;
#endif
}
}

int main(int argc, char **argv) {
if (argc > 1) {
} else {
}
if (argc > 2) {
niters = std::stoull(argv[2], NULL, 0);
} else {
niters = 10;
}
for (size_t i = 0; i < nthreads; ++i)
for (size_t i = 0; i < nthreads; ++i)
uint64_t expect = nthreads * niters;
std::cout << "expect " << expect << std::endl;
std::cout << "global " << global << std::endl;
}
``````

Compile, run and disassemble:

``````comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out                    \$common
g++ -o main_std_atomic.out -DSTD_ATOMIC \$common
g++ -o main_lock.out       -DLOCK       \$common

./main_fail.out       4 100000
./main_std_atomic.out 4 100000
./main_lock.out       4 100000

gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out
``````

Extremely likely "wrong" race condition output for `main_fail.out`:

``````expect 400000
global 100000
``````

and deterministic "right" output of the others:

``````expect 400000
global 400000
``````

Disassembly of `main_fail.out`:

``````   0x0000000000002780 <+0>:     endbr64
0x0000000000002784 <+4>:     mov    0x29b5(%rip),%rcx        # 0x5140 <niters>
0x000000000000278b <+11>:    test   %rcx,%rcx
0x0000000000002790 <+16>:    mov    0x29a1(%rip),%rdx        # 0x5138 <global>
0x0000000000002797 <+23>:    xor    %eax,%eax
0x0000000000002799 <+25>:    nopl   0x0(%rax)
0x00000000000027a8 <+40>:    cmp    %rcx,%rax
0x00000000000027ad <+45>:    mov    %rdx,0x2984(%rip)        # 0x5138 <global>
0x00000000000027b4 <+52>:    retq
``````

Disassembly of `main_std_atomic.out`:

``````   0x0000000000002780 <+0>:     endbr64
0x0000000000002784 <+4>:     cmpq   \$0x0,0x29b4(%rip)        # 0x5140 <niters>
0x000000000000278e <+14>:    xor    %eax,%eax
0x0000000000002790 <+16>:    lock addq \$0x1,0x299f(%rip)        # 0x5138 <global>
0x000000000000279d <+29>:    cmp    %rax,0x299c(%rip)        # 0x5140 <niters>
0x00000000000027a6 <+38>:    retq
``````

Disassembly of `main_lock.out`:

``````Dump of assembler code for function threadMain():
0x0000000000002780 <+0>:     endbr64
0x0000000000002784 <+4>:     cmpq   \$0x0,0x29b4(%rip)        # 0x5140 <niters>
0x000000000000278e <+14>:    xor    %eax,%eax
0x0000000000002790 <+16>:    lock incq 0x29a0(%rip)        # 0x5138 <global>
0x000000000000279c <+28>:    cmp    %rax,0x299d(%rip)        # 0x5140 <niters>
0x00000000000027a5 <+37>:    retq
``````

Conclusions:

• the non-atomic version saves the global to a register, and increments the register.

Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of `100000`.

• `std::atomic` compiles to `lock addq`. The LOCK prefix makes the following `inc` fetch, modify and update memory atomically.

• our explicit inline assembly LOCK prefix compiles to almost the same thing as `std::atomic`, except that our `inc` is used instead of `add`. Not sure why GCC chose `add`, considering that our INC generated a decoding 1 byte smaller.

ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?

Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.

### pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

I had the same issue with pip 1.5.6.

I just deleted the ~/.pip folder and it worked like a charm.

``````rm -r ~/.pip/
``````

### How do you get a timestamp in JavaScript?

One I haven't seen yet

``````Math.floor(Date.now() / 1000); // current time in seconds
``````

Another one I haven't seen yet is

``````var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();
``````

### Extracting text OpenCV

You can detect text by finding close edge elements (inspired from a LPD):

``````#include "opencv2/opencv.hpp"

std::vector<cv::Rect> detectLetters(cv::Mat img)
{
std::vector<cv::Rect> boundRect;
cv::Mat img_gray, img_sobel, img_threshold, element;
cvtColor(img, img_gray, CV_BGR2GRAY);
cv::Sobel(img_gray, img_sobel, CV_8U, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
cv::threshold(img_sobel, img_threshold, 0, 255, CV_THRESH_OTSU+CV_THRESH_BINARY);
element = getStructuringElement(cv::MORPH_RECT, cv::Size(17, 3) );
cv::morphologyEx(img_threshold, img_threshold, CV_MOP_CLOSE, element); //Does the trick
std::vector< std::vector< cv::Point> > contours;
cv::findContours(img_threshold, contours, 0, 1);
std::vector<std::vector<cv::Point> > contours_poly( contours.size() );
for( int i = 0; i < contours.size(); i++ )
if (contours[i].size()>100)
{
cv::approxPolyDP( cv::Mat(contours[i]), contours_poly[i], 3, true );
cv::Rect appRect( boundingRect( cv::Mat(contours_poly[i]) ));
if (appRect.width>appRect.height)
boundRect.push_back(appRect);
}
return boundRect;
}
``````

Usage:

``````int main(int argc,char** argv)
{
//Detect
std::vector<cv::Rect> letterBBoxes1=detectLetters(img1);
std::vector<cv::Rect> letterBBoxes2=detectLetters(img2);
//Display
for(int i=0; i< letterBBoxes1.size(); i++)
cv::rectangle(img1,letterBBoxes1[i],cv::Scalar(0,255,0),3,8,0);
cv::imwrite( "imgOut1.jpg", img1);
for(int i=0; i< letterBBoxes2.size(); i++)
cv::rectangle(img2,letterBBoxes2[i],cv::Scalar(0,255,0),3,8,0);
cv::imwrite( "imgOut2.jpg", img2);
return 0;
}
``````

Results:

a. element = getStructuringElement(cv::MORPH_RECT, cv::Size(17, 3) );

b. element = getStructuringElement(cv::MORPH_RECT, cv::Size(30, 30) );

Results are similar for the other image mentioned.

When eclipse runs the test case it will look for the file in target/classes not src/test/resources. When the resource is saved eclipse should copy it from src/test/resources to target/classes if it has changed but if for some reason this has not happened then you will get this error. Check that the file exists in target/classes to see if this is the problem.

### Programmatically shut down Spring Boot application

This works, even done is printed.

``````  SpringApplication.run(MyApplication.class, args).close();
System.out.println("done");
``````

So adding `.close()` after `run()`

Explanation:

`public ConfigurableApplicationContext run(String... args)`

Run the Spring application, creating and refreshing a new ApplicationContext. Parameters:

`args` - the application arguments (usually passed from a Java main method)

Returns: a running ApplicationContext

and:

`void close()` Close this application context, releasing all resources and locks that the implementation might hold. This includes destroying all cached singleton beans. Note: Does not invoke close on a parent context; parent contexts have their own, independent lifecycle.

This method can be called multiple times without side effects: Subsequent close calls on an already closed context will be ignored.

So basically, it will not close the parent context, that's why the VM doesn't quit.

### Adb over wireless without usb cable at all for not rooted phones

Had same issue, however I'm using Macbook Pro (2016) which has USB-c only and I forgot my adapter at home.

Since unable to run adb at all on my development machine, I found a different approach.

Connecting phone with USB cable to another computer (in same WiFi) and enable run adb tcpip from there.

Master-machine : computer where development goes on, with only USB-C connectors

Slave-machine: another computer with USB and in same WiFi

#### Steps:

1. Connect the phone to a different computer (slave-machine)
2. Run `adb usb && adb tcpip 5555` from there
3. On master machine

``````deko\$: adb devices
List of devices attached

connected to 10.0.20.153:5555
``````
4. Now Android Studio or Xamarin can install and run app on the phone

Sidenote:

I also tested Bluetooth tethering from the Phone to Master-machine and successfully connected to phone. Both Android Studio and Xamarin worked well, however the upload process, from Xamarin was taking long time. But it works.

### EC2 instance has no public DNS

The change to the DNS Hostnames setting can also be done using the AWS CLI:

``````aws ec2 modify-vpc-attribute --vpc-id \$vpc_id --enable-dns-hostnames '{"Value": true}'
``````

(Where \$vpc_id is the ID of the VPC that your instance is attached to.)

As soon as the VPC is updated the instance will gain a public DNS.

### A keyboard shortcut to comment/uncomment the select text in Android Studio

To comment/uncomment one line, use: Ctrl + /.

To comment/uncomment a block, use: Ctrl + Shift + /.

### Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

I found a working win7 binary here: Unofficial Windows Binaries for Python Extension Packages It's from Christoph Gohlke at UC Irvine. There are binaries for python 2.5, 2.6, 2.7 , 3.1 and 3.2 for both 32bit and 64 bit windows.

There are a whole lot of other compiled packages here, too.

Be sure to uninstall your old PILfirst. If you used easy_install: `easy_install -mnX pil`
And then remove the egg in python/Lib/site-packages

Be sure to remove any other failed attempts. I had moved the _image dll into Python*.*/DLLs and I had to remove it.

### Extract a subset of a dataframe based on a condition involving a field

Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:

``````    bar <- foo[foo[ ,1] == "there", ]
``````

This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).

This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:

``````    foo[foo[ ,c(1:N)], ]
``````

Or specific columns, as you would expect.

``````    foo[foo[ ,c(1,5,9)], ]
``````

### How do you input command line arguments in IntelliJ IDEA?

As @EastOcean said, We can add it by choosing Run/Debug configurations option. In my case, I have to set configuration for junit. So on clicking Edit configurations option, a pop up window is displayed. Then followed the below steps:

1. Click on + icon
2. Choose junit from the list
3. Then we can see Configuration tab in the right hand side
4. Select test kind, in my case Its a Class
5. Next step browse through the location of the class which needs to be executed/run
6. Next to that, choose VM Option, click on expand arrow icons
7. Set required arguments for an example (-Durl="http://test.com/home" -Dsourcename="API" -Dbrowsername="chrome")
8. Set jre path.

Save and run.

Thank you.

### Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

Another way to support Android L is to use custom `lpreview` property for Gradle. For instance:

``````lpreview = hasProperty('lpreview')

apply plugin: 'com.android.application'

android {
compileSdkVersion lpreview ? "android-L" : 19
buildToolsVersion "20.0.0"

productFlavors { lpreview ? lpreview{} : classic{} }

defaultConfig lpreview ? {} : {
minSdkVersion 14
targetSdkVersion 19
}
``````

Now, you can build your app with:

``````./gradlew clean
``````

or

``````./gradlew -Plpreview installLpreviewDebug
``````

This way you can build your app with `lpreview` property for Android L and without it for previous versions.

### jquery can't get data attribute value

Make sure to check if the event related to the button click is not propagating to child elements as an icon tag (`<i class="fa...`) inside the button for example, so this propagation can make you miss the button `\$(this).attr('data-X10')` and hit the icon tag.

``````<button data-x10="C5">
<i class="fa fa-check"></i> Text
</button>

\$('button.toggleStatus').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
\$(event.currentTarget).attr('data-X10');
});
``````

### How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In you app config file change the `url` to `localhost/example/public`

Then when you want to link to something

`<a href="{{ url('page') }}">Some Text</a>`

`<a href="<?php echo url('page') ?>">Some Text</a>`

### Why do Sublime Text 3 Themes not affect the sidebar?

To Sidebar ceased to be white:

2. In sublime 3 preferences -- > > Browse package
3. create a folder called "default theme" and put the downloaded file

if you installed the theme setUI, setUI file.sublime-the theme is looking for the line with comment:

``````"// sidebar || BG of selected files"
``````

and under it a string

``````"layer0. opacity: { "target": 0.0, "speed": 50.0, "interpolation": "smoothstep" }
replaceable target": 0.0 --> target": 1.0
``````

### How does += (plus equal) work?

1. `1 += 2` won't throw an error but you still shouldn't do it. In this statement you are basically saying "set 1 equal to 1 + 2" but 1 is a constant number and not a variable of type `:number` or `:string` so it probably wouldn't do anything. Saying
``````var myVariable = 1
myVariable += 2
console.log(myVariable)
``````
would log `3` to the console, as `x += y` is just short for `x = x + y`
2. ``````var data = [1,2,3,4,5]
var sum
data.forEach(function(value){
sum += value
})
``````
would make `sum` = 15 because:
``````sum += 1 //sum = 1
sum += 2 //sum = 3
sum += 3 //sum = 6
sum += 4 //sum = 10
sum += 5 //sum = 15
``````

### When to use throws in a Java method declaration?

If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.

Typically, if you are not going to do anything with the exception, you should not catch it.

The most dangerous thing you can do is catch an exception and not do anything with it.

A good discussion of when it is appropriate to throw exceptions is here

When to throw an exception?

### Bringing a subview to be in front of all other views

I had a need for this once. I created a custom `UIView` class - `AlwaysOnTopView`.

``````@interface AlwaysOnTopView : UIView
@end

@implementation AlwaysOnTopView

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == self.superview && [keyPath isEqual:@"subviews.@count"]) {
[self.superview bringSubviewToFront:self];
}

[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
if (self.superview) {
[self.superview removeObserver:self forKeyPath:@"subviews.@count"];
}

[super willMoveToSuperview:newSuperview];
}

- (void)didMoveToSuperview {
[super didMoveToSuperview];

if (self.superview) {
}
}

@end
``````

Have your view extend this class. Of course this only ensures a subview is above all of its sibling views.

### find -mtime files older than 1 hour

What about `-mmin`?

``````find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
-exec rm -f {} \;
``````

From man find:

```-mmin n
```

Also, make sure to test this first!

```... -exec echo rm -f '{}' \;
^^^^ Add the 'echo' so you just see the commands that are going to get
run instead of actual trying them first.
```

### Java: How to convert List to Map

A Java 8 example to convert a `List<?>` of objects into a `Map<k, v>`:

``````List<Hosting> list = new ArrayList<>();

//example 1
Map<Integer, String> result1 = list.stream().collect(
Collectors.toMap(Hosting::getId, Hosting::getName));

System.out.println("Result 1 : " + result1);

//example 2
Map<Integer, String> result2 = list.stream().collect(
Collectors.toMap(x -> x.getId(), x -> x.getName()));
``````

Code copied from:
https://www.mkyong.com/java8/java-8-convert-list-to-map/

### What is the fastest way to transpose a matrix in C++?

Modern linear algebra libraries include optimized versions of the most common operations. Many of them include dynamic CPU dispatch, which chooses the best implementation for the hardware at program execution time (without compromising on portability).

This is commonly a better alternative to performing manual optimization of your functinos via vector extensions intrinsic functions. The latter will tie your implementation to a particular hardware vendor and model: if you decide to swap to a different vendor (e.g. Power, ARM) or to a newer vector extensions (e.g. AVX512), you will need to re-implement it again to get the most of them.

MKL transposition, for example, includes the BLAS extensions function `imatcopy`. You can find it in other implementations such as OpenBLAS as well:

``````#include <mkl.h>

void transpose( float* a, int n, int m ) {
const char row_major = 'R';
const char transpose = 'T';
const float alpha = 1.0f;
mkl_simatcopy (row_major, transpose, n, m, alpha, a, n, n);
}
``````

For a C++ project, you can make use of the Armadillo C++:

``````#include <armadillo>

void transpose( arma::mat &matrix ) {
arma::inplace_trans(matrix);
}
``````

### How to request Administrator access inside a batch file

``````@echo off
Net session >nul 2>&1 || (PowerShell start -verb runas '%~0' &exit /b)
Echo Administrative privileges have been got. & pause
``````

The above works on my Windows 10 Version 1903

### Git push error '[remote rejected] master -> master (branch is currently checked out)'

For me working solution is:

ON REMOTE:

``````git checkout -b some_tmp_name
``````

ON LOCAL:

``````git push
``````

ON REMOTE:

``````git checkout master
git branch -d some_tmp_name
``````

But this is not the real solution it's just workaround.

### Get list of all input objects using JavaScript, without accessing a form object

querySelectorAll returns a NodeList which has its own forEach method:

``````document.querySelectorAll('input').forEach( input => {
// ...
});
``````

getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:

``````Array.from(document.getElementsByTagName('input')).forEach( input => {
// ...
});
``````

### Raise error in a Bash script

I often find it useful to write a function to handle error messages so the code is cleaner overall.

``````# Usage: die [exit_code] [error message]
die() {
local code=\$? now=\$(date +%T.%N)
if [ "\$1" -ge 0 ] 2>/dev/null; then  # assume \$1 is an error code if numeric
code="\$1"
shift
fi
echo "\$0: ERROR at \${now%???}\${1:+: \$*}" >&2
exit \$code
}
``````

This takes the error code from the previous command and uses it as the default error code when exiting the whole script. It also notes the time, with microseconds where supported (GNU date's `%N` is nanoseconds, which we truncate to microseconds later).

If the first option is zero or a positive integer, it becomes the exit code and we remove it from the list of options. We then report the message to standard error, with the name of the script, the word "ERROR", and the time (we use parameter expansion to truncate nanoseconds to microseconds, or for non-GNU times, to truncate e.g. `12:34:56.%N` to `12:34:56`). A colon and space are added after the word ERROR, but only when there is a provided error message. Finally, we exit the script using the previously determined exit code, triggering any traps as normal.

Some examples (assume the code lives in `script.sh`):

``````if [ condition ]; then die 123 "condition not met"; fi
# exit code 123, message "script.sh: ERROR at 14:58:01.234564: condition not met"

\$command |grep -q condition || die 1 "'\$command' lacked 'condition'"
# exit code 1, "script.sh: ERROR at 14:58:55.825626: 'foo' lacked 'condition'"

\$command || die
# exit code comes from command's, message "script.sh: ERROR at 14:59:15.575089"
``````

### How do we use runOnUiThread in Android?

You have it back-to-front. Your button click results in a call to `runOnUiThread()`, but this isn't needed, since the click handler is already running on the UI thread. Then, your code in `runOnUiThread()` is launching a new background thread, where you try to do UI operations, which then fail.

Instead, just launch the background thread directly from your click handler. Then, wrap the calls to `btn.setText()` inside a call to `runOnUiThread()`.

### SQL Server : How to test if a string has only digit characters

Method that will work. The way it is used above will not work.

``````declare @str varchar(50)='79136'

select
case
when  @str LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end

declare @str2 varchar(50)='79D136'

select
case
when  @str2 LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
``````

### How to convert java.sql.timestamp to LocalDate (java8) java.time?

I'll slightly expand @assylias answer to take time zone into account. There are at least two ways to get LocalDateTime for specific time zone.

You can use setDefault time zone for whole application. It should be called before any timestamp -> java.time conversion:

``````public static void main(String... args) {
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(utcTimeZone);
...
timestamp.toLocalDateTime().toLocalDate();
}
``````

Or you can use toInstant.atZone chain:

``````timestamp.toInstant()
.atZone(ZoneId.of("UTC"))
.toLocalDate();
``````

### Spring Boot without the web server

``````spring.main.web-application-type=none
``````

### When should you NOT use a Rules Engine?

I would strongly recommend business rules engines like Drools as open source or Commercial Rules Engine such as LiveRules.

• When you have a lot of business policies which are volatile in nature, it is very hard to maintain that part of the core technology code.
• The rules engine provides a great flexibility of the framework and easy to change and deploy.
• Rules engines are not to be used everywhere but need to used when you have lot of policies where changes are inevitable on a regular basis.

### How to prevent rm from reporting that a file was not found?

Yes, `-f` is the most suitable option for this.

### Why is @font-face throwing a 404 error on woff files?

This might be obvious, but it has tripped me up with 404s a number of times... Make sure the fonts folder permissions are set correctly.

### List of lists into numpy array

``````>>> numpy.array([[1, 2], [3, 4]])
array([[1, 2], [3, 4]])
``````

### How to find item with max value using linq?

With EF or LINQ to SQL:

``````var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
``````

With LINQ to Objects I suggest to use morelinq extension `MaxBy` (get morelinq from nuget):

``````var item = items.MaxBy(i => i.Value);
``````

### RegEx for validating an integer with a maximum length of 10 characters

In most languages i am aware of, the actual regex for validating should be `^[0-9]{1,10}\$`; otherwise the matcher will also return positive matches if the to be validated number is part of a longer string.

### Deserializing JSON array into strongly typed .NET object

I like this approach, it is visual for me.

``````using (var webClient = new WebClient())
{
JObject result = JObject.Parse(response);
var users = result.SelectToken("data");
List<User> userList = JsonConvert.DeserializeObject<List<User>>(users.ToString());
}
``````

### What is the perfect counterpart in Python for "while not EOF"

You can use the following code snippet. readlines() reads in the whole file at once and splits it by line.

``````line = obj.readlines()
``````

### Java - escape string to prevent SQL injection

Prepared Statements are the best solution, but if you really need to do it manually you could also use the `StringEscapeUtils` class from the Apache Commons-Lang library. It has an `escapeSql(String)` method, which you can use:

```import org.apache.commons.lang.StringEscapeUtils; … String escapedSQL = StringEscapeUtils.escapeSql(unescapedSQL); ```

### How do I convert a float to an int in Objective C?

I'm pretty sure C-style casting syntax works in Objective C, so try that, too:

``````int myInt = (int) myFloat;
``````

It might silence a compiler warning, at least.

### How to kill zombie process

A zombie is already dead, so you cannot kill it. To clean up a zombie, it must be waited on by its parent, so killing the parent should work to eliminate the zombie. (After the parent dies, the zombie will be inherited by pid 1, which will wait on it and clear its entry in the process table.) If your daemon is spawning children that become zombies, you have a bug. Your daemon should notice when its children die and `wait` on them to determine their exit status.

An example of how you might send a signal to every process that is the parent of a zombie (note that this is extremely crude and might kill processes that you do not intend. I do not recommend using this sort of sledge hammer):

``````# Don't do this.  Incredibly risky sledge hammer!
kill \$(ps -A -ostat,ppid | awk '/[zZ]/ && !a[\$2]++ {print \$2}')
``````

### Pointer vs. Reference

Pointers:

• Can be assigned `nullptr` (or `NULL`).
• At the call site, you must use `&` if your type is not a pointer itself, making explicitly you are modifying your object.
• Pointers can be rebound.

References:

• Cannot be null.
• Once bound, cannot change.
• Callers don't need to explicitly use `&`. This is considered sometimes bad because you must go to the implementation of the function to see if your parameter is modified.

### Logging POST data from \$request_body

I had a similar problem. GET requests worked and their (empty) request bodies got written to the the log file. POST requests failed with a 404. Experimenting a bit, I found that all POST requests were failing. I found a forum posting asking about POST requests and the solution there worked for me. That solution? Add a `proxy_header` line right before the `proxy_pass` line, exactly like the one in the example below.

``````server {
listen       192.168.0.1:45080;
server_name  foo.example.org;

access_log  /path/to/log/nginx/post_bodies.log post_bodies;
location / {
proxy_pass   http://10.1.2.3;
}
}
``````

(This is with nginx 1.2.1 for what it is worth.)

### Use "ENTER" key on softkeyboard instead of clicking button

To avoid the focus advancing to the next editable field (if you have one) you might want to ignore the key-down events, but handle key-up events. I also prefer to filter first on the keyCode, assuming that it would be marginally more efficient. By the way, remember that returning true means that you have handled the event, so no other listener will. Anyway, here is my version.

``````ETFind.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
|| keyCode ==  KeyEvent.KEYCODE_ENTER) {

if (event.getAction() == KeyEvent.ACTION_DOWN) {
// do nothing yet
} else if (event.getAction() == KeyEvent.ACTION_UP) {
findForward();
} // is there any other option here?...

// Regardless of what we did above,
// we do not want to propagate the Enter key up
// since it was our task to handle it.
return true;

} else {
// it is not an Enter key - let others handle the event
return false;
}
}

});
``````

### Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

``````client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);
``````

### Removing first x characters from string?

``````>>> text = 'lipsum'
>>> text[3:]
'sum'
``````

See the official documentation on strings for more information and this SO answer for a concise summary of the notation.

### How can I read large text files in Python, line by line, without loading it into memory?

The blaze project has come a long way over the last 6 years. It has a simple API covering a useful subset of pandas features.

dask.dataframe takes care of chunking internally, supports many parallelisable operations and allows you to export slices back to pandas easily for in-memory operations.

``````import dask.dataframe as dd

df.head(10)  # return first 10 rows
df.tail(10)  # return last 10 rows

# iterate rows
for idx, row in df.iterrows():
...

# group by my_field and return mean
df.groupby(df.my_field).value.mean().compute()

# slice by column
df[df.my_field=='XYZ'].compute()
``````

### How to load/reference a file as a File instance from the classpath

Try getting hold of a URL for your classpath resource:

``````URL url = this.getClass().getResource("/com/path/to/file.txt")
``````

Then create a file using the constructor that accepts a URI:

``````File file = new File(url.toURI());
``````

### Find out who is locking a file on a network share

sounds like you have the same problem i tried to solve here. in my case, it's a Linux fileserver (running samba, of course), so i can log in and see what process is locking the file; unfortunately, i haven't found how to close it without killing the responsible session. AFAICT, the windows client 'thinks' it's closed; but didn't bother telling the fileserver.

### anaconda - graphviz - can't import after installation

You can actually install both packages at the same time. For me:

``````conda install -c anaconda graphviz python-graphviz
``````

did the trick.

### How do I load a file into the python console?

For Python 2 give `execfile` a try. (See other answers for Python 3)

``````execfile('file.py')
``````

Example usage:
Let's use "copy con" to quickly create a small script file...

``````C:\junk>copy con execfile_example.py
a = [9, 42, 888]
b = len(a)
^Z
1 file(s) copied.
``````

...and then let's load this script like so:

``````C:\junk>\python27\python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
>>> execfile('execfile_example.py')
>>> a
[9, 42, 888]
>>> b
3
>>>
``````

### Binning column with python pandas

You can use `pandas.cut`:

``````bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]
``````

``````bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5
``````
``````bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5
``````

...and then `value_counts` or `groupby` and aggregate `size`:

``````s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64
``````

``````s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64
``````

By default `cut` return `categorical`.

`Series` methods like `Series.value_counts()` will use all categories, even if some categories are not present in the data, operations in categorical.

### shorthand If Statements: C#

To use shorthand to get the direction:

``````int direction = column == 0
? 0
: (column == _gridSize - 1 ? 1 : rand.Next(2));
``````

To simplify the code entirely:

``````if (column == gridSize - 1 || rand.Next(2) == 1)
{
}
else
{
}
``````

### Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

``````((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE
``````

The longer form evaluates left to right examining only the first element of each vector, so the above gives

``````((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE
``````

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use `all` and `any` to reduce it to length one for use in control flow statements, like `if`.

The functions `all` and `any` are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in `ifelse`.

One final difference: the `&&` and `||` only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value `a`; if it didn't short-circuit, as `&` and `|` don't, it would give an error.

``````a
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
FALSE & a
``````

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

### Transferring files over SSH

If copying to/from your desktop machine, use WinSCP, or if on Linux, Nautilus supports SCP via the Connect To Server option.

scp can only copy files to a machine running sshd, hence you need to run the client software on the remote machine from the one you are running scp on.

If copying on the command line, use:

``````# copy from local machine to remote machine
scp localfile user@host:/path/to/whereyouwant/thefile
``````

or

``````# copy from remote machine to local machine
scp user@host:/path/to/remotefile localfile
``````

### SQL Query for Selecting Multiple Records

I strongly recommend using lowercase field|column names, it will make your life easier.

Let's assume you have a table called users with the following definition and records:

``````id|firstname|lastname|username             |password
1 |joe      |doe     |[email protected]   |1234
2 |jane     |doe     |[email protected]  |12345
3 |johnny   |doe     |[email protected]|123456
``````

let's say you want to get all records from table users, then you do:

``````SELECT * FROM users;
``````

Now let's assume you want to select all records from table users, but you're interested only in the fields id, firstname and lastname, thus ignoring username and password:

``````SELECT id, firstname, lastname FROM users;
``````

Now we get at the point where you want to retrieve records based on condition(s), what you need to do is to add the WHERE clause, let's say we want to select from users only those that have username = [email protected] and password = 1234, what you do is:

``````SELECT * FROM users
WHERE ( ( username = '[email protected]' ) AND ( password = '1234' ) );
``````

But what if you need only the id of a record with username = [email protected] and password = 1234? then you do:

``````SELECT id FROM users
WHERE ( ( username = '[email protected]' ) AND ( password = '1234' ) );
``````

Now to get to your question, as others before me answered you can use the IN clause:

``````SELECT * FROM users
WHERE ( id IN (1,2,..,n) );
``````

or, if you wish to limit to a list of records between id 20 and id 40, then you can easily write:

``````SELECT * FROM users
WHERE ( ( id >= 20 ) AND ( id <= 40 ) );
``````

I hope this gives a better understanding.

### Make a link open a new window (not tab)

With pure HTML you can't influence this - every modern browser (= the user) has complete control over this behavior because it has been misused a lot in the past...

#### HTML option

You can open a new window (HTML4) or a new browsing context (HTML5). Browsing context in modern browsers is mostly "new tab" instead of "new window". You have no influence on that, and you can't "force" modern browsers to open a new window.

In order to do this, use the anchor element's attribute `target`[1]. The value you are looking for is `_blank`[2].

``````<a href="www.example.com/example.html" target="_blank">link text</a>
``````

#### JavaScript option

Forcing a new window is possible via javascript - see Ievgen's excellent answer below for a javascript solution.

(!) However, be aware, that opening windows via javascript (if not done in the onclick event from an anchor element) are subject to getting blocked by popup blockers!

[1] This attribute dates back to the times when browsers did not have tabs and using framesets was state of the art. In the meantime, the functionality of this attribute has slightly changed (see MDN Docu)

[2] There are some other values which do not make much sense anymore (because they were designed with framesets in mind) like `_parent`, `_self` or `_top`.

### How to print out more than 20 items (documents) in MongoDB's shell?

You can use `it` inside of the shell to iterate over the next 20 results. Just type `it` if you see "has more" and you will see the next 20 items.

### How do you make a HTTP request with C++?

There is a newer, less mature curl wrapper being developed called C++ Requests. Here's a simple GET request:

``````#include <iostream>
#include <cpr.h>

int main(int argc, char** argv) {
auto response = cpr::Get(cpr::Url{"http://httpbin.org/get"});
std::cout << response.text << std::endl;
}
``````

It supports a wide variety of HTTP verbs and curl options. There's more usage documentation here.

Disclaimer: I'm the maintainer of this library.

### batch/bat to copy folder and content at once

For Folder Copy You can Use

``````robocopy C:\Source D:\Destination /E
``````

For File Copy

``````copy D:\Sourcefile.txt D:\backup\Destinationfile.txt /Y
``````

Delete file in some folder last modify date more than some day

``````forfiles -p "D:\FolderPath" -s -m *.[Filetype eg-->.txt] -d -[Numberof dates] -c "cmd /c del @PATH"
``````

And you can Shedule task in windows perform this task automatically in specific time.

### Fail during installation of Pillow (Python module) in Linux

Working successfuly :

`````` sudo apt install libjpeg8-dev zlib1g-dev
``````

### How to import NumPy in the Python shell

On Debian/Ubuntu:

``````aptitude install python-numpy
``````

``````http://sourceforge.net/projects/numpy/files/NumPy/
``````

``````\$ tar xfz numpy-n.m.tar.gz
\$ cd numpy-n.m
\$ python setup.py install
``````

### How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

``````New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"
``````

### ImageMagick security policy 'PDF' blocking conversion

Well, at least in Ubuntu 20.04.2 LTS or maybe in other versions you can't really edit the policy.xml file directly in a GUI way. Here is a terminal way to edit it.

1. Open the policy.xml file in terminal by entering this command -

`sudo nano /etc/ImageMagick-6/policy.xml`

2. Now, directly edit the file in terminal, find `<policy domain="coder" rights="none" pattern="PDF" />` and replace `none` with `read|write` as shown in the picture. Then press Ctrl+X to exit.

### Connect to Active Directory via LDAP

ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.

OU=Your_OU,OU=other_ou,dc=example,dc=com

You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain

Now i miss a parameter to authenticate, this works the same as the path for the username

Introduction to LDAP

### how to rename an index in a cluster?

Just in case someone still needs it. The successful, not official, way to rename indexes are:

1. Close indexes that need to be renamed
2. Rename indexes' folders in all data directories of master and data nodes.
3. Reopen old closed indexes (I use kofp plugin). Old indexes will be reopened but stay unassigned. New indexes will appear in closed state
4. Reopen new indexes
5. Delete old indexes

If you happen to get this error "dangled index directory name is", remove index folder in all master nodes (not data nodes), and restart one of the data nodes.

### How to calculate the difference between two dates using PHP?

You can use the

``````getdate()
``````

function which returns an array containing all elements of the date/time supplied:

``````\$diff = abs(\$endDate - \$startDate);
\$my_t=getdate(\$diff);
print("\$my_t[year] years, \$my_t[month] months and \$my_t[mday] days");
``````

If your start and end dates are in string format then use

``````\$startDate = strtotime(\$startDateStr);
\$endDate = strtotime(\$endDateStr);
``````

before the above code

### Checking Date format from a string in C#

Use an array of valid dates format, check docs:

``````string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);

if(isValidFormat)
{
string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
// maybe throw an Exception
}
``````

### Should I use != or <> for not equal in T-SQL?

I preferred using `!=` instead of `<>` because sometimes I use the `<s></s>` syntax to write SQL commands. Using `!=` is more handy to avoid syntax errors in this case.

### How can I list all collections in the MongoDB shell?

``````> show dbs
local         0.000GB
> show collections
record
``````
• connect with the MongoDB database using `mongo`. This will start the connection.
• then run `show dbs` command. This will show you all exiting/available databases.
• then select the `database` you want. In the above it is `anuradhfirst`. Then run `use anuradhfirst`. This will switch to the database you want.
• then run `show collections` command. This will show all the `collections` inside your selected database.

### Replace an element into a specific position of a vector

You can do that using at. You can try out the following simple example:

``````const size_t N = 20;
std::vector<int> vec(N);
try {
vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);
``````

Notice that method `at` returns an `allocator_type::reference`, which is that case is a `int&`. Using `at` is equivalent to assigning values like `vec[i]=...`.

There is a difference between `at` and insert as it can be understood with the following example:

``````const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
vec[i] = i + 1;
}

vec.insert(vec.begin()+2, 10);
``````

If we now print out `vec` we will get:

``````1 2 10 3 4 5 0 0 0
``````

If, instead, we did `vec.at(2) = 10`, or `vec[2]=10`, we would get

``````1 2 10 4 5 0 0 0
``````

### Splitting a table cell into two columns in HTML

Like this http://jsfiddle.net/8ha9e/1/

Add `colspan="2"` to the 3rd `<th>` and then have 4 `<td>`'s in your second row.

``````<table border="1">
<tr>
</tr>
<tr>
<th scope="row">&nbsp;</th>
<td>&nbsp;</td>
<!-- The following two cells will appear under the same header -->
<td>Col 1</td>
<td>Col 2</td>
</tr>
</table>
``````

### How to import csv file in PHP?

From the PHP manual:

``````<?php
\$row = 1;
if ((\$handle = fopen("test.csv", "r")) !== FALSE) {
while ((\$data = fgetcsv(\$handle, 1000, ",")) !== FALSE) {
\$num = count(\$data);
echo "<p> \$num fields in line \$row: <br /></p>\n";
\$row++;
for (\$c=0; \$c < \$num; \$c++) {
echo \$data[\$c] . "<br />\n";
}
}
fclose(\$handle);
}
?>
``````

### What does "commercial use" exactly mean?

If the usage of something is part of the process of you making money, then it's generally considered a commercial use. If the purpose of the site is to, through some means or another, directly or indirectly, make you money, then it's probably commercial use.

If, on the other hand, something is merely incidental (not part of the process of production/working, but instead simply tacked on to the side), there are potential grounds for it not to be considered commercial use.

### Where can I find a list of escape characters required for my JSON ajax return type?

Take a look at http://json.org/. It claims a bit different list of escaped characters than Chris proposed.

``````\"
\\
\/
\b
\f
\n
\r
\t
\u four-hex-digits
``````

### show/hide html table columns using css

I don't think there is anything you can do to avoid what you are already doing, however, if you are building the table on the client with javascript, you can always add the style rules dynamically, so you can allow for any number of columns without cluttering up your css file with all those rules. See http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript if you don't know how to do this.

Edit: For your "sticky" toggle, you should just append class names rather than replacing them. For instance, you can give it a class name of "hide2 hide3" etc. I don't think you really need the "show" classes, since that would be the default. Libraries like jQuery make this easy, but in the absence, a function like this might help:

``````var modifyClassName = function (elem, add, string) {
var s = (elem.className) ? elem.className : "";
var a = s.split(" ");
for (var i=0; i<a.length; i++) {
if (a[i] == string) {
return;
}
}
s += " " + string;
}
else {
s = "";
for (var i=0; i<a.length; i++) {
if (a[i] != string)
s += a[i] + " ";
}
}
elem.className = s;
}
``````

### Rename a file using Java

Running code is here.

``````private static void renameFile(File fileName) {

FileOutputStream fileOutputStream =null;

String newFileName = "yourNewFileName"

try {
fileOutputStream = new FileOutputStream(newFileName);

String sCurrentLine;

while ((sCurrentLine = br.readLine()) != null) {
fileOutputStream.write(("\n"+sCurrentLine).getBytes());
}

fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
if (br != null)
br.close();

if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
``````

### How can I truncate a datetime in SQL Server?

``````CONVERT(DATE, <yourdatetime>) or CONVERT(DATE, GetDate()) or CONVERT(DATE, CURRENT_TIMESTAMP)
``````

### How to install VS2015 Community Edition offline

You can download the ISO from https://beta.visualstudio.com/downloads/ (even if it has "beta" in the URL you'll have the latest stable version. Currently update 3)

### Display tooltip on Label's hover?

Just set a title on the label:

``````<label for="male" title="Hello This Will Have Some Value">Hello...</label>
``````

Using jQuery:

``````<label for="male" data-title="Language" />
<input type="hidden" name="Language" value="Hello This Will Have Some Value">

\$("label").prop("title", function() {
return \$("input[name='" + \$(this).data("title") + "']").text();
});
``````

If you can use CSS3, you can use the `text-overflow: ellipsis;` to handle the ellipsis for you so all you need to do is copy the text from the label into the title attribute using jQuery:

HTML:

``````<label for="male">Hello This Will Have Some Value</label>
``````

CSS:

``````label {
display: inline-block;
width: 50px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
``````

jQuery:

``````\$("label").prop("title", function() {
return \$(this).text();
});
``````

Example: http://jsfiddle.net/Xm8Xe/

Finally, if you need robust and cross-browser support, you could use the DotDotDot jQuery plugin.

### Change the selected value of a drop-down list with jQuery

Just try with

``````\$("._statusDDL").val("2");
``````

and not with

``````\$("._statusDDL").val(2);
``````

``````\$(function () {
\$(document).on("click","selector",function (e) {

});

});
``````

### How to hide app title in android?

You can do it programatically:

``````import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class ActivityName extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// remove title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
}
``````

Or you can do it via your `AndroidManifest.xml` file:

``````<activity android:name=".ActivityName"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>
``````

Edit: I added some lines so that you can show it in fullscreen, as it seems that's what you want.

### git visual diff between branches

If you use the excellent WebStorm editor, you can compare with any branch you'd like:

### T-SQL: How to Select Values in Value List that are NOT IN the Table?

This Should work with all SQL versions.

``````SELECT  E.AccessCode ,
CASE WHEN C.AccessCode IS NOT NULL THEN 'Exist'
ELSE 'Not Exist'
END AS [Status]
FROM    ( SELECT    '60552' AS AccessCode
UNION ALL
SELECT    '80630'
UNION ALL
SELECT    '1611'
UNION ALL
SELECT    '0000'
) AS E
LEFT OUTER JOIN dbo.Credentials C ON E.AccessCode = c.AccessCode
``````

### HTTP Error 404 when running Tomcat from Eclipse

Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.34\webapps, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like your-eclipse-workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or .../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

### Moment js get first and last day of current month

There would be another way to do this:

``````var begin = moment().format("YYYY-MM-01");
var end = moment().format("YYYY-MM-") + moment().daysInMonth();
``````

### unable to install pg gem

Answered here: Can't install pg gem on Windows

There is no Windows native version of latest release of pg (0.10.0) released yesterday, but if you install 0.9.0 it should install binaries without issues.

### MySQL Insert with While Loop

You cannot use `WHILE` like that; see: mysql DECLARE WHILE outside stored procedure how?

You have to put your code in a stored procedure. Example:

``````CREATE PROCEDURE myproc()
BEGIN
DECLARE i int DEFAULT 237692001;
WHILE i <= 237692004 DO
INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
SET i = i + 1;
END WHILE;
END
``````

Alternatively, generate a list of `INSERT` statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:

``````for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES (\$i, 1, 1);"; done
``````

By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.

### git - remote add origin vs remote set-url origin

Try this:

``````git init
git remote -v
git status
``````

### How to delete the last row of data of a pandas dataframe

For more complex DataFrames that have a Multi-Index (say "Stock" and "Date") and one wants to remove the last row for each Stock not just the last row of the last Stock, then the solution reads:

``````# To remove last n rows
df = df.groupby(level='Stock').apply(lambda x: x.head(-1)).reset_index(0, drop=True)

# To remove first n rows
df = df.groupby(level='Stock').apply(lambda x: x.tail(-1)).reset_index(0, drop=True)
``````

As the `groupby()` is adding an additional level to the Multi-Index we just drop it at the end using `reset_index()`. The resulting df keeps the same type of Multi-Index as before the operation.

### Map vs Object in JavaScript

I don't think the following points have been mentioned in the answers so far, and I thought they'd be worth mentioning.

#### Maps can be bigger

In chrome I can get 16.7 million key/value pairs with `Map` vs. 11.1 million with a regular object. Almost exactly 50% more pairs with a `Map`. They both take up about 2GB of memory before they crash, and so I think may be to do with memory limiting by chrome (Edit: Yep, try filling 2 `Maps` and you only get to 8.3 million pairs each before it crashes). You can test it yourself with this code (run them separately and not at the same time, obviously):

``````var m = new Map();
var i = 0;
while(1) {
m.set(((10**30)*Math.random()).toString(36), ((10**30)*Math.random()).toString(36));
i++;
if(i%1000 === 0) { console.log(i/1000,"thousand") }
}
// versus:
var m = {};
var i = 0;
while(1) {
m[((10**30)*Math.random()).toString(36)] = ((10**30)*Math.random()).toString(36);
i++;
if(i%1000 === 0) { console.log(i/1000,"thousand") }
}
``````

#### Objects have some properties/keys already

This one has tripped me up before. Regular objects have `toString`, `constructor`, `valueOf`, `hasOwnProperty`, `isPrototypeOf` and a bunch of other pre-existing properties. This may not be a big problem for most use cases, but it has caused problems for me before.

#### Maps can be slower:

Due to the `.get` function call overhead and lack of internal optimisation, Map can be considerably slower than a plain old JavaScript object for some tasks.

### How to get share counts using graph API

Check out this gist. It has snippets for how to get the sharing count for the following services:

• Pinterest
• StumbledUpon

I don't like `ActionView` based solutions, my idea is:

1. create a layout with `TextView`, that `TextView` will be populated by application
2. when you need to draw a `MenuItem`:

2.1. inflate layout

2.2. call `measure()` & `layout()` (otherwise `view` will be 0px x 0px, it's too small for most use cases)

2.3. set the `TextView`'s text

2.4. make "screenshot" of the view

2.6. set `MenuItem`'s icon based on bitmap created on 2.4

3. profit!

so, result should be something like

1. create layout here is a simple example
``````<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/counterPanel"
android:layout_width="32dp"
android:layout_height="32dp"
<RelativeLayout
android:id="@+id/counterValuePanel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<ImageView
android:id="@+id/counterBackground"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

<TextView
android:id="@+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textSize="8sp"
android:layout_centerInParent="true"
android:textColor="#FFFFFF" />
</RelativeLayout>
</FrameLayout>
``````

`@drawable/unread_background` is that green `TextView`'s background, `@drawable/ic_menu_gallery` is not really required here, it's just to preview layout's result in IDE.

1. add code into `onCreateOptionsMenu`/`onPrepareOptionsMenu`

``````@Override

return true;
}
``````
2. Implement build-the-icon method:

``````private Drawable buildCounterDrawable(int count, int backgroundImageId) {
LayoutInflater inflater = LayoutInflater.from(this);
view.setBackgroundResource(backgroundImageId);

if (count == 0) {
View counterTextPanel = view.findViewById(R.id.counterValuePanel);
counterTextPanel.setVisibility(View.GONE);
} else {
TextView textView = (TextView) view.findViewById(R.id.count);
textView.setText("" + count);
}

view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);

return new BitmapDrawable(getResources(), bitmap);
}
``````

The complete code is here: https://github.com/cvoronin/ActionBarMenuItemCounter

### Redirecting from HTTP to HTTPS with PHP

This is a good way to do it:

``````<?php
if (!(isset(\$_SERVER['HTTPS']) && (\$_SERVER['HTTPS'] == 'on' ||
\$_SERVER['HTTPS'] == 1) ||
isset(\$_SERVER['HTTP_X_FORWARDED_PROTO']) &&
\$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
\$redirect = 'https://' . \$_SERVER['HTTP_HOST'] . \$_SERVER['REQUEST_URI'];
exit();
}
?>
``````

### Creation timestamp and last update timestamp with Hibernate and MySQL

As data type in JAVA I strongly recommend to use java.util.Date. I ran into pretty nasty timezone problems when using Calendar. See this Thread.

For setting the timestamps I would recommend using either an AOP approach or you could simply use Triggers on the table (actually this is the only thing that I ever find the use of triggers acceptable).

### How to dismiss the dialog with click on outside of the dialog?

Following has worked for me:

``````myDialog.setCanceledOnTouchOutside(true);
``````

### Allow only pdf, doc, docx format for file upload?

For only acept files with extension doc and docx in the explorer window try this

``````    <input type="file" id="docpicker"
accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
``````

### How do I style (css) radio buttons and labels?

For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels

``````input:checked + label {
color: white;
}
``````

MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.

### How do you round a floating point number in Perl?

If you decide to use printf or sprintf, note that they use the Round half to even method.

``````foreach my \$i ( 0.5, 1.5, 2.5, 3.5 ) {
printf "\$i -> %.0f\n", \$i;
}
__END__
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4
``````

### How to adjust gutter in Bootstrap 3 grid system?

You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:

``````.col {
}
``````

EDIT If you only want the spacing between columns you can select all cols except first and last like this..

``````.col:not(:first-child,:last-child) {
}
``````

# Updated Bootply

For Bootstrap 4 see: Remove gutter space for a specific div only

### What's the best way to add a full screen background image in React Native

I solved my background image issue using this code.

``````import React from 'react';
import { StyleSheet, Text, View,Alert,ImageBackground } from 'react-native';

import { TextInput,Button,IconButton,Colors,Avatar } from 'react-native-paper';

class SignInScreen extends React.Component {

state = {
}
render() {
return (
<ImageBackground  source={require('../assets/icons/background3.jpg')} style {styles.backgroundImage}>
<Text>React Native App</Text>
</ImageBackground>
);
}
}

export default SignInScreen;

const styles = StyleSheet.create({
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch'
}
});
``````

### Get DataKey values in GridView RowCommand

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

On the Button:

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

On the Server Event

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

### How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

You are out of luck, I think. THe problem is not a SQL level problem as all other answers seem to focus on, but simply one of the user interface. Management Studio is not meant to be a general purpose / generic data access interface. It is not there to be your interface, but your administrative area, and it has serious limitations handling binary data and large test data - because people using it within the specified usage profile will not run into this problem.

Presenting large text data is simply not the planned usage.

Your only choice would be a table valued function that takes the text input and cuts it rows for every line, so that Management Studio gets a list of rows, not a single row.

### Eclipse error "Could not find or load main class"

Well the following worked for me...

1. Went into the project folder (inside `workspace`)
2. Then, deleted the `bin` folder
3. Then, Cleaned project / projects (in Eclipse)
4. built/run from Eclipse.

### How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

In the earlier versions of MySQL ( < 5.7.5 ) the only way to set

'innodb_buffer_pool_size'

variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :

``````[mysqld]

innodb_buffer_pool_size = 2147483648
``````

You need to restart your mysql server to have it's effect in action.

#### UPDATE :

As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:

``````mysql> SET GLOBAL innodb_buffer_pool_size=402653184;
``````

### How to use underscore.js as a template engine?

I am giving a very simple example

1)

``````var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate);
``````

The result would be

``````Welcome you are at mysite.This has been created by john whose age is 25.
``````

2) This is a template

``````   <script type="text/template" id="template_1">
<% _.each(items,function(item,key,arr) { %>
<li>
<span><%= key %></span>
<span><%= item.name %></span>
<span><%= item.type %></span>
</li>
<% }); %>
</script>
``````

This is html

``````<div>
<ul id="list_2"></ul>
</div>
``````

This is the javascript code which contains json object and putting template into html

``````   var items = [
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
}
];
var template = \$("#template_1").html();
\$("#list_2").html(_.template(template,{items:items}));
});
``````

### 'const int' vs. 'int const' as function parameters in C++ and C

`const int` is identical to `int const`, as is true with all scalar types in C. In general, declaring a scalar function parameter as `const` is not needed, since C's call-by-value semantics mean that any changes to the variable are local to its enclosing function.

### SQL multiple column ordering

``````SELECT  *
FROM    mytable
ORDER BY
column1 DESC, column2 ASC
``````

### Is there a way to return a list of all the image file names from a folder using only Javascript?

Although you can run FTP commands using WebSockets, the simpler solution is listing your files using `opendir` in server side (`PHP`), and "spitting" it into the HTML source-code, so it will be available to client side.

The following code will do just that,

Optionally -

• use `<a>` tag to present a link.
• query for more information using server side (`PHP`),

for example a file size,

PHP filesize TIP:   also you can easily overcome the 2GB limit of PHP's filesize using: AJAX + HEAD request + .htaccess rule to allow `Content-Length` access from client-side.

``````<?php

\$path = 'resources';
\$files = [];
\$handle = @opendir('./' . \$path . '/');

("." !== \$file && ".." !== \$file) && array_push(\$files, \$file);
@closedir(\$handle);
sort(\$files); //uksort(\$files, "strnatcasecmp");

\$files = json_encode(\$files);

unset(\$handle,\$ext,\$file,\$path);
?>
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<body>
<div data-container></div>
<script>
/* you will see (for example): 'var files = ["1.bat","1.exe","1.txt"];' if your folder containes those 1.bat 1.exe 1.txt files, it will be sorted too! :) */

var files = <?php echo \$files; ?>;

files = files.map(function(file){
.replace(/##FILE##/g,       file)
.replace(/##EXT##/g,        file.split('.').slice(-1) )
;
}).join("\n<br/>\n");

document.querySelector('[data-container]').innerHTML = files;
</script>

</body>
</html>
``````

DOM result will look like that:

``````<html lang="en-US" dir="ltr"><head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<body>
<div data-container="">
<br/>
<br/>
<br/>
</div>
<script>
var files = ["1.bat","1.exe","1.txt"];

files = files.map(function(file){
.replace(/##FILE##/g,       file)
.replace(/##EXT##/g,        file.split('.').slice(-1) )
;
}).join("\n<br/>\n");

document.querySelector('[data-container').innerHTML = files;
</script>

</body></html>
``````

### Execution time of C program

You have to take into account that measuring the time that took a program to execute depends a lot on the load that the machine has in that specific moment.

Knowing that, the way of obtain the current time in C can be achieved in different ways, an easier one is:

``````#include <time.h>

#define CPU_TIME (getrusage(RUSAGE_SELF,&ruse), ruse.ru_utime.tv_sec + \
ruse.ru_stime.tv_sec + 1e-6 * \
(ruse.ru_utime.tv_usec + ruse.ru_stime.tv_usec))

int main(void) {
time_t start, end;
double first, second;

// Save user and CPU start time
time(&start);
first = CPU_TIME;

// Perform operations
...

// Save end time
time(&end);
second = CPU_TIME;

printf("cpu  : %.2f secs\n", second - first);
printf("user : %d secs\n", (int)(end - start));
}
``````

Hope it helps.

Regards!

### MySQL FULL JOIN?

Hm, combining LEFT and RIGHT JOIN with UNION could do this:

``````SELECT  p.LastName, p.FirstName, o.OrderNo
FROM    persons AS p
LEFT JOIN
orders AS o
ON      p.P_Id = Orders.P_Id
UNION ALL
SELECT  p.LastName, p.FirstName, o.OrderNo
FROM    persons AS p
RIGHT JOIN
orders AS o
ON      p.P_Id = Orders.P_Id
WHERE   p.P_Id IS NULL
``````

### How can I get an HTTP response body as a string?

Here are two examples from my working project.

1. ``````HttpResponse response = httpClient.execute(new HttpGet(URL));
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
``````
2. ``````HttpResponse response = httpClient.execute(new HttpGet(URL));
String responseString = new BasicResponseHandler().handleResponse(response);
System.out.println(responseString);
``````

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

`````` public class ProgramViwer : Form{
public ProgramViwer()
{
InitializeComponent();
}
private void ProgramViwer_Load(object sender, System.EventArgs e)
{
formPanel.Controls.Clear();
}
}
``````

### Convert Promise to Observable

``````import { from } from 'rxjs';

.subscribe((user: any) => {
console.log('test');
});
``````

Here is a shorter version using a combination of some of the answers above to convert your code from a promise to an observable.

### How to change a PG column to NULLABLE TRUE?

From the fine manual:

``````ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
``````

There's no need to specify the type when you're just changing the nullability.

### Gulp error: The following tasks did not complete: Did you forget to signal async completion?

Basically v3.X was simpler but v4.x is strict in these means of synchronous & asynchronous tasks.

The async/await is pretty simple & helpful way to understand the workflow & issue.

Use this simple approach

``````const gulp = require('gulp')

return console.log('Gulp is running...')
})
``````

### iframe to Only Show a Certain Part of the Page

I got this work good for me.

``````<div style="border: 3px solid rgb(201, 0, 1); overflow: hidden; margin: 15px auto; max-width: 736px;">
<iframe scrolling="no" src="http://www.w3schools.com/css/default.asp" style="border: 0px none; margin-left: -185px; height: 859px; margin-top: -533px; width: 926px;">
</iframe>
</div>
``````

Is this working for you or not let us know.

### change <audio> src with javascript

change this

``````audio.src='audio/ogg/' + document.getElementById(song1.ogg);
``````

to

``````audio.src='audio/ogg/' + document.getElementById('song1');
``````

### Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

One Good solution is to restart the PC, this will make the right entry in the Registry of the PC. Restarting solves my problem

### NoClassDefFoundError for code in an Java library on Android

Just in case it helps someone, I faced the same issue. My jar file was under the libs directory and the jar was added to the build path. Still it was throwing that exception.

I just cleaned the project and it worked for me.

Eclipse -> Project -> Clean -> Select the project and clean

### Use HTML5 to resize an image before upload

Here is what I ended up doing and it worked great.

First I moved the file input outside of the form so that it is not submitted:

``````<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<input id="name" value="#{name}" />
... a few more inputs ...
</form>
``````

Then I changed the `uploadPhotos` function to handle only the resizing:

``````window.uploadPhotos = function(url){
var file = event.target.files[0];

// Ensure it's an image
if(file.type.match(/image.*/)) {

var image = new Image();

// Resize the image
var canvas = document.createElement('canvas'),
max_size = 544,// TODO : pull max size from a site config
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var resizedImage = dataURLToBlob(dataUrl);
\$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl
});
}
}
}
};
``````

As you can see I'm using `canvas.toDataURL('image/jpeg');` to change the resized image into a dataUrl adn then I call the function `dataURLToBlob(dataUrl);` to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:

``````/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];

return new Blob([raw], {type: contentType});
}

var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;

var uInt8Array = new Uint8Array(rawLength);

for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}

return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB      */
``````

Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.

``````/* Handle image resized events */
\$(document).on("imageResized", function (event) {
if (event.blob && event.url) {
data.append('image_data', event.blob);

\$.ajax({
url: event.url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
//handle errors...
}
});
}
});
``````

### SQL Server Management Studio – tips for improving the TSQL coding process

I suggest that you create standards for your SQL scripting and stick to them. Also use templates to quickly create different types of stored procedures and functions. Here is a question about templates in SQL Server 2005 Management Studio

How do you create SQL Server 2005 stored procedure templates in SQL Server 2005 Management Studio?

### Why doesn't Java allow overriding of static methods?

In Java (and many OOP languages, but I cannot speak for all; and some do not have static at all) all methods have a fixed signature - the parameters and types. In a virtual method, the first parameter is implied: a reference to the object itself and when called from within the object, the compiler automatically adds `this`.

There is no difference for static methods - they still have a fixed signature. However, by declaring the method static you have explicitly stated that the compiler must not include the implied object parameter at the beginning of that signature. Therefore, any other code that calls this must must not attempt to put a reference to an object on the stack. If it did do that, then the method execution would not work since the parameters would be in the wrong place - shifted by one - on the stack.

Because of this difference between the two; virtual methods always have a reference to the context object (i.e. `this`) so then it is possible to reference anything within the heap that belong to that instance of the object. But with static methods, since there is no reference passed, that method cannot access any object variables and methods since the context is not known.

If you wish that Java would change the definition so that a object context is passed in for every method, static or virtual, then you would in essence have only virtual methods.

As someone asked in a comment to the op - what is your reason and purpose for wanting this feature?

I do not know Ruby much, as this was mentioned by the OP, I did some research. I see that in Ruby classes are really a special kind of object and one can create (even dynamically) new methods. Classes are full class objects in Ruby, they are not in Java. This is just something you will have to accept when working with Java (or C#). These are not dynamic languages, though C# is adding some forms of dynamic. In reality, Ruby does not have "static" methods as far as I could find - in that case these are methods on the singleton class object. You can then override this singleton with a new class and the methods in the previous class object will call those defined in the new class (correct?). So if you called a method in the context of the original class it still would only execute the original statics, but calling a method in the derived class, would call methods either from the parent or sub-class. Interesting and I can see some value in that. It takes a different thought pattern.

Since you are working in Java, you will need to adjust to that way of doing things. Why they did this? Well, probably to improve performance at the time based on the technology and understanding that was available. Computer languages are constantly evolving. Go back far enough and there is no such thing as OOP. In the future, there will be other new ideas.

EDIT: One other comment. Now that I see the differences and as I Java/C# developer myself, I can understand why the answers you get from Java developers may be confusing if you are coming from a language like Ruby. Java `static` methods are not the same as Ruby `class` methods. Java developers will have a hard time understanding this, as will conversely those who work mostly with a language like Ruby/Smalltalk. I can see how this would also be greatly confusing by the fact that Java also uses "class method" as another way to talk about static methods but this same term is used differently by Ruby. Java does not have Ruby style class methods (sorry); Ruby does not have Java style static methods which are really just old procedural style functions, as found in C.

By the way - thanks for the question! I learned something new for me today about class methods (Ruby style).

### How to format numbers?

Due to the bugs found by JasperV — good points! — I have rewritten my old code. I guess I only ever used this for positive values with two decimal places.

Depending on what you are trying to achieve, you may want rounding or not, so here are two versions split across that divide.

#### First up, with rounding.

I've introduced the `toFixed()` method as it better handles rounding to specific decimal places accurately and is well support. It does slow things down however.

This version still detaches the decimal, but using a different method than before. The `w|0` part removes the decimal. For more information on that, this is a good answer. This then leaves the remaining integer, stores it in `k` and then subtracts it again from the original number, leaving the decimal by itself.

Also, if we're to take negative numbers into account, we need to while loop (skipping three digits) until we hit `b`. This has been calculated to be 1 when dealing with negative numbers to avoid putting something like `-,100.00`

The rest of the loop is the same as before.

``````function formatThousandsWithRounding(n, dp){
var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
s = ''+k, i = s.length, r = '';
while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};
``````

In the snippet below you can edit the numbers to test yourself.

_x000D_
_x000D_
``````function formatThousandsWithRounding(n, dp){_x000D_
var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,_x000D_
u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),_x000D_
s = ''+k, i = s.length, r = '';_x000D_
while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }_x000D_
return s.substr(0, i + 3) + r + (d ? '.'+d: '');_x000D_
};_x000D_
_x000D_
var dp;_x000D_
var createInput = function(v){_x000D_
var inp = jQuery('<input class="input" />').val(v);_x000D_
var eql = jQuery('<span>&nbsp;=&nbsp;</span>');_x000D_
var out = jQuery('<div class="output" />').css('display', 'inline-block');_x000D_
var row = jQuery('<div class="row" />');_x000D_
row.append(inp).append(eql).append(out);_x000D_
inp.keyup(function(){_x000D_
out.text(formatThousandsWithRounding(Number(inp.val()), Number(dp.val())));_x000D_
});_x000D_
inp.keyup();_x000D_
jQuery('body').append(row);_x000D_
return inp;_x000D_
};_x000D_
_x000D_
jQuery(function(){_x000D_
var numbers = [_x000D_
0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999_x000D_
], inputs = \$();_x000D_
dp = jQuery('#dp');_x000D_
for ( var i=0; i<numbers.length; i++ ) {_x000D_
}_x000D_
dp.on('input change', function(){_x000D_
inputs.keyup();_x000D_
});_x000D_
});``````
_x000D_
``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />``````
_x000D_
_x000D_
_x000D_

#### Now the other version, without rounding.

This takes a different route and attempts to avoid mathematical calculation (as this can introduce rounding, or rounding errors). If you don't want rounding, then you are only dealing with things as a string i.e. 1000.999 converted to two decimal places will only ever be 1000.99 and not 1001.00.

This method avoids using `.split()` and `RegExp()` however, both of which are very slow in comparison. And whilst I learned something new from Michael's answer about `toLocaleString`, I also was surprised to learn that it is — by quite a way — the slowest method out of them all (at least in Firefox and Chrome; Mac OSX).

Using `lastIndexOf()` we find the possibly existent decimal point, and from there everything else is pretty much the same. Save for the padding with extra 0s where needed. This code is limited to 5 decimal places. Out of my test this was the faster method.

``````var formatThousandsNoRounding = function(n, dp){
var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
i = s.lastIndexOf('.'), j = i == -1 ? l : i,
r = e, d = s.substr(j+1, dp);
while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
return s.substr(0, j + 3) + r +
(dp ? '.' + d + ( d.length < dp ?
('00000').substr(0, dp - d.length):e):e);
};
``````

_x000D_
_x000D_
``````var formatThousandsNoRounding = function(n, dp){_x000D_
var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,_x000D_
i = s.lastIndexOf('.'), j = i == -1 ? l : i,_x000D_
r = e, d = s.substr(j+1, dp);_x000D_
while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }_x000D_
return s.substr(0, j + 3) + r + _x000D_
(dp ? '.' + d + ( d.length < dp ? _x000D_
('00000').substr(0, dp - d.length):e):e);_x000D_
};_x000D_
_x000D_
var dp;_x000D_
var createInput = function(v){_x000D_
var inp = jQuery('<input class="input" />').val(v);_x000D_
var eql = jQuery('<span>&nbsp;=&nbsp;</span>');_x000D_
var out = jQuery('<div class="output" />').css('display', 'inline-block');_x000D_
var row = jQuery('<div class="row" />');_x000D_
row.append(inp).append(eql).append(out);_x000D_
inp.keyup(function(){_x000D_
out.text(formatThousandsNoRounding(Number(inp.val()), Number(dp.val())));_x000D_
});_x000D_
inp.keyup();_x000D_
jQuery('body').append(row);_x000D_
return inp;_x000D_
};_x000D_
_x000D_
jQuery(function(){_x000D_
var numbers = [_x000D_
0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999_x000D_
], inputs = \$();_x000D_
dp = jQuery('#dp');_x000D_
for ( var i=0; i<numbers.length; i++ ) {_x000D_
}_x000D_
dp.on('input change', function(){_x000D_
inputs.keyup();_x000D_
});_x000D_
});``````
_x000D_
``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />``````
_x000D_
_x000D_
_x000D_

I'll update with an in-page snippet demo shortly, but for now here is a fiddle:

https://jsfiddle.net/bv2ort0a/2/

#### Old Method

Why use RegExp for this? — don't use a hammer when a toothpick will do i.e. use string manipulation:

``````var formatThousands = function(n, dp){
var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r +
(d ? '.' + Math.round(d * Math.pow(10, dp || 2)) : '');
};
``````

#### walk through

``````formatThousands( 1000000.42 );
``````

First strip off decimal:

``````s = '1000000', d = ~ 0.42
``````

Work backwards from the end of the string:

``````',' + '000'
',' + '000' + ',000'
``````

Finalise by adding the leftover prefix and the decimal suffix (with rounding to `dp` no. decimal points):

``````'1' + ',000,000' + '.42'
``````

#### fiddlesticks

http://jsfiddle.net/XC3sS/

### Select all 'tr' except the first one

ideal solution but not supported in IE

``````tr:not(:first-child) {css}
``````

second solution would be to style all tr's and then override with css for first-child:

``````tr {css}
tr:first-child {override css above}
``````

### Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

This is the solution according to the VS code debugging page. This worked for my setup on Windows 10.

``````"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "\${file}"
}
``````

The solution is here:

https://code.visualstudio.com/docs/editor/debugging

Here is the launch configuration generated for Node.js debugging

### An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

Enable this option in VS: Just My Code option

Tools -> Options -> Debugging -> General -> Enable Just My Code (Managed only)

### what is the use of "response.setContentType("text/html")" in servlet

You have to tell the browser what you are sending back so that the browser can take appropriate action like launching a PDF viewer if its a PDF that is being received or launching a video player to play video file ,rendering the HTML if the content type is simple html response, save the bytes of the response as a downloaded file, etc.

some common MIME types are text/html,application/pdf,video/quicktime,application/java,image/jpeg,application/jar etc

In your case since you are sending HTML response to client you will have to set the content type as text/html

### Changing capitalization of filenames in Git

You can open the ".git" directory and then edit the "config" file. Under "[core]" set, set "ignorecase = true" and you are done ;)

### python pip: force install ignoring dependencies

pip has a `--no-dependencies` switch. You should use that.

For more information, run `pip install -h`, where you'll see this line:

``````--no-deps, --no-dependencies
Ignore package dependencies
``````

### Eclipse - Unable to install breakpoint due to missing line number attributes

I found yet another reason for this message. I was programming Scala. The solution was:

1. Open Run -> Debug configurations
2. In the Main tab, on the bottom, beside the "Apply" and "Revert" buttons, there is a text saying which Launcher you are using, and beside it, there is a hyperlink saying "Select other". It is a strange UI element, doesn't look actionable at first glance.
3. Use the "Select other" link and choose "Scala Application (new debugger) Launcher". The other one doesn't seem to work with Scala.

Now the debugging should work. Notice that I have installed the Scala IDE plugin, this option may not be available if you don't have it.

### Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

### How do I trigger a macro to run after a new mail is received in Outlook?

This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.

``````Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)

On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
``````

After pasting the code in `ThisOutlookSession` module, you must restart Outlook.

### Multiple bluetooth connection

Have you looked into the `BluetoothAdapter` Android class? You set up one device as a server and the other as a client. It may be possible (although I haven't looked into it myself) to connect multiple clients to the server.

I have had success connecting a BlueTooth audio device to a phone while it also had this `BluetoothAdapter` connection to another phone, but I haven't tried with three phones. At least this tells me that the Bluetooth radio can tolerate multiple simultaneous connections :)

### Count frequency of words in a list and sort by frequency

You can use reduce() - A functional way.

``````words = "apple banana apple strawberry banana lemon"
reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {})
``````

returns:

``````{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2}
``````

### SQL Server: converting UniqueIdentifier to string in a case statement

I think I found the answer:

``````convert(nvarchar(50), RequestID)
``````

Here's the link where I found this info:

http://msdn.microsoft.com/en-us/library/ms187928.aspx

### Angular 2 'component' is not a known element

I had a similar issue. It turned out that `ng generate component` (using CLI version 7.1.4) adds a declaration for the child component to the AppModule, but not to the TestBed module that emulates it.

The "Tour of Heroes" sample app contains a `HeroesComponent` with selector `app-heroes`. The app ran fine when served, but `ng test` produced this error message: `'app-heroes' is not a known element`. Adding the `HeroesComponent` manually to the declarations in `configureTestingModule` (in `app.component.spec.ts`) eliminates this error.

``````describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
HeroesComponent
],
}).compileComponents();
}));

it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
}
``````

### How do I give text or an image a transparent background using CSS?

This gives the desired result -

``````body {
background-image: url("\images\dark-cloud.jpg");
background-size: 100% 100%;
background-attachment: fixed;
opacity: .8;
}
``````

Setting the opacity of the background.

### Stop absolutely positioned div from overlapping text

Thank you for all your answers, Whilst all were correct, none actually solved my problem. The solution for me was to create a second invisible div at the end of the content of unknown length, this invisible div is the same size as my absolutely positioned div, this ensures that there is always a space at the end of my content for the absolutely positioned div.

This answer was previously provided here: Prevent absolutely-positioned elements from overlapping with text However I didn't see (until now) how to apply it to a bottom right positioned div.

New structure is as follows:

_x000D_
_x000D_
``````<div id="outer" style="position: relative; width:450px; background-color:yellow;">
<p>Content of unknown length</p>
<div>Content of unknown height </div>
<div id="spacer" style="width: 200px; height: 25px; margin-right:0px;"></div>
<div style="position: absolute; right: 0; bottom: 0px; width: 200px; height: 20px; background-color:red;">bottom right</div>
</div>``````
_x000D_
_x000D_
_x000D_

This seems to solve the issue.

### How to extract img src, title and alt from html using php?

If it's XHTML, your example is, you need only simpleXML.

``````<?php
\$input = '<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny"/>';
var_dump(\$sx);
?>
``````

Output:

``````object(SimpleXMLElement)#1 (1) {
["@attributes"]=>
array(3) {
["src"]=>
string(22) "/image/fluffybunny.jpg"
["title"]=>
string(16) "Harvey the bunny"
["alt"]=>
string(26) "a cute little fluffy bunny"
}
}
``````

### How do I go about adding an image into a java project with eclipse?

It is very simple to adding an image into project and view the image. First create a folder into in your project which can contain any type of images.

Then Right click on Project `->>`Go to Build Path `->>` configure Build Path `->>` add Class folder `->>` choose your folder (which you just created for store the images) under the project name.

``````class Surface extends JPanel {

private BufferedImage slate;
private BufferedImage java;
private BufferedImage pane;
private TexturePaint slatetp;
private TexturePaint javatp;
private TexturePaint panetp;

public Surface() {

}

try {

} catch (IOException ex) {

Logger.`enter code here`getLogger(Surface.class.getName()).log(
Level.SEVERE, null, ex);
}
}

private void doDrawing(Graphics g) {

Graphics2D g2d = (Graphics2D) g.create();

slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));
javatp = new TexturePaint(java, new Rectangle(0, 0, 90, 60));
panetp = new TexturePaint(pane, new Rectangle(0, 0, 90, 60));

g2d.setPaint(slatetp);
g2d.fillRect(10, 15, 90, 60);

g2d.setPaint(javatp);
g2d.fillRect(130, 15, 90, 60);

g2d.setPaint(panetp);
g2d.fillRect(250, 15, 90, 60);

g2d.dispose();
}

@Override
public void paintComponent(Graphics g) {

super.paintComponent(g);
doDrawing(g);
}
}

public class TexturesEx extends JFrame {

public TexturesEx() {

initUI();
}

private void initUI() {

setTitle("Textures");
setSize(360, 120);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
TexturesEx ex = new TexturesEx();
ex.setVisible(true);
}
});
}
}
``````

### load Js file in HTML

I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:

``````const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))
``````

### How to split large text file in windows?

you can split using a third party software http://www.hjsplit.org/, for example give yours input that could be upto 9GB and then split, in my case I split 10 MB each

### How to execute cmd commands via Java

This because every `runtime.exec(..)` returns a `Process` class that should be used after the execution instead that invoking other commands by the `Runtime` class

If you look at Process doc you will see that you can use

• `getInputStream()`
• `getOutputStream()`

on which you should work by sending the successive commands and retrieving the output..

### SQL query, if value is null then return 1

``````SELECT orderhed.ordernum, orderhed.orderdate, currrate.currencycode,

case(currrate.currentrate) when null then 1 else currrate.currentrate end

FROM orderhed LEFT OUTER JOIN currrate ON orderhed.company = currrate.company AND orderhed.orderdate = currrate.effectivedate
``````

### init-param and context-param

`<init-param>` and `<context-param>` are static parameters which are stored in web.xml file. If you have any data which doesn't change frequently you can store it in one of them.

If you want to store particular data which is confined to a particular servlet scope, then you can use `<init-param>` .Anything you declare inside `<init-param>` is only accessible only for that particular servlet.The init-param is declared inside the `<servlet>` tag.

``````<servlet>
<display-name>HelloWorldServlet</display-name>
<servlet-name>HelloWorldServlet</servlet-name>
<init-param>
<param-name>Greetings</param-name>
<param-value>Hello</param-value>
</init-param>
</servlet>
``````

and you can access those parameters in the servlet as follows:

``````out.println(getInitParameter("Greetings"));
``````

If you want to store data which is common for whole application and if it doesn't change frequently you can use `<context-param>` instead of `servletContext.setAttribute()` method of the application context. For more information regarding usage of `<context-param>` VS `ServletContext.setAttribute()` have a look at this question. context-param are declared under the tag `web-app`. You can declare and access the `<context-param>` as follows

``````<web-app>
<context-param>
<param-name>Country</param-name>
<param-value>India</param-value>
</context-param>
<context-param>
<param-name>Age</param-name>
<param-value>24</param-value>
</context-param>
</web-app>
``````

Usage in the application either in a JSP or Servlet

``````getServletContext().getInitParameter("Country");
getServletContext().getInitParameter("Age");
``````

### m2e error in MavenArchiver.getManifest()

I solved this error in pom.xml by adding the below code

spring-rest-demo org.apache.maven.plugins maven-war-plugin 2.6

### Getting activity from context in android

``````public Activity getActivityByContext(Context context){

if(context == null){
return null;
}

else if((context instanceof ContextWrapper) && (context instanceof Activity)){
return (Activity) context;
}

else if(context instanceof ContextWrapper){
return getActivity(((ContextWrapper) context).getBaseContext());
}

return null;

}
``````

I hope this helps.. Merry coding!

### Creating a procedure in mySql with parameters

``````(IN @brugernavn varchar(64)**)**,IN @password varchar(64))
``````

The problem is the `)`

### How do I make a dictionary with multiple keys to one value?

Your example creates multiple key: value pairs if using `fromkeys`. If you don't want this, you can use one key and create an alias for the key. For example if you are using a register map, your key can be the register address and the alias can be register name. That way you can perform read/write operations on the correct register.

``````>>> mydict = {}
>>> mydict[(1,2)] = [30, 20]
>>> alias1 = (1,2)
>>> print mydict[alias1]
[30, 20]
>>> mydict[(1,3)] = [30, 30]
>>> print mydict
{(1, 2): [30, 20], (1, 3): [30, 30]}
>>> alias1 in mydict
True
``````

### Flexbox: center horizontally and vertically

``````.container {
display: flex;
justify-content: center;
align-items: center;
}
``````

to the container element of whatever you want to center. Documentation: justify-content and align-items.

### How to center Font Awesome icons horizontally?

i solved my problem with this:

``````<div class="d-flex justify-content-center"></div>
``````

im using bootstrap with font awesome icons.

if you want to know more acess the link below: https://getbootstrap.com/docs/4.0/utilities/flex/

### An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

Adding `<validation validateIntegratedModeConfiguration="false"/>` addresses the symptom, but is not appropriate for all circumstances. Having ran around this issue a few times, I hope to help others not only overcome the problem but understand it. (Which becomes more and more important as IIS 6 fades into myth and rumor.)

Background:

This issue and the confusion surrounding it started with the introduction of ASP.NET 2.0 and IIS 7. IIS 6 had and continues to have only one pipeline mode, and it is equivalent to what IIS 7+ calls "Classic" mode. The second, newer, and recommended pipeline mode for all applications running on IIS 7+ is called "Integrated" mode.

So, what's the difference? The key difference is how ASP.NET interacts with IIS.

• Classic mode is limited to an ASP.NET pipeline that cannot interact with the IIS pipeline. Essentially a request comes in and if IIS 6/Classic has been told, through server configuration, that ASP.NET can handle it then IIS hands off the request to ASP.NET and moves on. The significance of this can be gleaned from an example. If I were to authorize access to static image files, I would not be able to do it with an ASP.NET module because the IIS 6 pipeline will handle those requests itself and ASP.NET will never see those requests because they were never handed off.* On the other hand, authorizing which users can access a .ASPX page such as a request for Foo.aspx is trivial even in IIS 6/Classic because IIS always hands those requests off to the ASP.NET pipeline. In Classic mode ASP.NET does not know what it hasn't been told and there is a lot that IIS 6/Classic may not be telling it.

• Integrated mode is recommended because ASP.NET handlers and modules can interact directly with the IIS pipeline. No longer does the IIS pipeline simply hand off the request to the ASP.NET pipeline, now it allows ASP.NET code to hook directly into the IIS pipeline and all the requests that hit it. This means that an ASP.NET module can not only observe requests to static image files, but can intercept those requests and take action by denying access, logging the request, etc.

Overcoming the error:

1. If you are running an older application that was originally built for IIS 6, perhaps you moved it to a new server, there may be absolutely nothing wrong with running the application pool of that application in Classic mode. Go ahead you don't have to feel bad.
2. Then again maybe you are giving your application a face-lift or it was chugging along just fine until you installed a 3rd party library via NuGet, manually, or by some other means. In that case it is entirely possible `httpHandlers` or `httpModules` have been added to `system.web`. The outcome is the error that you are seeing because `validateIntegratedModeConfiguration` defaults `true`. Now you have two choices:

1. Remove the `httpHandlers` and `httpModules` elements from `system.web`. There are a couple possible outcomes from this:
• Everything works fine, a common outcome;
• Your application continues to complain, there may be a web.config in a parent folder you are inheriting from, consider cleaning up that web.config too;
• You grow tired of removing the `httpHandlers` and `httpModules` that NuGet packages keep adding to `system.web`, hey do what you need to.
3. If those options do not work or are more trouble than it is worth then I'm not going to tell you that you can't set `validateIntegratedModeConfiguration` to `false`, but at least you know what you're doing and why it matters.

*Of course there are ways to get all kind of strange things into the ASP.NET pipeline from IIS 6/Classic via incantations like wildcard mappings, if you like that sort of thing.

### NumPy array is not JSON serializable

I had a similar problem with a nested dictionary with some numpy.ndarrays in it.

``````def jsonify(data):
json_data = dict()
for key, value in data.iteritems():
if isinstance(value, list): # for lists
value = [ jsonify(item) if isinstance(item, dict) else item for item in value ]
if isinstance(value, dict): # for nested lists
value = jsonify(value)
if isinstance(key, int): # if key is integer: > to string
key = str(key)
if type(value).__module__=='numpy': # if value is numpy.*: > to python list
value = value.tolist()
json_data[key] = value
return json_data
``````

### Regex for parsing directory and filename

Most languages have path parsing functions that will give you this already. If you have the ability, I'd recommend using what comes to you for free out-of-the-box.

Assuming / is the path delimiter...

``````^(.*/)([^/]*)\$
``````

The first group will be whatever the directory/path info is, the second will be the filename. For example:

• /foo/bar/baz.log: "/foo/bar/" is the path, "baz.log" is the file
• foo/bar.log: "foo/" is the path, "bar.log" is the file
• /foo/bar: "/foo/" is the path, "bar" is the file
• /foo/bar/: "/foo/bar/" is the path and there is no file.

### Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.

As pointed out, you can use `getElementById` instead, but you can also still achieve the same with a `querySelector`:

``````document.querySelector("[id='22']")
``````

### Text border using css (border around text)

The following will cover all browsers worth covering:

``````text-shadow: 0 0 2px #fff; /* Firefox 3.5+, Opera 9+, Safari 1+, Chrome, IE10 */
filter: progid:DXImageTransform.Microsoft.Glow(Color=#ffffff,Strength=1); /* IE<10 */
``````

### How can I make an image transparent on Android?

For 20% transparency, this worked for me:

``````Button bu = (Button)findViewById(R.id.button1);
bu.getBackground().setAlpha(204);
``````

### How do I avoid the "#DIV/0!" error in Google docs spreadsheet?

Wrap your formula with `IFERROR`.

``````=IFERROR(yourformula)
``````

### Two versions of python on linux. how to make 2.7 the default

Add `/usr/local/bin` to your `PATH` environment variable, earlier in the list than `/usr/bin`.

Generally this is done in your shell's rc file, e.g. for bash, you'd put this in `.bashrc`:

``````export PATH="/usr/local/bin:\$PATH"
``````

This will cause your shell to look first for a `python` in `/usr/local/bin`, before it goes with the one in `/usr/bin`.

(Of course, this means you also need to have `/usr/local/bin/python` point to `python2.7` - if it doesn't already, you'll need to symlink it.)

### Declare multiple module.exports in Node.js

in addition to @mash answer I recommend you to always do the following:

``````const method = () => {
}

const otherMethod = () => {
}

module.exports = {
method,
otherMethod,
// anotherMethod
};
``````

Note here:

• You can call `method` from `otherMethod` and you will need this a lot
• You can quickly hide a method as private when you need
• This is easier for most IDE's to understand and autocomplete your code ;)
• You can also use the same technique for import:

`const {otherMethod} = require('./myModule.js');`

### How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

@ewomack has a great answer for C#, unless you don't need extra object values. In my case, I ended up using something similar to:

``````@Html.ActionLink("Delete", "DeleteList", "List", new object { },
new { @class = "delete"})
``````

### What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

`JpaRepository` extends `PagingAndSortingRepository` which in turn extends `CrudRepository`.

Their main functions are:

Because of the inheritance mentioned above, `JpaRepository` will have all the functions of `CrudRepository` and `PagingAndSortingRepository`. So if you don't need the repository to have the functions provided by `JpaRepository` and `PagingAndSortingRepository` , use `CrudRepository`.

### How to access pandas groupby dataframe by key

I was looking for a way to sample a few members of the GroupBy obj - had to address the posted question to get this done.

#### create groupby object based on `some_key` column

``````grouped = df.groupby('some_key')
``````

#### pick N dataframes and grab their indices

``````sampled_df_i  = random.sample(grouped.indices, N)
``````

#### grab the groups

``````df_list  = map(lambda df_i: grouped.get_group(df_i), sampled_df_i)
``````

#### optionally - turn it all back into a single dataframe object

``````sampled_df = pd.concat(df_list, axis=0, join='outer')
``````

### Appending values to dictionary in Python

If you want to append to the lists of each key inside a dictionary, you can append new values to them using `+` operator (tested in Python 3.7):

``````mydict = {'a':[], 'b':[]}
print(mydict)
mydict['a'] += [1,3]
mydict['b'] += [4,6]
print(mydict)
mydict['a'] += [2,8]
print(mydict)
``````

and the output:

``````{'a': [], 'b': []}
{'a': [1, 3], 'b': [4, 6]}
{'a': [1, 3, 2, 8], 'b': [4, 6]}
``````

`mydict['a'].extend([1,3])` will do the job same as `+` without creating a new list (efficient way).

### Linux shell sort file according to the second column?

To sort by second field only (thus where second fields match, those lines with matches remain in the order they are in the original without sorting on other fields) :

``````sort -k 2,2 -s orig_file > sorted_file
``````

### jQuery: Check if button is clicked

try something like :

``````var focusout = false;

\$("#Button1").click(function () {
if (focusout == true) {
focusout = false;
return;
}
else {
GetInfo();
}
});

\$("#Text1").focusout(function () {
focusout = true;
GetInfo();
});
``````

### Call a Class From another class

``````Class2 class2 = new Class2();
``````

Instead of calling the main, perhaps you should call individual methods where and when you need them.

### jQuery UI tabs. How to select a tab based on its id not based on index

I make a wild assumption that you really have layout as:

``````<ul  class="tabs">
<li id="tabone">one</li>
<li id="tabtwo">two</li>
</ul>
``````

IF that assumption is correct, you simply use the ID to select the "tab"

``````\$('#tabone').css("display","none");
``````

EDIT: select the tab on your layout:

``````var index = \$('.tabs ul').index(\$('#tabone'));
\$('.tabs ul').tabs('select', index);
``````

### Removing NA observations with dplyr::filter()

If someone is here in 2020, after making all the pipes, if u pipe `%>% na.exclude` will take away all the NAs in the pipe!

### Scale image to fit a bounding box

html:

``````    <div class="container">
<img class="flowerImg" src="flower.jpg">
</div>
``````

css:

``````.container{
width: 100px;
height: 100px;
}

.flowerImg{
width: 100px;
height: 100px;
object-fit: cover;
/*object-fit: contain;
object-fit: scale-down;
object-position: -10% 0;
object-fit: none;
object-fit: fill;*/
}
``````

### How to squash all git commits into one?

``````echo "message" | git commit-tree HEAD^{tree}
``````

This will create an orphaned commit with the tree of HEAD, and output its name (SHA-1) on stdout. Then just reset your branch there.

``````git reset SHA-1
``````

To do the above in a single step:

``````git reset \$(git commit-tree HEAD^{tree} -m "commit message")
``````

### How to use *ngIf else?

ngif expression resulting value won’t just be the boolean true or false

if the expression is just a object, it still evaluate it as truthiness.

if the object is undefined, or non-exist, then ngif will evaluate it as falseness.

common use is if an object loaded, exist, then display the content of this object, otherwise display "loading.......".

`````` <div *ngIf="!object">
</div>

<div *ngIf="object">
<!-- the content of this object -->

object.info, object.id, object.name ... etc.
</div>
``````

another example:

``````  things = {
car: 'Honda',
shoes: 'Nike',
shirt: 'Tom Ford',
watch: 'Timex'
};

<div *ngIf="things.car; else noCar">
Nice car!
</div>

<ng-template #noCar>
Call a Uber.
</ng-template>

<!-- Nice car ! -->
``````

anthoer example:

``````<div *ngIf="things.car; let car">
Nice {{ car }}!
</div>
<!-- Nice Honda! -->
``````

ngif template

ngif angular 4

### Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the `distinct` approach is executed like:

• Copy all `business_key` values to a temporary table
• Sort the temporary table
• Scan the temporary table, returning each item that is different from the one before it

The `group by` could be executed like:

• Scan the full table, storing each value of `business key` in a hashtable
• Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

### WordPress - Check if user is logged in

Try following code that worked fine for me

``````global \$current_user;
get_currentuserinfo();
``````

Then, use following code to check whether user has logged in or not.

``````if (\$current_user->ID == '') {
//show nothing to user
}
else {
}
``````

### How to set viewport meta for iPhone that handles rotation properly?

just want to share, i've played around with the viewport settings for my responsive design, if i set the Max scale to 0.8, the initial scale to 1 and scalable to no then i get the smallest view in portrait mode and the iPad view for landscape :D... this is properly an ugly hack but it seems to work, i don't know why so i won't be using it, but interesting results

``````<meta name="viewport" content="user-scalable=no, initial-scale = 1.0,maximum-scale = 0.8,width=device-width" />
``````

enjoy :)

### How to insert a timestamp in Oracle?

Inserting date in sql

``````insert
into tablename (timestamp_value)
values ('dd-mm-yyyy hh-mm-ss AM');
``````

If suppose we wanted to insert system date

``````insert
into tablename (timestamp_value)
values (sysdate);
``````

### How to create a drop-down list?

You can also use AppCompatSpinner widget:

``````<android.support.v7.widget.AppCompatSpinner
android:id="@+id/spinner_order_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:backgroundTint="@color/red"/>
``````

``````AppCompatSpinner spinOrderType = (AppCompatSpinner) findViewById(R.id.spinner_order_type);
List<String> categories = new ArrayList<String>();

R.layout.layout_spinner_item, categories);
spinOrderType.setSelection(0);

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
String item = parent.getItemAtPosition(position).toString();
Log.d(TAG, item);
}

@Override

}
});
``````

layout_spinner_item.xml

``````<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:gravity="left"
android:textSize="@dimen/text.size.large"
``````

### SELECT query with CASE condition and SUM()

``````select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType
``````

Cheers -

### jQuery detect if textarea is empty

I know you are long past getting a solution. So, this is for others that come along to see how other people are solving the same common problem-- like me.

The examples in the question and answers indicates the use of jQuery and I am using the .change listener/handler/whatever to see if my textarea changes. This should take care of manual text changes, automated text changes, etc. to trigger the

``````//pseudocode
\$('#textarea').change(function () {
if (\$.trim(\$('#textarea').val()).length < 1) {

} else {

\$('#output').html('Your users managed to put something in the box!');
//No guarantee it isn't mindless gibberish, sorry.

}
});
});
``````

Seems to work on all the browsers I use. http://jsfiddle.net/Q3LW6/. Message shows when textarea loses focus.

Uses and reports .change(), .blur(), .keydown(), .keyup(), .mousedown(), .mouseup(), .click(), mouseleave(), and .setInterval().

# In case of multiple values and str dtype

I used the following to filter out given values in a col:

``````def filter_rows_by_values(df, col, values):
return df[df[col].isin(values) == False]
``````

Example:

In a DataFrame I want to remove rows which have values "b" and "c" in column "str"

``````df = pd.DataFrame({"str": ["a","a","a","a","b","b","c"], "other": [1,2,3,4,5,6,7]})
df
str  other
0   a   1
1   a   2
2   a   3
3   a   4
4   b   5
5   b   6
6   c   7

filter_rows_by_values(d,"str", ["b","c"])

str  other
0   a   1
1   a   2
2   a   3
3   a   4
``````

### How to exit in Node.js

I was able to get all my node processes to die directly from the Git Bash shell on Windows 10 by typing `taskkill -F -IM node.exe` - this ends all the node processes on my computer at once. I found I could also use `taskkill //F //IM node.exe`. Not sure why both `-` and `//` work in this context. Hope this helps!