Programs & Examples On #Wgl

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Following Glens idea, here it goes another possibility. It would allow you to scroll inside the div, but would prevent the body to scroll with it, when the div scroll ends. However, it seems to accumulate too many preventDefault if you scroll too much, and then it creates a lag if you want to scroll up. Does anybody have a suggestion to fix that?

       var bodyTop = document.body.scrollTop;
           'mousewheel': function(e) {
           if (document.body.scrollTop == bodyTop) return;

Android emulator: could not get wglGetExtensionsStringARB error

I ran into this issue running Android Studio 1.4. In the Android Virtual Device (AVD) Manager, I had checked the 'Use Host GPU' box, thinking this would give me some sort of boost in the emulator's speed.
Android Studio will let you choose a device that's configured that way, and it will show you the command it used to start the virtual device: Android Studio 'Run' window output

but for some reason, it doesn't warn you that the program crashed, and it doesn't show you the stderr message that you would see had you run it from the command line yourself: Output as run on the command line

When I ran it from Android Studio, I didn't see the dialog box in the screenshot above, though it shows up just fine when you run the command from the command line, so I just sat there patiently for a few minutes while nothing happened.
As pointed out elsewhere, the drivers needed for the Use Host GPU option are not yet available. Reading through that post, it appears that this setting can be used with some Intel CPUs but not the ARM chip I chose (see CPU/ABI setting below).

My solution was to just uncheck the "Use Host GPU" box which is near the bottom of the window opened through the 'edit' option after choosing the virtual device in the Android Virtual Devices tab in the AVD Manager. You can get to the AVD manager directly in Windows at
%ANDROID_HOME%\AVD Manager.exe
where in my Windows 8 install, %ANDROID_HOME% resolved to

I don't have it running on Linux at the moment, but I'd assume it's in a similar path there, i.e.:

After unchecking the 'Use Host GPU' box, I opted to check the 'Snapshot' box next to it (as I understand, that stores a copy of the already-built vm so it doesn't need to get rebuilt every time, which should save some startup time for future instances). Here are the full settings I used:
Edit Android Virtual Device (AVD) window screenshot

How to convert image into byte array and byte array to base64 String in android?

Try this:

// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();

// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg), 

what does this mean ? image/png;base64?

They serve the actual image inside CSS so there will be less HTTP requests per page.

Multiple glibc libraries on a single host

This question is old, the other answers are old. "Employed Russian"s answer is very good and informative, but it only works if you have the source code. If you don't, the alternatives back then were very tricky. Fortunately nowadays we have a simple solution to this problem (as commented in one of his replies), using patchelf. All you have to do is:

$ ./patchelf --set-interpreter /path/to/newglibc/ --set-rpath /path/to/newglibc/ myapp

And after that, you can just execute your file:

$ ./myapp

No need to chroot or manually edit binaries, thankfully. But remember to backup your binary before patching it, if you're not sure what you're doing, because it modifies your binary file. After you patch it, you can't restore the old path to interpreter/rpath. If it doesn't work, you'll have to keep patching it until you find the path that will actually work... Well, it doesn't have to be a trial-and-error process. For example, in OP's example, he needed GLIBC_2.3, so you can easily find which lib provides that version using strings:

$ strings /lib/i686/ | grep GLIBC_2.3
$ strings /path/to/newglib/ | grep GLIBC_2.3

In theory, the first grep would come empty because the system libc doesn't have the version he wants, and the 2nd one should output GLIBC_2.3 because it has the version myapp is using, so we know we can patchelf our binary using that path. If you get a segmentation fault, read the note at the end.

When you try to run a binary in linux, the binary tries to load the linker, then the libraries, and they should all be in the path and/or in the right place. If your problem is with the linker and you want to find out which path your binary is looking for, you can find out with this command:

$ readelf -l myapp | grep interpreter
  [Requesting program interpreter: /lib/]                                                                                                                                                                                   

If your problem is with the libs, commands that will give you the libs being used are:

$ readelf -d myapp | grep Shared
$ ldd myapp 

This will list the libs that your binary needs, but you probably already know the problematic ones, since they are already yielding errors as in OP's case.

"patchelf" works for many different problems that you may encounter while trying to run a program, related to these 2 problems. For example, if you get: ELF file OS ABI invalid, it may be fixed by setting a new loader (the --set-interpreter part of the command) as I explain here. Another example is for the problem of getting No such file or directory when you run a file that is there and executable, as exemplified here. In that particular case, OP was missing a link to the loader, but maybe in your case you don't have root access and can't create the link. Setting a new interpreter would solve your problem.

Thanks Employed Russian and Michael Pankov for the insight and solution!

Note for segmentation fault: you might be in the case where myapp uses several libs, and most of them are ok but some are not; then you patchelf it to a new dir, and you get segmentation fault. When you patchelf your binary, you change the path of several libs, even if some were originally in a different path. Take a look at my example below:

$ ldd myapp
./myapp: /usr/lib/x86_64-linux-gnu/ version `GLIBCXX_3.4.20' not found (required by ./myapp)
./myapp: /usr/lib/x86_64-linux-gnu/ version `GLIBCXX_3.4.21' not found (required by ./myapp) =>  (0x00007fffb167c000) => /lib/x86_64-linux-gnu/ (0x00007f9a9aad2000) => /lib/x86_64-linux-gnu/ (0x00007f9a9a8ce000) => /lib/x86_64-linux-gnu/ (0x00007f9a9a6af000) => /usr/lib/x86_64-linux-gnu/ (0x00007f9a9a3ab000) => /lib/x86_64-linux-gnu/ (0x00007f9a99fe6000)
        /lib64/ (0x00007f9a9adeb000) => /lib/x86_64-linux-gnu/ (0x00007f9a99dcf000)

Note that most libs are in /lib/x86_64-linux-gnu/ but the problematic one ( is on /usr/lib/x86_64-linux-gnu. After I patchelf'ed myapp to point to /path/to/mylibs, I got segmentation fault. For some reason, the libs are not totally compatible with the binary. Since myapp didn't complain about the original libs, I copied them from /lib/x86_64-linux-gnu/ to /path/to/mylibs2, and I also copied from /path/to/mylibs there. Then I patchelf'ed it to /path/to/mylibs2, and myapp works now. If your binary uses different libs, and you have different versions, it might happen that you can't fix your situation. :( But if it's possible, mixing libs might be the way. It's not ideal, but maybe it will work. Good luck!

Splitting string with pipe character ("|")

Or.. Pattern#quote:

String[] value_split = rat_values.split(Pattern.quote("|"));

This is happening because String#split accepts a regex:

| has a special meaning in regex.

quote will return a String representation for the regex.

Show Error on the tip of the Edit Text Android

You have written your code in onClick event. This will call when you click on EditText. But this is something like you are checking it before entering.

So what my suggestion is, you should use focus changed. When any view get focus, you are setting no error and when focus changed, you check whether there is valid input or not like below.

firstName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    public void onFocusChange(View arg0, boolean arg1) {
        if (firstName.getText().toString().trim().equalsIgnoreCase("")) {
            firstName.setError("Enter FirstName");

What does "pending" mean for request in Chrome Developer Window?

In my case, I found (after much hair-pulling) that the "pending" status was caused by the AdBlock extension. The image that I couldn't get to load had the word "ad" in the URL, so AdBlock kept it from loading.

Disabling AdBlock fixes this issue.

Renaming the file so that it doesn't contain "ad" in the URL also fixes it, and is obviously a better solution. Unless it's an advertisement, in which case you should leave it like that. :)

How to display an unordered list in two columns?

I was looking at @jaider's solution which worked but I'm offering a slightly different approach that I think is more easy to work with and which I've seen to be good across browsers.

    list-style-type: disc;
    -webkit-columns: 2;
    -moz-columns: 2;
    columns: 2;
    list-style-position: inside;//this is important addition

By default un-ordered list display the bullet position outside but then in some browsers it would cause some display problems based on the browser's way of laying out your website.

To get it to display in the format:


etc. use the following:

ul li{
    float: left;
    width: 50%;//helps to determine number of columns, for instance 33.3% displays 3 columns
    list-style-type: disc;

This should solve all your problems with displaying columns. All the best and thanks @jaider as your response helped to guide me to discover this.

Return back to MainActivity from another activity

Use this code on button click in activity and When return back to another activity just finish previous activity by setting flag in intent then put only one Activity in the Stack and destroy the previous one.

  Intent i=new Intent("this","YourClassName.Class");

Having issues with a MySQL Join that needs to meet multiple conditions

    u . *
    room u
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

Adding a css class to select using @Html.DropDownList()

Try this:

    new[] {
        new SelectListItem() { Value = "IN", Text = "India" },
        new SelectListItem() { Value = "US", Text = "United States" }
    new { @class = "form-control",@selected = Model.Country}

How to import the class within the same directory or sub directory?

In python3, is no longer necessary. If the current directory of the console is the directory where the python script is located, everything works fine with

import user

However, this won't work if called from a different directory, which does not contain
In that case, use

from . import user

This works even if you want to import the whole file instead of just a class from there.

ExpressJS - throw er Unhandled error event

This worked for me.

Just change the port number from the Project properties.

TypeError: 'NoneType' object has no attribute '__getitem__'

move.CompleteMove() does not return a value (perhaps it just prints something). Any method that does not return a value returns None, and you have assigned None to self.values.

Here is an example of this:

>>> def hello(x):
...    print x*2
>>> hello('world')
>>> y = hello('world')
>>> y

You'll note y doesn't print anything, because its None (the only value that doesn't print anything on the interactive prompt).

Vue js error: Component template should contain exactly one root element

Just make sure that you have one root div and put everything inside this root

  <div class="root">
    <!--and put all child here --!>
   <div class='child1'></div>
   <div class='child2'></div>

and so on

Deleting an element from an array in PHP

unset() destroys the specified variables.

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

    function destroy_foo()
        global $foo;

    $foo = 'bar';
    echo $foo;

The answer of the above code will be bar.

To unset() a global variable inside of a function:

    function foo()

    $bar = "something";

Angular 2 @ViewChild annotation returns undefined

This works for me, see the example below.

import {Component, ViewChild, ElementRef} from 'angular2/core';_x000D_
    selector: 'app',_x000D_
    template:  `_x000D_
        <a (click)="toggle($event)">Toggle</a>_x000D_
        <div *ngIf="visible">_x000D_
          <input #control name="value" [(ngModel)]="value" type="text" />_x000D_
export class AppComponent {_x000D_
    private elementRef: ElementRef;_x000D_
    @ViewChild('control') set controlElRef(elementRef: ElementRef) {_x000D_
      this.elementRef = elementRef;_x000D_
    toggle($event: Event) {_x000D_
      this.visible = !this.visible;_x000D_
      if(this.visible) {_x000D_
        setTimeout(() => { this.elementRef.nativeElement.focus(); });_x000D_

Passing multiple variables to another page in url


Warning The superglobals $_GET and $_REQUEST are already decoded. Using urldecode() on an element in $_GET or $_REQUEST could have unexpected and dangerous results.


be careful.

Lollipop : draw behind statusBar with its color set to transparent

This worked for my case

// Create/Set toolbar as actionbar
toolbar = (Toolbar) findViewById(;

// Check if the version of Android is Lollipop or higher
if (Build.VERSION.SDK_INT >= 21) {

    // Set the status bar to dark-semi-transparentish

    // Set paddingTop of toolbar to height of status bar.
    // Fixes statusbar covers toolbar issue
    toolbar.setPadding(0, getStatusBarHeight(), 0, 0);

// A method to find height of the status bar
public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    return result;

For more information about working with statusBars:

NLTK and Stopwords Fail #lookuperror

If you want to manually install NLTK Corpus.

1) Go to and download your desired NLTK Corpus file.

2) Now in a Python shell check the value of

3) Choose one of the path that exists on your machine, and unzip the data files into the corpora sub directory inside.

4) Now you can import the data from nltk.corpos import stopwords


Is there a stopwatch in Java?

Try this...

import java.util.concurrent.TimeUnit;

public class StopwatchTest {
    public static void main(String[] args) throws Exception {
        Stopwatch stopwatch = Stopwatch.createStarted();
        Thread.sleep(1000 * 60);
        stopwatch.stop(); // optional
        long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        System.out.println("Time in milliseconds "+millis);
        System.out.println("that took: " + stopwatch);

Is there a way to reset IIS 7.5 to factory settings?

There are automatic backup under %systemdrive%\inetpub\history but it may not help much if you already made lots of changes.

You will have to regularly back up manually using appcmd.

If you try to reinstall IIS, please first uninstall IIS and WAS via Add/Remove Programs, and then delete all existing files under C:\inetpub and C:\Windows\system32\inetsrv directories. Then you can install again cleanly.

WARN: beginners on IIS are not recommended to execute the steps above without a full backup of the system. The steps should be executed with caution and good understanding of IIS. If you are not capable of or you have doubt, make sure you open a support case with Microsoft via and consult.

Bootstrap 3 - How to load content in modal body via AJAX?

A simple way to use modals is with eModal!

Ex from github:

  1. Link to eModal.js <script src="//"></script>
  2. use eModal to display a modal for alert, ajax, prompt or confirm

    // Display an alert modal with default title (Attention)

$(document).ready(function () {/* activate scroll spy menu */_x000D_
    var iconPrefix = '.glyphicon-';_x000D_
    $(iconPrefix + 'cloud').click(ajaxDemo);_x000D_
    $(iconPrefix + 'comment').click(alertDemo);_x000D_
    $(iconPrefix + 'ok').click(confirmDemo);_x000D_
    $(iconPrefix + 'pencil').click(promptDemo);_x000D_
    $(iconPrefix + 'screenshot').click(iframeDemo);_x000D_
    ///////////////////* Implementation *///////////////////_x000D_
    // Demos_x000D_
    function ajaxDemo() {_x000D_
        var title = 'Ajax modal';_x000D_
        var params = {_x000D_
            buttons: [_x000D_
               { text: 'Close', close: true, style: 'danger' },_x000D_
               { text: 'New content', close: false, style: 'success', click: ajaxDemo }_x000D_
            size: eModal.size.lg,_x000D_
            title: title,_x000D_
            url: '' + Math.floor((Math.random() * 7) + 1) + '/short/ul/bq/prude/code/decorete'_x000D_
        return eModal_x000D_
            .then(function () { alert('Ajax Request complete!!!!', title) });_x000D_
    function alertDemo() {_x000D_
        var title = 'Alert modal';_x000D_
        return eModal_x000D_
            .alert('You welcome! Want clean code ?', title)_x000D_
            .then(function () { alert('Alert modal is visible.', title); });_x000D_
    function confirmDemo() {_x000D_
        var title = 'Confirm modal callback feedback';_x000D_
        return eModal_x000D_
            .confirm('It is simple enough?', 'Confirm modal')_x000D_
            .then(function (/* DOM */) { alert('Thank you for your OK pressed!', title); })_x000D_
            .fail(function (/*null*/) { alert('Thank you for your Cancel pressed!', title) });_x000D_
    function iframeDemo() {_x000D_
        var title = 'Insiders';_x000D_
        return eModal_x000D_
            .iframe('', title)_x000D_
            .then(function () { alert('iFrame loaded!!!!', title) });_x000D_
    function promptDemo() {_x000D_
        var title = 'Prompt modal callback feedback';_x000D_
        return eModal_x000D_
            .prompt({ size:, message: 'What\'s your name?', title: title })_x000D_
            .then(function (input) { alert({ message: 'Hi ' + input + '!', title: title, imgURI: '' }) })_x000D_
            .fail(function (/**/) { alert('Why don\'t you tell me your name?', title); });_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<link href="" rel="stylesheet" >_x000D_
<link href="http//" rel="stylesheet">_x000D_
<div class="row" itemprop="about">_x000D_
 <div class="col-sm-1 text-center"></div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <p>You must get the message from a remote server? No problem!</p>_x000D_
    <i class="glyphicon glyphicon-cloud fa-5x pointer" title="Try me!"></i>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <p>Traditional alert box. Using only text or a lot of magic!?</p>_x000D_
    <i class="glyphicon glyphicon-comment fa-5x pointer" title="Try me!"></i>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <p>Get an okay from user, has never been so simple and clean!</p>_x000D_
    <i class="glyphicon glyphicon-ok fa-5x pointer" title="Try me!"></i>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10  text-center">_x000D_
    <p>Do you have a question for the user? We take care of it...</p>_x000D_
    <i class="glyphicon glyphicon-pencil fa-5x pointer" title="Try me!"></i>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10  text-center">_x000D_
    <p>IFrames are hard to deal with it? We don't think so!</p>_x000D_
    <i class="glyphicon glyphicon-screenshot fa-5x pointer" title="Try me!"></i>_x000D_
 <div class="col-sm-1 text-center"></div>_x000D_

PostgreSQL: Why psql can't connect to server?

In my case I had this error, /var/run/postgresql/.s.PGSQL.5433 (note, one number up from the file it was looking for, .s.PGSQL.5432) was present. Tried the instructions at the top of this page but nothing worked.

Turns out there was an old directory for PostGreSQL 12 config files in /etc/postgresql/12, which I deleted, which solved the issue.


1 cent: no space b/w CAST and (expression). i.e., CAST(columnName AS SIGNED).

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("");  // as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

Delete first character of a string in Javascript

You can do it with substring method:

let a = "My test string";

a = a.substring(1);

console.log(a); // y test string

How do I increment a DOS variable in a FOR /F loop?

Or you can do this without using Delay.

set /a "counter=0"

-> your for loop here

do (
   call :increaseby1

set /a "counter+=1"

Missing maven .m2 folder

Use mvn -X or mvn --debug to find out from which different locations Maven reads settings.xml. This switch activates debug logging. Just check the first lines of mvn --debug | findstr /i /c:using /c:reading.

Right, Maven uses the Java system property user.home as location for the .m2 folder.

But user.home does not always resolve to %USERPROFILE%\.m2. If you have moved the location of your Desktop folder to another place, user.home might resolve to the parent directory of this new Desktop folder. This happens when using Windows Vista or a more recent Windows together with Java 7 or any older Java version.

The blog post Java’s “user.home” is Wrong on Windows describes it very well and gives links to the official bug reports. The bug is marked as resolved in Java 8. The comment of the blog's visitor Lars proposes a nice workaround.

Create listview in fragment android

Please use ListFragment. Otherwise, it won't work.

EDIT 1: Then you'll only need setListAdapter() and getListView().

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +


Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

mov <- subset(movies, length != "")

SQLite: How do I save the result of a query as a CSV file?

To include column names to your csv file you can do the following:

sqlite> .headers on
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

To verify the changes that you have made you can run this command:

sqlite> .show


echo: off   
explain: off   
headers: on   
mode: csv   
nullvalue: ""  
output: stdout  
separator: "|"   
stats: off   
width: 22 18 

Matplotlib: ValueError: x and y must have same first dimension

You should make x and y numpy arrays, not lists:

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,

With this change, it produces the expect plot. If they are lists, m * x will not produce the result you expect, but an empty list. Note that m is anumpy.float64 scalar, not a standard Python float.

I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:

In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]

while multiplying a list with a float gives an error (as I think it should):

In [43]: 1.5 * [1, 2, 3]
TypeError                                 Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'

The weird thing is that multiplying a Python list with a Numpy scalar apparently works:

In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []

In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]

In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]

So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:

In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123,  2.123,  3.123])

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

Seems PyAudio is supported by Python 2.7, 3.4, 3.5, and 3.6. Refer

Please suggest if there is any alternate way to install PyAudio on Python 3.8.2

SQL Server, division returns zero

When you use only integers in a division, you will get integer division. When you use (at least one) double or float, you will get floating point division (and the answer you want to get).

So you can

  1. declare one or both of the variables as float/double
  2. cast one or both of the variables to float/double.

Do not just cast the result of the integer division to double: the division was already performed as integer division, so the numbers behind the decimal are already lost.

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I had the same issue but the password was good and "Log on as batch job" alone was not sufficient.

Check that the IIS application pool identity account or group has both the "Log on as Batch Job" permission AND that it can "impersonate a client after authentication".

To change these settings perform the following steps on the web front end server:

  • Start>Run type "secpol.msc"
    • Find: Security Settings>Local Policies>User Rights assignment
    • Add user or group to "Log on as Batch Job"
    • Check group membership of service account (in Active Directory) if a particular group is being used for this purpose.
    • Find "impersonate a client after authentication" and add the application pool identity
    • Reboot the server

You should be able to access the site!

Is there a way to check which CSS styles are being used or not used on a web page?

Google Chrome has a two ways to check for unused CSS.

1. Audit Tab: > Right Click + Inspect Element on the page, find the "Audit" tab, and run the audit, making sure "Web Page Performance" is checked.

Lists all unused CSS tags - see image below.

Screen Shot of Chrome's Audit Tool

Update: - - - - - - - - - - - - - - OR - - - - - - - - - - - - - -

2. Coverage Tab: > Right Click + Inspect Element on the page, find the three dots on the far right (circled in image) and open Console Drawer (or hit Esc), finally click the three dots left side in the drawer (circled in image) to open Coverage tool.

Chrome launched a tool to see unused CSS and JS - Chrome 59 Update Allows you to start and stop a recording (red square in image) to allow better coverage of a user experience on the page.

Shows all used and unused CSS/JS in the files - see image below.

Example of Coverage tool in Chrome

Select multiple columns by labels in pandas

Just pick the columns you want directly....


Hash function for a string

Use boost::hash

#include <boost\functional\hash.hpp>


std::string a = "ABCDE";
size_t b = boost::hash_value(a);

Why is "forEach not a function" for this object?

When I tried to access the result from

Object.keys(a).forEach(function (key){ console.log(a[key]); });

it was plain text result with no key-value pairs Here is an example

var fruits = {
    apple: "fruits/apple.png",
    banana: "fruits/banana.png",
    watermelon: "watermelon.jpg",
    grapes: "grapes.png",
    orange: "orange.jpg"

Now i want to get all links in a separated array , but with this code

    function linksOfPics(obJect){

the result of :



I figured out this one which solves what I'm looking for

["fruits/apple.png", "fruits/banana.png", "watermelon.jpg", "grapes.png", "orange.jpg"]

Making the Android emulator run faster

I noticed that the emulator defaults to only Core 0, where most Windows applications will default to "any" core. Also, if you put it on another core (like the last core), it may make the emulator go crazy. If you can, you can try putting your heavy-CPU usage applications on the other CPU cores for a boost in speed.

Hardware-wise, get the fastest CPU you can get that works for single-core applications. More than 2 cores might not experience a huge difference in terms of emulator performance.

Eclipse + the Android emulator together eat up a ton of RAM. I would recommend 3 gigs of RAM at least because I used a system with 2 gigs of RAM, and it slowed down because the system ran out of RAM and started to use the page file.

I feel that the best CPUs for it will probably have a high clock (only use clock as a measure for CPUs in the same series btw), handle non-SIMD operations well, and have a turbo boost mechanism. There aren't many Java-based benchmarks, but overall look for application benchmarks like compression and office. Don't look at gaming or media since those are affected greatly by SIMD. If you find a Java one, even better.

Cannot start session without errors in phpMyAdmin


I'm using windows 7 ultimate and WAMP 2.4 server The tmp folder was missing, so I created one and this solved my problem. Check the php.ini file for the correct path: session.save_path

What version of JBoss I am running?

You can retrieve information about the version of your JBoss EAP installation by running the same script used to start the server with the -V switch. For Linux and Unix installations this script is and on Microsoft Windows installations it is run.bat. Regardless of platform the script is located in $JBOSS_HOME/bin. Using these scripts to actually start your server is dealt with in Chapter 4, Launching the JBoss EAP Server.

How do I specify unique constraint for multiple columns in MySQL?

You can add multiple-column unique indexes via phpMyAdmin. (I tested in version 4.0.4)

Navigate to the structure page for your target table. Add a unique index to one of the columns. Expand the Indexes list on the bottom of the structure page to see the unique index you just added. Click the edit icon, and in the following dialog you can add additional columns to that unique index.

Login to website, via C#

You can simplify things quite a bit by creating a class that derives from WebClient, overriding its GetWebRequest method and setting a CookieContainer object on it. If you always set the same CookieContainer instance, then cookie management will be handled automatically for you.

But the only way to get at the HttpWebRequest before it is sent is to inherit from WebClient and override that method.

public class CookieAwareWebClient : WebClient
    private CookieContainer cookie = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
            (request as HttpWebRequest).CookieContainer = cookie;
        return request;

var client = new CookieAwareWebClient();
client.BaseAddress = @"";
var loginData = new NameValueCollection();
loginData.Add("login", "YourLogin");
loginData.Add("password", "YourPassword");
client.UploadValues("login.php", "POST", loginData);

//Now you are logged in and can request pages    
string htmlSource = client.DownloadString("index.php");

Abstract Class vs Interface in C++

Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.

class IInterface() 
   Virtual ~IInterface(){}; 

Class ClassImpl : public IInterface 

Int main() 

  IInterface* pInterface = new ClassImpl(); 
  delete pInterface; // Wrong in OO Programming, correct in C++.

Explain why constructor inject is better than other options

By using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner

We need the assurance from the IoC container that, before using any bean, the injection of necessary beans must be done.

In setter injection strategy, we trust the IoC container that it will first create the bean first but will do the injection right before using the bean using the setter methods. And the injection is done according to your configuration. If you somehow misses to specify any beans to inject in the configuration, the injection will not be done for those beans and your dependent bean will not function accordingly when it will be in use!

But in constructor injection strategy, container imposes (or must impose) to provide the dependencies properly while constructing the bean. This was addressed as " container-agnostic manner", as we are required to provide dependencies while creating the bean, thus making the visibility of dependency, independent of any IoC container.


Q1: And how to prevent container from creating bean by constructor with null values instead of missing beans?

You have no option to really miss any <constructor-arg> (in case of Spring), because you are imposed by IoC container to provide all the constructor arguments needed to match a provided constructor for creating the bean. If you provide null in your <constructor-arg> intentionally. Then there is nothing IoC container can do or need to do with it!

How to save password when using Subversion from the console

I'm using the TortoiseSVN client on Windows, and for me, setting store-passwords parameter as yes in %USERPROFILE%\AppData\Roaming\Subversion\config does not help to store the password.

The password was successfully saved after removing this folder (just in case renaming):



Windows 7, TortoiseSVN 1.7.11 (Build 23600 - 64 bit, 2012-12-12T19:08:52), Subversion 1.7.8.

Why is the GETDATE() an invalid identifier

Use ORACLE equivalent of getdate() which is sysdate . Read about here. Getdate() belongs to SQL Server , will not work on Oracle.

Other option is current_date

Git add and commit in one command

I use the following alias for add all and commit:

git config --global '!git add -A && git commit -a'

Then, by typing:

git ac

I get a vim window to get more editing tools for my commit message.

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

There is one simple answer for this: You have been output something else, like text, or anything related to output from your page before you send your header. This affect why you get that error.

Just check your code for posible output or you can put the header on top of your method so it will be send first.

how to stop a running script in Matlab

If ctrl+c doesn't respond right away because your script is too long/complex, hold it.

The break command doesn't run when matlab is executing some of its deeper scripts, and either it won't log a ctrl sequence in the buffer, or it clears the buffer just before or just after it completes those pieces of code. In either case, when matlab returns to execute more of your script, it will recognize that you are holding ctrl+c and terminate.

For longer running programs, I usually try to find a good place to provide a status update and I always accompany that with some measure of time using tic and toc. Depending on what I am doing, I might use run time, segment time, some kind of average, etc...

For really long running programs, I found this to be exceptionally useful

but it looks like they have some newer functions for this too.

Adding an HTTP Header to the request in a servlet filter

Extend HttpServletRequestWrapper, override the header getters to return the parameters as well:

public class AddParamsToHeader extends HttpServletRequestWrapper {
    public AddParamsToHeader(HttpServletRequest request) {

    public String getHeader(String name) {
        String header = super.getHeader(name);
        return (header != null) ? header : super.getParameter(name); // Note: you can't use getParameterValues() here.

    public Enumeration getHeaderNames() {
        List<String> names = Collections.list(super.getHeaderNames());
        return Collections.enumeration(names);

..and wrap the original request with it:

chain.doFilter(new AddParamsToHeader((HttpServletRequest) request), response);

That said, I personally find this a bad idea. Rather give it direct access to the parameters or pass the parameters to it.

How to make Apache serve index.php instead of index.html?

PHP will work only on the .php file extension.

If you are on Apache you can also set, in your httpd.conf file, the extensions for PHP. You'll have to find the line:

AddType application/x-httpd-php .php .html

and add how many extensions, that should be read with the PHP interpreter, as you want.

How to align the text middle of BUTTON

You can use text-align: center; line-height: 65px;



.loginBtn {
    background:url(images/loginBtn-center.jpg) repeat-x;
    margin:20px auto;
    box-shadow:0 1px 2px #5e5d5b;
    text-align: center;  <--------- Here
    line-height: 65px;   <--------- Here

How to create a timeline with LaTeX?

There is timeline.sty floating around.

The syntax is simpler than using tikz:

%%% In LaTeX:
%%% \begin{timeline}{length}(start,stop)
%%%   .
%%%   .
%%%   .
%%% \end{timeline}
%%% in plain TeX
%%% \timeline{length}(start,stop)
%%%   .
%%%   .
%%%   .
%%% \endtimeline
%%% in between the two, we may have:
%%% \item{date}{description}
%%% \item[sortkey]{date}{description}
%%% \optrule
%%% the options to timeline are:
%%%      length The amount of vertical space that the timeline should
%%%                use.
%%%      (start,stop) indicate the range of the timeline. All dates or
%%%                sortkeys should lie in the range [start,stop]
%%% \item without the sort key expects date to be a number (such as a
%%%      year).
%%% \item with the sort key expects the sort key to be a number; date
%%%      can be anything. This can be used for log scale time lines
%%%      or dates that include months or days.
%%% putting \optrule inside of the timeline environment will cause a
%%%      vertical rule to be drawn down the center of the timeline.

I've used python's to convert dates to 'sort keys' in the context of the package.

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Use Transformation method:

To Hide:

editText.transformationMethod = PasswordTransformationMethod.getInstance()

To Visible:

editText.transformationMethod = SingleLineTransformationMethod.getInstance()

That's it.

Android Drawing Separator/Divider Line in Layout?

Here is your answer..this is an example to draw line between controls...

            android:text="FaceBook Feeds" />


            android:layout_height="50dp" />

This code draw line between two controls...

Convert floating point number to a certain precision, and then copy to string

In case the precision is not known until runtime, this other formatting option is useful:

>>> n = 9
>>> '%.*f' % (n, numvar)

What is the format specifier for unsigned short int?

For scanf, you need to use %hu since you're passing a pointer to an unsigned short. For printf, it's impossible to pass an unsigned short due to default promotions (it will be promoted to int or unsigned int depending on whether int has at least as many value bits as unsigned short or not) so %d or %u is fine. You're free to use %hu if you prefer, though.

Store a cmdlet's result value in a variable in Powershell

Just access the Priority property of the object returned from the pipeline:

$var = (Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

(This won't work if Get-WSManInstance returns multiple objects.2)

For the second question: to get two properties there are several options, problably the simplest is to have have one variable* containing an object with two separate properties:

$var = (Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)

and then use, assuming only one process:




If there are multiple processes $var will be an array which you can index, so to get the properties of the first process (using the array literal syntax @(...) so it is always a collection1):

$var = @(Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)

and then use:


1 PowerShell helpfully for the command line, but not so helpfully in scripts has some extra logic when assigning the result of a pipeline to a variable: if no objects are returned then set $null, if one is returned then that object is assigned, otherwise an array is assigned. Forcing an array returns an array with zero, one or more (respectively) elements.

2 This changes in PowerShell V3 (at the time of writing in Release Candidate), using a member property on an array of objects will return an array of the value of those properties.

Finding the average of an array using JS

You can use map/reduce functions of javascript to find average. Reduce will sum them up, and map will find average.

var avg =, i, arr) => c / arr.length).reduce((p, c) => c + p);

MSVCP140.dll missing

That's probably the C++ runtime library. Since it's a DLL it is not included in your program executable. Your friend can download those libraries from Microsoft.

React setState not updating state

In case of hooks, you should use useEffect hook.

const [fruit, setFruit] = useState('');


useEffect(() => {
  console.log('Fruit', fruit);
}, [fruit])

Spring data JPA query with parameter properties

You can try something like this:

public interface PersonRepository extends CrudRepository<Person, Long> {
       @Query("select p from Person AS p"
       + " ,Name AS n"  
       + " where p.forename = n.forename "
       + " and p.surname = n.surname"
       + " and n = :name")
       Set<Person>findByName(@Param("name") Name name);

Radio buttons not checked in jQuery

if ($("input").is(":not(:checked)"))

AFAIK, this should work, tested against the latest stable jQuery (1.2.6).

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

So let's fully understand, Let's say you have a query which works in localhost but does not in production mode, This is because in MySQL 5.7 and above they decided to activate the sql_mode=only_full_group_by by default, basically it is a strict mode which prevents you to select non aggregated fields.

Here's the query (works in local but not in production mode) :

SELECT post.*, YEAR(created_at) as year
FROM post

SELECT, YEAR(created_at) as year  // This will generate an error since there are many ids
FROM post

To verify if the sql_mode=only_full_group_by is activated for, you should execute the following query :

SELECT @@sql_mode;   //localhost


But if try in production mode, or somewhere where it gives you the error it should be activated:

SELECT @@sql_mode;   //production


Otherwise, if you are using phpMyAdmin then go to -> Variables and search for sql_mode

Let's take our previous example and adapt it to it :

SELECT MIN(, YEAR(created_at) as year  //Here we are solving the problem with MIN()
FROM post

And the same for MAX()

And if we want all the IDs, we're going to need:

SELECT GROUP_CONCAT( SEPARATOR ','), YEAR(created_at) as year
FROM post

or another newly added function:

SELECT ANY_VALUE(, YEAR(created_at) as year 
FROM post

?? ANY_VALUE does not exist for MariaDB

And If you want all the fields, then you could use the same:

SELECT ANY_VALUE(, ANY_VALUE(post.slug), ANY_VALUE(post.content) YEAR(created_at) as year 
FROM post

? To deactivate the sql_mode=only_full_group_by then you'll need to execute this query:

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));

Sorry for the novel, hope it helps.

How to remove all white spaces from a given text file

Try this:

tr -d " \t" <filename

See the manpage for tr(1) for more details.

What is the function of FormulaR1C1?

Here's some info from my blog on how I like to use formular1c1 outside of vba:

You’ve just finished writing a formula, copied it to the whole spreadsheet, formatted everything and you realize that you forgot to make a reference absolute: every formula needed to reference Cell B2 but now, they all reference different cells.

How are you going to do a Find/Replace on the cells, considering that one has B5, the other C12, the third D25, etc., etc.?

The easy way is to update your Reference Style to R1C1. The R1C1 reference works with relative positioning: R marks the Row, C the Column and the numbers that follow R and C are either relative positions (between [ ]) or absolute positions (no [ ]).


  • R[2]C refers to the cell two rows below the cell in which the formula’s in
  • RC[-1] refers to the cell one column to the left
  • R1C1 refers the cell in the first row and first cell ($A$1)

What does it matter? Well, When you wrote your first formula back in the beginning of this post, B2 was the cell 4 rows above the cell you wrote it in, i.e. R[-4]C. When you copy it across and down, while the A1 reference changes, the R1C1 reference doesn’t. Throughout the whole spreadsheet, it’s R[-4]C. If you switch to R1C1 Reference Style, you can replace R[-4]C by R2C2 ($B$2) with a simple Find / Replace and be done in one fell swoop.

how to create a logfile in php?

You could use built-in function trigger_error() to trigger user errors/warnings/notices and set_error_handler() to handle them. Inside your error handler you might want to use error_log() or file_put_contents() to store all records on files. To have a single file for every day just use something like sprintf('%s.log', date('Y-m-d')) as filename. And now you should know where to start... :)

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

1) Put =Left(E1,5) in F1

2) Copy F1, then select entire F column and paste.

Constructors in Go

In Go, a constructor can be implemented using a function that returns a pointer to a modified structure.

type Colors struct {
    R   byte
    G   byte
    B   byte

// Constructor
func NewColors (r, g, b byte) *Colors {
    return &Color{R:r, G:g, B:b}

For weak dependencies and better abstraction, the constructor does not return a pointer to a structure, but an interface that this structure implements.

type Painter interface {
    paintMethod1() byte
    paintMethod2(byte) byte

type Colors struct {
    R byte
    G byte
    B byte

// Constructor return intreface
func NewColors(r, g, b byte) Painter {
    return &Color{R: r, G: g, B: b}

func (c *Colors) paintMethod1() byte {
    return c.R

func (c *Colors) paintMethod2(b byte) byte {
    return c.B = b

How to handle windows file upload using Selenium WebDriver?

Below code works for me :

public void test() {
    WebDriver driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

SQL Server: use CASE with LIKE

CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE 
Lname END AS LnameTrue FROM dbo.____Fname_Lname

iPhone: How to get current milliseconds?

This is what I used for Swift

var date = NSDate()
let currentTime = Int64(date.timeIntervalSince1970 * 1000)

print("Time in milliseconds is \(currentTime)")

used this site to verify accuracy

how to run mysql in ubuntu through terminal

If you want to run your scripts, then

mysql -u root -p < yourscript.sql

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

exceeds the list view threshold 5000 items in Sharepoint 2010

You can increase the List View Threshold beyond the 5,000 default, but it is highly recommended that you don't, as it has performance implications. The recommended fix is to add an index to the field or fields used in the query (usually the ID field for a list or the Title field for a library).

When there is an index, that is used to retrieve the item(s); when there is no index the whole list is opened for a scan (and therefore hits the threshold). You create the index on the List (or Library) settings page.

This article is a good overview:

Count the occurrences of DISTINCT values

I have resolved the same problem using the below code:

String query = "SELECT violationDate, COUNT(*) as date " +
            "FROM challan " +
            "WHERE challanType = '" + type + "' GROUP BY violationDate";

Here violationDate and date are two columns of the result table. date column will return occurrence.


How to unapply a migration in ASP.NET Core with EF Core

To revert the last applied migration you should (package manager console commands):

  1. Revert migration from database: PM> Update-Database <prior-migration-name>
  2. Remove migration file from project (or it will be reapplied again on next step)
  3. Update model snapshot: PM> Remove-Migration

UPD: The second step seems to be not required in latest versions of Visual Studio (2017).

What's the difference between the atomic and nonatomic attributes?

This is explained in Apple's documentation, but below are some examples of what is actually happening.

Note that there is no "atomic" keyword, if you do not specify "nonatomic", then the property is atomic, but specifying "atomic" explicitly will result in an error.

If you do not specify "nonatomic", then the property is atomic, but you can still specify "atomic" explicitly in recent versions if you want to.

//@property(nonatomic, retain) UITextField *userName;
//Generates roughly

- (UITextField *) userName {
    return userName;

- (void) setUserName:(UITextField *)userName_ {
    [userName_ retain];
    [userName release];
    userName = userName_;

Now, the atomic variant is a bit more complicated:

//@property(retain) UITextField *userName;
//Generates roughly

- (UITextField *) userName {
    UITextField *retval = nil;
    @synchronized(self) {
        retval = [[userName retain] autorelease];
    return retval;

- (void) setUserName:(UITextField *)userName_ {
    @synchronized(self) {
      [userName_ retain];
      [userName release];
      userName = userName_;

Basically, the atomic version has to take a lock in order to guarantee thread safety, and also is bumping the ref count on the object (and the autorelease count to balance it) so that the object is guaranteed to exist for the caller, otherwise there is a potential race condition if another thread is setting the value, causing the ref count to drop to 0.

There are actually a large number of different variants of how these things work depending on whether the properties are scalar values or objects, and how retain, copy, readonly, nonatomic, etc interact. In general the property synthesizers just know how to do the "right thing" for all combinations.

Cmake is not able to find Python-libraries

In case that might help, I found a workaround for a similar problem, looking at the cmake doc :

You must set two env vars for cmake to find coherent versions. Unfortunately this is not a generic solution...

cmake -DPYTHON_LIBRARY=${HOME}/.pyenv/versions/3.8.0/lib/libpython3.8.a -DPYTHON_INCLUDE_DIR=${HOME}/.pyenv/versions/3.8.0/include/python3.8/ cern_root/

Make a UIButton programmatically in Swift

Swift 3: You can create a UIButton programmatically

either inside a methods scope for example in ViewDidLoad() Be sure to add constraints to the button, otherwise you wont see it

let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false #selector(buttonAction), withSender: self)
//button.backgroundColor etc


@objc func buttonAction() {
   //some Action

or outside your scope as global variable to access it from anywhere in your module

let button: UIButton = {
   let b = UIButton()
   b.translatesAutoresizingMaskIntoConstraints = false
   //b.backgroundColor etc
   return b

and then you setup the constraints

func setupButtonView() {
   button.widthAnchor.constraint(equalToConstant: 40).isActive = true
   button.heightAnchor.constraint(equalToConstant: 40).isActive = true
   // etc


How to undo a SQL Server UPDATE query?

Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.

Then you can just review the contents pre-update and write a SQL script to do the update.

python to arduino serial read & write

I found it is better to use the command Serial.readString() to replace the to obtain the continuous I/O for Arduino.

Get array of object's keys


For getting all of the keys of an Object you can use Object.keys(). Object.keys() takes an object as an argument and returns an array of all the keys.


const object = {_x000D_
  a: 'string1',_x000D_
  b: 42,_x000D_
  c: 34_x000D_
const keys = Object.keys(object)_x000D_
console.log(keys.length) // we can easily access the total amount of properties the object has

In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.

Getting the values with: Object.values()

The complementary function of Object.keys() is Object.values(). This function takes an object as an argument and returns an array of values. For example:

const object = {_x000D_
  a: 'random',_x000D_
  b: 22,_x000D_
  c: true_x000D_

How to format DateTime columns in DataGridView?

I used these code Hope it could help

dataGridView2.Rows[n].Cells[3].Value = item[2].ToString();
dataGridView2.Rows[n].Cells[3].Value = Convert.ToDateTime(item[2].ToString()).ToString("d");

Understanding the Rails Authenticity Token

Methods Where authenticity_token is required

authenticity_token is required in case of idempotent methods like post, put and delete, Because Idempotent methods are affecting to data.

Why It is Required

It is required to prevent from evil actions. authenticity_token is stored in session, whenever a form is created on web pages for creating or updating to resources then a authenticity token is stored in hidden field and it sent with form on server. Before executing action user sent authenticity_token is cross checked with authenticity_token stored in session. If authenticity_token is same then process is continue otherwise it does not perform actions.

Column standard deviation R

The general idea is to sweep the function across. You have many options, one is apply():

R> set.seed(42)
R> M <- matrix(rnorm(40),ncol=4)
R> apply(M, 2, sd)
[1] 0.835449 1.630584 1.156058 1.115269

How to set image on QPushButton?

You can also use:

button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");

Note: This is a little hacky. You should use this only as last resort. Icons should be set from C++ code or Qt Designer.

How can I multiply and divide using only bit shifting and adding?

This should work for multiplication:


.globl  main


# $4 * $5 = $2

    addi $4, $0, 0x9
    addi $5, $0, 0x6

    add  $2, $0, $0 # initialize product to zero

    beq  $5, $0, Exit # if multiplier is 0,terminate loop
    andi $3, $5, 1 # mask out the 0th bit in multiplier
    beq  $3, $0, Shift # if the bit is 0, skip add
    addu $2, $2, $4 # add (shifted) multiplicand to product

    sll $4, $4, 1 # shift up the multiplicand 1 bit
    srl $5, $5, 1 # shift down the multiplier 1 bit
    j Loop # go for next  

Exit: #

li $v0,10

Android: resizing imageview in XML

Please try this one works for me:

<ImageView android:id="@+id/image_view"     

Mockito How to mock only the call of a method of the superclass

If you really don't have a choice for refactoring you can mock/stub everything in the super method call e.g.

    class BaseService {

        public void validate(){
            fail(" I must not be called");

        public void save(){
            //Save method of super will still be called.

    class ChildService extends BaseService{

        public void load(){}

        public void save(){

    public void testSave() {
        ChildService classToTest = Mockito.spy(new ChildService());

        // Prevent/stub logic in

        // When;

        // Then

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

What is the difference between active and passive FTP?

Redacted version of my article FTP Connection Modes (Active vs. Passive):

FTP connection mode (active or passive), determines how a data connection is established. In both cases, a client creates a TCP control connection to an FTP server command port 21. This is a standard outgoing connection, as with any other file transfer protocol (SFTP, SCP, WebDAV) or any other TCP client application (e.g. web browser). So, usually there are no problems when opening the control connection.

Where FTP protocol is more complicated comparing to the other file transfer protocols are file transfers. While the other protocols use the same connection for both session control and file (data) transfers, the FTP protocol uses a separate connection for the file transfers and directory listings.

In the active mode, the client starts listening on a random port for incoming data connections from the server (the client sends the FTP command PORT to inform the server on which port it is listening). Nowadays, it is typical that the client is behind a firewall (e.g. built-in Windows firewall) or NAT router (e.g. ADSL modem), unable to accept incoming TCP connections.

For this reason the passive mode was introduced and is mostly used nowadays. Using the passive mode is preferable because most of the complex configuration is done only once on the server side, by experienced administrator, rather than individually on a client side, by (possibly) inexperienced users.

In the passive mode, the client uses the control connection to send a PASV command to the server and then receives a server IP address and server port number from the server, which the client then uses to open a data connection to the server IP address and server port number received.

Network Configuration for Passive Mode

With the passive mode, most of the configuration burden is on the server side. The server administrator should setup the server as described below.

The firewall and NAT on the FTP server side have to be configured not only to allow/route the incoming connections on FTP port 21 but also a range of ports for the incoming data connections. Typically, the FTP server software has a configuration option to setup a range of the ports, the server will use. And the same range has to be opened/routed on the firewall/NAT.

When the FTP server is behind a NAT, it needs to know it's external IP address, so it can provide it to the client in a response to PASV command.

Network Configuration for Active Mode

With the active mode, most of the configuration burden is on the client side.

The firewall (e.g. Windows firewall) and NAT (e.g. ADSL modem routing rules) on the client side have to be configured to allow/route a range of ports for the incoming data connections. To open the ports in Windows, go to Control Panel > System and Security > Windows Firewall > Advanced Settings > Inbound Rules > New Rule. For routing the ports on the NAT (if any), refer to its documentation.

When there's NAT in your network, the FTP client needs to know its external IP address that the WinSCP needs to provide to the FTP server using PORT command. So that the server can correctly connect back to the client to open the data connection. Some FTP clients are capable of autodetecting the external IP address, some have to be manually configured.

Smart Firewalls/NATs

Some firewalls/NATs try to automatically open/close data ports by inspecting FTP control connection and/or translate the data connection IP addresses in control connection traffic.

With such a firewall/NAT, the above configuration is not necessary for a plain unencrypted FTP. But this cannot work with FTPS, as the control connection traffic is encrypted and the firewall/NAT cannot inspect nor modify it.

How to remove \n from a list element?

Using list comprehension:

myList = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']

[(el.strip()) for el in myList]

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

We can make it So simple like below

<input type="number"  onkeydown="javascript: return event.keyCode == 69 ? false : true" />

Updated Answer

we can make it even more simple as @88 MPG suggests

<input type="number" onkeydown="return event.keyCode !== 69" />

Git Ignores and Maven targets

The .gitignore file in the root directory does apply to all subdirectories. Mine looks like this:


This is in a multi-module maven project. All the submodules are imported as individual eclipse projects using m2eclipse. I have no further .gitignore files. Indeed, if you look in the gitignore man page:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory

So this should work for you.

Bat file to run a .exe at the command prompt

You can use:

start "windowTitle" fullPath/file.exe

Note: the first set of quotes must be there but you don't have to put anything in them, e.g.:

start "" fullPath/file.exe

MySQL JDBC Driver 5.1.33 - Time Zone Issue

  1. I added in mysql config file in section [mysqld]

  2. And restart mysql server:

    sudo service mysql restart

Where +03:00 my UTC time zone.

Path to config file on my os ubuntu 16.04:



My url jdbc connection:


iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

This has happened to me also, after undating to IOS11 on my iPhone. When I try to connect to the corporate network it bring up the corporate cert and says it isn't trusted. I press the 'trust' button and the connection fails and the cert does not appear in the trusted certs list.

Detecting attribute change of value of an attribute I made

You can use MutationObserver to track attribute changes including data-* changes. For example:

var foo = document.getElementById('foo');_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  console.log('data-select-content-val changed');_x000D_
observer.observe(foo, { _x000D_
  attributes: true, _x000D_
  attributeFilter: ['data-select-content-val'] });_x000D_
foo.dataset.selectContentVal = 1;
 <div id='foo'></div>_x000D_

Javascript - Track mouse position

ES6 based code:

let handleMousemove = (event) => {
  console.log(`mouse position: ${event.x}:${event.y}`);

document.addEventListener('mousemove', handleMousemove);

If you need throttling for mousemoving, use this:

let handleMousemove = (event) => {

let throttle = (func, delay) => {
  let prev = - delay;
  return (...args) => {
    let current =;
    if (current - prev >= delay) {
      prev = current;
      func.apply(null, args);

// let's handle mousemoving every 500ms only
document.addEventListener('mousemove', throttle(handleMousemove, 500));

here is example

iOS app 'The application could not be verified' only on one device

As I notice The application could not be verified. raise up because in your device there is already an app installed with the same bundle identifier.

I got this issue because in my device there is my app that download from App store. and i test its update Version from Xcode. And i used same identifier that is live app and my development testing app. So i just remove app-store Live app from my device and this error going to be fix.

Javascript/jQuery: Set Values (Selection) in a multiple Select

var groups = ["Test", "Prof","Off"];

    $('#fruits option').filter(function() {
      return groups.indexOf($(this).text()) > -1; //Options text exists in array
    }).prop('selected', true); //Set selected

Mailx send html message

It's easy, if your mailx command supports the -a (append header) option:

$ mailx -a 'Content-Type: text/html' -s "my subject" [email protected] < email.html

If it doesn't, try using sendmail:

# create a header file
$ cat mailheader
To: [email protected]
Subject: my subject
Content-Type: text/html

# send
$ cat mailheader email.html | sendmail -t

Extract column values of Dataframe as List in Apache Spark

List<String> whatever_list = df.toJavaRDD().map(new Function<Row, String>() {
    public String call(Row row) {
        return row.getAs("column_name").toString();
}).collect();"list is %s",whatever_list)); //verification

Since no one has given any solution in java(Real Programming Language) Can thank me later

What are the most useful Intellij IDEA keyboard shortcuts?

Ctrl + F11 invokes a dialog with all alphanumeric keys on the keyboard. Selecting one empty will add the current line to bookmarks and mark the line with selected key.

Shift + F11 invokes a list of bookmarks. Pressing a key takes to associated bookmark.

Python exit commands - why so many and when should each be used?

Let me give some information on them:

  1. quit() simply raises the SystemExit exception.

    Furthermore, if you print it, it will give a message:

    >>> print (quit)
    Use quit() or Ctrl-Z plus Return to exit

    This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.

    Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.

  2. exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.

    Furthermore, it too gives a message when printed:

    >>> print (exit)
    Use exit() or Ctrl-Z plus Return to exit

    However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.

  3. sys.exit() also raises the SystemExit exception. This means that it is the same as quit and exit in that respect.

    Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.

  4. os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.

    Note that, of the four methods given, only this one is unique in what it does.

Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.

Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:

raise SystemExit

This way, you do not need to import sys first.

However, this choice is simply one on style and is purely up to you.

How do I create the small icon next to the website tab for my site?

It is called favicon.ico and you can generate it from this site.

Getting all selected checkboxes in an array

I didnt test it but it should work

<script type="text/javascript">
var selected = new Array();

$(document).ready(function() {

  $("input:checkbox[name=type]:checked").each(function() {



how to change namespace of entire project?

Just right click the solution, go to properties, change "default namespace" under 'Application' section.

enter image description here

Need to get a string after a "word" in a string in c#

add this code to your project

  public static class Extension {
        public static string TextAfter(this string value ,string search) {
            return  value.Substring(value.IndexOf(search) + search.Length);

then use

"code : string text ".TextAfter(":")

Transfer data between databases with PostgreSQL

You can not perform a cross-database query like SQL Server; PostgreSQL does not support this.

The DbLink extension of PostgreSQL is used to connect one database to another database. You have install and configure DbLink to execute a cross-database query.

I have already created a step-by-step script and example for executing cross database query in PostgreSQL. Please visit this post: PostgreSQL [Video]: Cross Database Queries using the DbLink Extension

AngularJS sorting by property

It's pretty easy, just do it like this

$scope.props = [{order:"1"},{order:"5"},{order:"2"}]

ng-repeat="prop in props | orderBy:'order'"

How to split one text file into multiple *.txt files?

Try something like this:

awk -vc=1 'NR%1000000==0{++c}{print $0 > c".txt"}' Datafile.txt

for filename in *.txt; do mv "$filename" "Prefix_$filename"; done;

how to set value of a input hidden field through javascript?

For me it works:

document.getElementById("checkyear").value = "1";

Maybe your JS is not executed and you need to add a function() {} around it all.

Grouping switch statement cases together?

You can't remove keyword case. But your example can be written shorter like this:

switch ((Answer - 1) / 4)                                      
   case 0:
      cout << "You need more cars.";
   case 1:
      cout << "Now you need a house.";
      cout << "What are you? A peace-loving hippie freak?";

How do we control web page caching, across all browsers?

Not sure if my answer sounds simple and stupid, and perhaps it has already been known to you since long time ago, but since preventing someone from using browser back button to view your historical pages is one of your goals, you can use:


Of course, this may not be possible to be implemented across the entire site, but at least for some critical pages, you can do that. Hope this helps.

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

For me, it's working with this:

BigDecimal a = new BigDecimal("9999999999.6666",precision);
BigDecimal b = new BigDecimal("21",precision);


Elegant solution for line-breaks (PHP)

in php line breaks we can use PHP_EOL (END of LINE) .it working as "\n" but it cannot be shown on the ht ml page .because we have to give HTML break to break the Line..

so you can use it using define

define ("EOL","<br>");

then you can call it

How can I get a vertical scrollbar in my ListBox?

Scroll Bar is added to the List box automatically unless its visibility is set to Hidden. Whenever the size of List Items exceeds the one, which can be shown inside a list box vertical or horizontal list box can be seen during the run time.

How to import a JSON file in ECMAScript 6?

A bit late, but I just stumbled across the same problem while trying to provide analytics for my web app that involved sending app version based on the package.json version.

Configuration is as follows: React + Redux, Webpack 3.5.6

The json-loader isn't doing much since Webpack 2+, so after some fiddling with it, I ended up removing it.

The solution that actually worked for me, was simply using fetch. While this will most probably enforce some code changes to adapt to the async approach, it worked perfectly, especially given the fact that fetch will offer json decoding on the fly.

So here it is:

  .then(resp => resp.json())
  .then((packageJson) => {

Do keep in mind, that since we're talking about package.json specifically here, the file will not usually come bundled in your production build (or even dev for that matter), so you will have to use the CopyWebpackPlugin to have access to it when using fetch.

Handlebars.js Else If

I usually use this form:

{{#if FriendStatus.IsFriend}}
{{else}} {{#if FriendStatus.FriendRequested}}

Get hours difference between two dates in Moment Js

If you want total minutes between two dates in day wise than may below code will help full to you Start Date : 2018-05-04 02:08:05 , End Date : 2018-05-14 09:04:07...

function countDaysAndTimes(startDate,endDate){
return new Promise(function (resolve, reject) {
var dayObj = new Object;
var finalArray = new Array;

var datetime1 = moment(startDate);
var datetime2 = moment(endDate);
if(datetime1.format('D') != datetime2.format('D') || datetime1.format('M') != datetime2.format('M') ||  datetime1.format('YYYY') != datetime2.format('YYYY')){
  var onlyDate1 = startDate.split(" ");
  var onlyDate2 = endDate.split(" ");
  var totalDays = moment(onlyDate2[0]).diff(moment(onlyDate1[0]), 'days')

  // First Day Entry
  dayObj.startDate = startDate;
  dayObj.endDate = moment(onlyDate1[0]).add(1, 'day').format('YYYY-MM-DD')+" 00:00:00";
  dayObj.minutes = moment(dayObj.endDate).diff(moment(dayObj.startDate), 'minutes');

  // Between Days Entry
  var i = 1;
  if(totalDays > 1){
    for(i=1; i<totalDays; i++){
      var dayObj1 = new Object;
      dayObj1.startDate = moment(onlyDate1[0]).add(i, 'day').format('YYYY-MM-DD')+" 00:00:00";
      dayObj1.endDate = moment(onlyDate1[0]).add(i+1, 'day').format('YYYY-MM-DD')+" 00:00:00";
      dayObj1.minutes = moment(dayObj1.endDate).diff(moment(dayObj1.startDate), 'minutes');

  // Last Day Entry
  var dayObj2 = new Object;
  dayObj2.startDate = moment(onlyDate1[0]).add(i, 'day').format('YYYY-MM-DD')+" 00:00:00";
  dayObj2.endDate = endDate ;
  dayObj2.minutes = moment(dayObj2.endDate).diff(moment(dayObj2.startDate), 'minutes');

  dayObj.startDate = startDate;
  dayObj.endDate = endDate;
  dayObj.minutes = datetime2.diff(datetime1, 'minutes');
// console.table(finalArray);


  "startDate":"2018-05-04 02:08:05",
  "endDate":"2018-05-05 00:00:00",
  "startDate":"2018-05-05 00:00:00",
  "endDate":"2018-05-06 00:00:00",
  "startDate":"2018-05-06 00:00:00",
  "endDate":"2018-05-07 00:00:00",
  "startDate":"2018-05-07 00:00:00",
  "endDate":"2018-05-08 00:00:00",
  "startDate":"2018-05-08 00:00:00",
  "endDate":"2018-05-09 00:00:00",
  "startDate":"2018-05-09 00:00:00",
  "endDate":"2018-05-10 00:00:00",
  "startDate":"2018-05-10 00:00:00",
  "endDate":"2018-05-11 00:00:00",
  "startDate":"2018-05-11 00:00:00",
  "endDate":"2018-05-12 00:00:00",
  "startDate":"2018-05-12 00:00:00",
  "endDate":"2018-05-13 00:00:00",
  "startDate":"2018-05-13 00:00:00",
  "endDate":"2018-05-14 00:00:00",
  "startDate":"2018-05-14 00:00:00",
  "endDate":"2018-05-14 09:04:07",

Warning: Cannot modify header information - headers already sent by ERROR

Check something with echo, print() or printr() in the include file, header.php.

It might be that this is the problem OR if any MVC file, then check the number of spaces after ?>. This could also make a problem.

Java ArrayList copy

Yes, assignment will just copy the value of l1 (which is a reference) to l2. They will both refer to the same object.

Creating a shallow copy is pretty easy though:

List<Integer> newList = new ArrayList<>(oldList);

(Just as one example.)

How do I get logs/details of ansible-playbook module executions?

There is also other way to generate log file.

Before running ansible-playbook run the following commands to enable logging:

  • Specify the location for the log file.

    export ANSIBLE_LOG_PATH=~/ansible.log

  • Enable Debug

    export ANSIBLE_DEBUG=True

  • To check that generated log file.


Find the IP address of the client in an SSH session

You can get it in a programmatic way via an SSH library (

public static String getIpAddress() throws TaskExecFailException{
    ConnBean cb = new ConnBean(host, username, password);
    SSHExec ssh = SSHExec.getInstance(cb);
    CustomTask sampleTask = new ExecCommand("echo \"${SSH_CLIENT%% *}\"");
    String Result = ssh.exec(sampleTask).sysout;
    return Result;

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:


      if ($(this).scrollTop() > 135) {
      } else {


.fixed {position:fixed; top:0; left:0;}


How can I put strings in an array, split by new line?

PHP already knows the current system's newline character(s). Just use the EOL constant.


How can I define an array of objects?

What you have above is an object, not an array.

To make an array use [ & ] to surround your objects.

userTestStatus = [
  { "id": 0, "name": "Available" },
  { "id": 1, "name": "Ready" },
  { "id": 2, "name": "Started" }

Aside from that TypeScript is a superset of JavaScript so whatever is valid JavaScript will be valid TypeScript so no other changes are needed.

Feedback clarification from OP... in need of a definition for the model posted

You can use the types defined here to represent your object model:

type MyType = {
    id: number;
    name: string;

type MyGroupType = {
    [key:string]: MyType;

var obj: MyGroupType = {
    "0": { "id": 0, "name": "Available" },
    "1": { "id": 1, "name": "Ready" },
    "2": { "id": 2, "name": "Started" }
// or if you make it an array
var arr: MyType[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }

In android how to set navigation drawer header image and name programmatically in class file?

In Kotlin

    val hView = nav_view.getHeaderView(0)
    val textViewName = hView.findViewById( as TextView
    val textViewEmail = hView.findViewById( as TextView
    val imgvw = hView.findViewById( as ImageView

How do I align a label and a textarea?

Try setting a height on your td elements.

vertical-align: middle; 

means the element the style is applied to will be aligned within the parent element. The height of the td may be only as high as the text inside.

How to have an auto incrementing version number (Visual Studio)?

You could use the T4 templating mechanism in Visual Studio to generate the required source code from a simple text file :

I wanted to configure version information generation for some .NET projects. It’s been a long time since I investigated available options, so I searched around hoping to find some simple way of doing this. What I’ve found didn’t look very encouraging: people write Visual Studio add-ins and custom MsBuild tasks just to obtain one integer number (okay, maybe two). This felt overkill for a small personal project.

The inspiration came from one of the StackOverflow discussions where somebody suggested that T4 templates could do the job. And of course they can. The solution requires a minimal effort and no Visual Studio or build process customization. Here what should be done:

  1. Create a file with extension ".tt" and place there T4 template that will generate AssemblyVersion and AssemblyFileVersion attributes:
<#@ template language="C#" #>
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.

using System.Reflection;

[assembly: AssemblyVersion("1.0.1.<#= this.RevisionNumber #>")]
[assembly: AssemblyFileVersion("1.0.1.<#= this.RevisionNumber #>")]
    int RevisionNumber = (int)(DateTime.UtcNow - new DateTime(2010,1,1)).TotalDays;

You will have to decide about version number generation algorithm. For me it was sufficient to auto-generate a revision number that is set to the number of days since January 1st, 2010. As you can see, the version generation rule is written in plain C#, so you can easily adjust it to your needs.

  1. The file above should be placed in one of the projects. I created a new project with just this single file to make version management technique clear. When I build this project (actually I don’t even need to build it: saving the file is enough to trigger a Visual Studio action), the following C# is generated:
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.

using System.Reflection;

[assembly: AssemblyVersion("")]
[assembly: AssemblyFileVersion("")]

Yes, today it’s 113 days since January 1st, 2010. Tomorrow the revision number will change.

  1. Next step is to remove AssemblyVersion and AssemblyFileVersion attributes from AssemblyInfo.cs files in all projects that should share the same auto-generated version information. Instead choose “Add existing item” for each projects, navigate to the folder with T4 template file, select corresponding “.cs” file and add it as a link. That will do!

What I like about this approach is that it is lightweight (no custom MsBuild tasks), and auto-generated version information is not added to source control. And of course using C# for version generation algorithm opens for algorithms of any complexity.

TimePicker Dialog from clicking EditText

public class **Your java Class** extends ActionBarActivity implements  View.OnClickListener{
date = (EditText) findViewById(;
        dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);


private void setDateTimeField() {
        Calendar newCalendar = Calendar.getInstance();
        fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);

        }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));

    public void onClick(View v) {;

parsing a tab-separated file in Python

You can use the csv module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.

Where line is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip() builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):

TypeError: 'float' object is not callable

You have forgotten a * between -3.7 and (prof[x]).


for x in range(len(prof)):
    PB = 2.25 * (1 - math.pow(math.e, (-3.7 * (prof[x])/2.25))) * (math.e, (0/2.25)))

Also, there seems to be missing an ( as I count 6 times ( and 7 times ), and I think (math.e, (0/2.25)) is missing a function call (probably math.pow, but thats just a wild guess).

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

You can use a union:

INSERT INTO dbo.MyTable (ID, Name) 
    SELECT 123, 'Timmy'
    SELECT 124, 'Jonny'
    SELECT 125, 'Sally'
) AS X (ID, Name)

JSON to string variable dump

i personally use the jquery dump plugin alot to dump objects, its a bit similar to php's print_r() function Basic usage:

var obj = {
            hubba: "Some string...",
            bubba: 12.5,
            dubba: ["One", "Two", "Three"]
/* will return:
Object { 
     hubba: "Some string..."
     bubba: 12.5
     dubba: Array ( 
          0 => "One"
          1 => "Two"
          2 => "Three"

Its very human readable, i also recommend this site for creating/parsing/reading json, because it has nice colors

Declaring and using MySQL varchar variables

This works fine for me using MySQL 5.1.35:


DROP PROCEDURE IF EXISTS `example`.`test` $$
CREATE PROCEDURE `example`.`test` ()

  DECLARE FOO varchar(7);
  DECLARE oldFOO varchar(7);
  SET FOO = '138';
  SET oldFOO = CONCAT('0', FOO);

  update mypermits
     set person = FOO
   where person = oldFOO;

END $$



DROP TABLE IF EXISTS `example`.`mypermits`;
CREATE TABLE  `example`.`mypermits` (
  `person` varchar(7) NOT NULL

INSERT INTO mypermits VALUES ('0138');

CALL test()

Add Header and Footer for PDF using iTextsharp

The answers to this question, while they are correct, are very unnecessarily complicated. It doesn't take that much code for text to show up in the header/footer. Here is a simple example of adding text to the header/footer.

The current version of iTextSharp works by implementing a callback class which is defined by the IPdfPageEvent interface. From what I understand, it's not a good idea to add things during the OnStartPage method, so instead I will be using the OnEndPage page method. The events are triggered depending on what is happening to the PdfWriter

First, create a class which implements IPdfPageEvent. In the:

public void OnEndPage(PdfWriter writer, Document document)

function, obtain the PdfContentByte object by calling

PdfContentByte cb = writer.DirectContent;

Now you can add text very easily:

ColumnText ct = new ColumnText(cb);

cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
//Note, (0,0) in this case is at the bottom of the document
cb.SetTextMatrix(document.LeftMargin, document.BottomMargin); 
cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));

So the full for the OnEndPage function will be:

public void OnEndPage(PdfWriter writer, Document document)
    PdfContentByte cb = writer.DirectContent;
    ColumnText ct = new ColumnText(cb);

    cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
    cb.SetTextMatrix(document.LeftMargin, document.BottomMargin);
    cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));


This will show up at the bottom of your document. One last thing. Don't forget to assign the IPdfPageEvent like this:

writter.PageEvent = new PDFEvents();

To the PdfWriter writter object

For the header it is very similar. Just flip the SetTextMatrix y coordinate:

cb.SetTextMatrix(document.LeftMargin, document.PageSize.Height - document.TopMargin);

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

In my case I am using Visual Studio and Nuget packages its failing because have duplicated libraries one in the same folder as jQuery and another in the folder umd. By removing the popper javascript files from the same level as jQuery and refere to the popper.js inside the umd folder fixed my issue and I can see the tooltips correctly.

ERROR Android emulator gets killed

For me it seems it was a problem that OpenGL didn't work on my Windows 10 machine. I fixed it as follows:

  1. Go to: Tools > Android > AVD Manager
  2. Press the "edit" (pencil) icon next to your AVD
  3. Change "Graphics" to "Software".

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

    WHERE YEAR = '2010' AND MONTH = '12'

you can read this article to understand more!

use current date as default value for a column

Right click on the table and click on Design,then click on column that you want to set default value.

Then in bottom of page in column properties set Default value or binding to : 'getdate()'

Converting from longitude\latitude to Cartesian coordinates

Theory for convert GPS(WGS84) to Cartesian coordinates

The following is what I am using:

  • Longitude in GPS(WGS84) and Cartesian coordinates are the same.
  • Latitude need be converted by WGS 84 ellipsoid parameters semi-major axis is 6378137 m, and
  • Reciprocal of flattening is 298.257223563.

I attached a VB code I wrote:

Imports System.Math

'Input GPSLatitude is WGS84 Latitude,h is altitude above the WGS 84 ellipsoid

Public Function GetSphericalLatitude(ByVal GPSLatitude As Double, ByVal h As Double) As Double

        Dim A As Double = 6378137 'semi-major axis 
        Dim f As Double = 1 / 298.257223563  '1/f Reciprocal of flattening
        Dim e2 As Double = f * (2 - f)
        Dim Rc As Double = A / (Sqrt(1 - e2 * (Sin(GPSLatitude * PI / 180) ^ 2)))
        Dim p As Double = (Rc + h) * Cos(GPSLatitude * PI / 180)
        Dim z As Double = (Rc * (1 - e2) + h) * Sin(GPSLatitude * PI / 180)
        Dim r As Double = Sqrt(p ^ 2 + z ^ 2)
        Dim SphericalLatitude As Double =  Asin(z / r) * 180 / PI
        Return SphericalLatitude
End Function

Please notice that the h is altitude above the WGS 84 ellipsoid.

Usually GPS will give us H of above MSL height. The MSL height has to be converted to height h above the WGS 84 ellipsoid by using the geopotential model EGM96 (Lemoine et al, 1998).
This is done by interpolating a grid of the geoid height file with a spatial resolution of 15 arc-minutes.

Or if you have some level professional GPS has Altitude H (msl,heigh above mean sea level) and UNDULATION,the relationship between the geoid and the ellipsoid (m) of the chosen datum output from internal table. you can get h = H(msl) + undulation

To XYZ by Cartesian coordinates:

x = R * cos(lat) * cos(lon)

y = R * cos(lat) * sin(lon)

z = R *sin(lat)

Multiplying across in a numpy array

I've compared the different options for speed and found that – much to my surprise – all options (except diag) are equally fast. I personally use

A * b[:, None]

(or (A.T * b).T) because it's short.

enter image description here

Code to reproduce the plot:

import numpy
import perfplot

def newaxis(data):
    A, b = data
    return A * b[:, numpy.newaxis]

def none(data):
    A, b = data
    return A * b[:, None]

def double_transpose(data):
    A, b = data
    return (A.T * b).T

def double_transpose_contiguous(data):
    A, b = data
    return numpy.ascontiguousarray((A.T * b).T)

def diag_dot(data):
    A, b = data
    return, A)

def einsum(data):
    A, b = data
    return numpy.einsum("ij,i->ij", A, b)
    setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n)),
    n_range=[2 ** k for k in range(13)],
    xlabel="len(A), len(b)",

Print current call stack from a method in Python code

Here's a variation of @RichieHindle's excellent answer which implements a decorator that can be selectively applied to functions as desired. Works with Python 2.7.14 and 3.6.4.

from __future__ import print_function
import functools
import traceback
import sys

INDENT = 4*' '

def stacktrace(func):
    def wrapped(*args, **kwds):
        # Get all but last line returned by traceback.format_stack()
        # which is the line below.
        callstack = '\n'.join([INDENT+line.strip() for line in traceback.format_stack()][:-1])
        print('{}() called:'.format(func.__name__))
        return func(*args, **kwds)

    return wrapped

def test_func():
    return 42


Output from sample:

test_func() called:
    File "", line 28, in <module>

Converting Pandas dataframe into Spark dataframe error

I made this script, It worked for my 10 pandas Data frames

from pyspark.sql.types import *

# Auxiliar functions
def equivalent_type(f):
    if f == 'datetime64[ns]': return TimestampType()
    elif f == 'int64': return LongType()
    elif f == 'int32': return IntegerType()
    elif f == 'float64': return FloatType()
    else: return StringType()

def define_structure(string, format_type):
    try: typo = equivalent_type(format_type)
    except: typo = StringType()
    return StructField(string, typo)

# Given pandas dataframe, it will return a spark's dataframe.
def pandas_to_spark(pandas_df):
    columns = list(pandas_df.columns)
    types = list(pandas_df.dtypes)
    struct_list = []
    for column, typo in zip(columns, types): 
      struct_list.append(define_structure(column, typo))
    p_schema = StructType(struct_list)
    return sqlContext.createDataFrame(pandas_df, p_schema)

You can see it also in this gist

With this you just have to call spark_df = pandas_to_spark(pandas_df)

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

How to generate xsd from wsdl

Once I found an xsd link on the top of the wsdl. Like this wsdl example from the web, you can see a link xsd1. The server has to be running to see it.

<?xml version="1.0"?>
<definitions name="StockQuote"

Errors in pom.xml with dependencies (Missing artifact...)

I know it is an old question. But I hope my answer will help somebody. I had the same issue and I think the problem is that it cannot find those .jar files in your local repository. So what I did is I added the following code to my pom.xml and it worked.

      <name>Spring Milestones</name>

Laravel where on relationship object

The correct syntax to do this on your relations is:

Event::whereHas('participants', function ($query) {
    return $query->where('IDUser', '=', 1);


Create Log File in Powershell

Using this Log-Entry framework:


Function Main {
    Log -File "D:\Apps\Logs\$Env:computername.log"

    $tcp = (get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductVersionRaw
    $dfs = (get-childitem C:\Windows\Microsoft.NET\Framework\v2.0.50727\dfsvc.exe).Versioninfo.ProductVersionRaw

    Log "TCPIP.sys Version on $computer is:" $tcp
    Log "DFSVC.exe Version on $computer is:" $dfs

    If (get-wmiobject win32_share | where-object {$_.Name -eq "REMINST"}) {Log "The REMINST share exists on $computer"}
    Else {Log "The REMINST share DOES NOT exist on $computer - Please create as per standards"}

    "KB2450944", "KB3150513", "KB3176935" | ForEach {
        $hotfix = Get-HotFix -Id $_ -ErrorAction SilentlyContinue
        If ($hotfix) {Log -Color Green Hotfix $_ is installed}
        Else {Log -Color Red Hotfix $_ " is NOT installed - Please ensure you install this hotfix"}

Screen output: Screen output

Log File (at D:\Apps\Logs\<computername>.log):

2017-05-31  Write-Log (version: 01.00.02, PowerShell version: 5.1.14393.1198)
19:19:29.00 C:\Users\User\PowerShell\Write-Log\Check.ps1 
19:19:29.47 TCPIP.sys Version on  is: {Major: 10, Minor: 0, Build: 14393, Revision: 1066, MajorRevision: 0, MinorRevision: 1066}
19:19:29.50 DFSVC.exe Version on  is: {Major: 2, Minor: 0, Build: 50727, Revision: 8745, MajorRevision: 0, MinorRevision: 8745}
19:19:29.60 The REMINST share DOES NOT exist on  - Please create as per standards
Error at 25,13: Cannot find the requested hotfix on the 'localhost' computer. Verify the input and run the command again.
19:19:33.41 Hotfix KB2450944 is NOT installed - Please ensure you install this hotfix
19:19:37.03 Hotfix KB3150513 is installed
19:19:40.77 Hotfix KB3176935 is installed
19:19:40.77 End

Dump Mongo Collection into JSON format

Use mongoexport/mongoimport to dump/restore a collection:

Export JSON File:

mongoexport --db <database-name> --collection <collection-name> --out output.json

Import JSON File:

mongoimport --db <database-name> --collection <collection-name> --file input.json

WARNING mongoimport and mongoexport do not reliably preserve all rich BSON data types because JSON can only represent a subset of the types supported by BSON. As a result, data exported or imported with these tools may lose some measure of fidelity.


BSON is designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.

In addition to compactness, BSON adds additional data types unavailable in JSON, notably the BinData and Date data types.

Application not picking up .css file (flask/python)

In jinja2 templates (which flask uses), use

href="{{ url_for('static', filename='mainpage.css')}}"

The static files are usually in the static folder, though, unless configured otherwise.


This one disables all bogus verbs and only allows GET and POST

      <verbs allowUnlisted="false">
    <add verb="GET" allowed="true"/>
    <add verb="POST" allowed="true"/>

What is special about /dev/tty?

The 'c' means it's a character special file.

Can I have onScrollListener for a ScrollView?

Here's a derived HorizontalScrollView I wrote to handle notifications about scrolling and scroll ending. It properly handles when a user has stopped actively scrolling and when it fully decelerates after a user lets go:

public class ObservableHorizontalScrollView extends HorizontalScrollView {
    public interface OnScrollListener {
        public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY);
        public void onEndScroll(ObservableHorizontalScrollView scrollView);

    private boolean mIsScrolling;
    private boolean mIsTouching;
    private Runnable mScrollingRunnable;
    private OnScrollListener mOnScrollListener;

    public ObservableHorizontalScrollView(Context context) {
        this(context, null, 0);

    public ObservableHorizontalScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    public ObservableHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    public boolean onTouchEvent(MotionEvent ev) {
        int action = ev.getAction();

        if (action == MotionEvent.ACTION_MOVE) {
            mIsTouching = true;
            mIsScrolling = true;
        } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            if (mIsTouching && !mIsScrolling) {
                if (mOnScrollListener != null) {

            mIsTouching = false;

        return super.onTouchEvent(ev);

    protected void onScrollChanged(int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);

        if (Math.abs(oldX - x) > 0) {
            if (mScrollingRunnable != null) {

            mScrollingRunnable = new Runnable() {
                public void run() {
                    if (mIsScrolling && !mIsTouching) {
                        if (mOnScrollListener != null) {

                    mIsScrolling = false;
                    mScrollingRunnable = null;

            postDelayed(mScrollingRunnable, 200);

        if (mOnScrollListener != null) {
            mOnScrollListener.onScrollChanged(this, x, y, oldX, oldY);

    public OnScrollListener getOnScrollListener() {
        return mOnScrollListener;

    public void setOnScrollListener(OnScrollListener mOnEndScrollListener) {
        this.mOnScrollListener = mOnEndScrollListener;


Maven error :Perhaps you are running on a JRE rather than a JDK?

i am using centos and getting same error when run mvn command with goal, install. After some googling i have found the solution to run following command.

sudo yum install java-1.8.0-openjdk-devel

Python xml ElementTree from a string source?

io.StringIO is another option for getting XML into xml.etree.ElementTree:

import io
f = io.StringIO(xmlstring)
tree = ET.parse(f)
root = tree.getroot()

Hovever, it does not affect the XML declaration one would assume to be in tree (although that's needed for ElementTree.write()). See How to write XML declaration using xml.etree.ElementTree.

How to parse a string into a nullable int

I would suggest following extension methods for string parsing into int value with ability to define default value in case parsing is not possible:

public static int ParseInt(this string value, int defaultIntValue = 0)
            return int.TryParse(value, out var parsedInt) ? parsedInt : defaultIntValue;

public static int? ParseNullableInt(this string value)
            if (string.IsNullOrEmpty(value))
                return null;

            return value.ParseInt();

jQuery checkbox checked state changed event

Try this "html-approach" which is acceptable for small JS projects

function msg(animal,is) {
  console.log(animal, is.checked);   // Do stuff
<input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
<input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>

Position a CSS background image x pixels from the right?

I was trying to do a similar task to get a dropdown arrow always on the right side of the table header and came up with this which seemed to work in Chrome and Firefox, but safari was telling me it was an invalid property.

background: url( center right 10px no-repeat;

After doing a bit of messing around in the inspector, I came up with this cross-browser solution that works in IE8+, Chrome, Firefox, and Safari, as well as responsive designs.

background: url( no-repeat 95% center;

Here is a codepen of how it looks and works. Codepen is written with SCSS -

How to store custom objects in NSUserDefaults

On your Player class, implement the following two methods (substituting calls to encodeObject with something relevant to your own object):

- (void)encodeWithCoder:(NSCoder *)encoder {
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.question forKey:@"question"];
    [encoder encodeObject:self.categoryName forKey:@"category"];
    [encoder encodeObject:self.subCategoryName forKey:@"subcategory"];

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        //decode properties, other class vars
        self.question = [decoder decodeObjectForKey:@"question"];
        self.categoryName = [decoder decodeObjectForKey:@"category"];
        self.subCategoryName = [decoder decodeObjectForKey:@"subcategory"];
    return self;

Reading and writing from NSUserDefaults:

- (void)saveCustomObject:(MyObject *)object key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:encodedObject forKey:key];
    [defaults synchronize];


- (MyObject *)loadCustomObjectWithKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *encodedObject = [defaults objectForKey:key];
    MyObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;

Code shamelessly borrowed from: saving class in nsuserdefaults

Java: method to get position of a match in a String?

int match_position=text.indexOf(match);

Date formatting in WPF datagrid

Very late to the party here but in case anyone else stumbles across this page...

You can do it by setting the AutoGeneratingColumn handler in XAML:

<DataGrid AutoGeneratingColumn="OnAutoGeneratingColumn"  ..etc.. />

And then in code behind do something like this:

private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    if (e.PropertyType == typeof(System.DateTime))
        (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";

Display all post meta keys and meta values of the same post ID in wordpress

$myvals = get_post_meta( get_the_ID());
foreach($myvals as $key=>$val){
  foreach($val as $vals){
    if ($key=='Youtube'){
       echo $vals 

Key = Youtube videos all meta keys for youtube videos and value

How do I create 7-Zip archives with .NET?

Install the NuGet package called SevenZipSharp.Interop


var compressor = new SevenZip.SevenZipCompressor();
var filesToCompress = Directory.GetFiles(@"D:\data\");
compressor.CompressFiles(@"C:\archive\abc.7z", filesToCompress);

SQL - How to find the highest number in a column?


$sql = mysql_query("select id from customers order by id desc");
$rs = mysql_fetch_array($sql);
if ( !$rs ) { $newid = 1; } else { $newid = $rs[newid]+1; }

thus $newid = 23 if last record in column id was 22.

There is already an open DataReader associated with this Command which must be closed first

I am using web service in my tool, where those service fetch the stored procedure. while more number of client tool fetches the web service, this problem arises. I have fixed by specifying the Synchronized attribute for those function fetches the stored procedure. now it is working fine, the error never showed up in my tool.

 public static List<t> MyDBFunction(string parameter1)

This attribute allows to process one request at a time. so this solves the Issue.

how to use LIKE with column name


 WHERE ColumnName LIKE '%'+ColumnName+'%'

Android layout replacing a view with another view on run time

private void replaceView(View oldV,View newV){
        ViewGroup par = (ViewGroup)oldV.getParent();
        if(par == null){return;}
        int i1 = par.indexOfChild(oldV);

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

I get the same error when I run Oracle XE instance on the same machine. As my database is Oracle, I preferred changing Glassfish's default port:

  1. Locate domain.xml inside Glassfish installation folders.
  2. Change the the port on the below line:

  <network-listener port="9090" protocol="http-listener-1" transport="tcp" name="http-listener-1" thread-pool="http-thread-pool"></network-listener>_x000D_

How to display a confirmation dialog when clicking an <a> link?

Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:

document.body.onclick = function( e ) {
    // Cross-browser handling
    var evt = e || window.event,
        target = || evt.srcElement;

    // If the element clicked is an anchor
    if ( target.nodeName === 'A' ) {

        // Add the confirm box
        return confirm( 'Are you sure?' );

This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.

Bootstrap modal z-index

I fell into this this with using the JQLayout plugin, especially when using nested layouts and modals with Bootstrap 4.

An overriding css needs to be added to correct the behaviour,

    z-index:inherit !important;

Select the first row by group

A base R option is the split()-lapply() idiom:

>, lapply(split(test, test$id), head, 1))
  id string
1  1      A
2  2      B
3  3      C
4  4      D
5  5      E

A more direct option is to lapply() the [ function:

>, lapply(split(test, test$id), `[`, 1, ))
  id string
1  1      A
2  2      B
3  3      C
4  4      D
5  5      E

The comma-space 1, ) at the end of the lapply() call is essential as this is equivalent of calling [1, ] to select first row and all columns.

Can I add jars to maven 2 build classpath without installing them?

Note: When using the System scope (as mentioned on this page), Maven needs absolute paths.

If your jars are under your project's root, you'll want to prefix your systemPath values with ${basedir}.

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}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
    <input id="name" value="#{name}" />
    ... a few more inputs ... 

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

window.uploadPhotos = function(url){
    // Read in file
    var file =[0];

    // Ensure it's an image
    if(file.type.match(/image.*/)) {
        console.log('An image has been loaded');

        // Load the image
        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            var image = new Image();
            image.onload = function (imageEvent) {

                // 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);
                    type: "imageResized",
                    blob: resizedImage,
                    url: dataUrl
            image.src =;

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) {
    var data = new FormData($("form[id*='uploadImageForm']")[0]);
    if (event.blob && event.url) {
        data.append('image_data', event.blob);

            url: event.url,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(data){
               //handle errors...

Why doesn't [01-12] range work as expected?

A character class in regular expressions, denoted by the [...] syntax, specifies the rules to match a single character in the input. As such, everything you write between the brackets specify how to match a single character.

Your pattern, [01-12] is thus broken down as follows:

  • 0 - match the single digit 0
  • or, 1-1, match a single digit in the range of 1 through 1
  • or, 2, match a single digit 2

So basically all you're matching is 0, 1 or 2.

In order to do the matching you want, matching two digits, ranging from 01-12 as numbers, you need to think about how they will look as text.

You have:

  • 01-09 (ie. first digit is 0, second digit is 1-9)
  • 10-12 (ie. first digit is 1, second digit is 0-2)

You will then have to write a regular expression for that, which can look like this:

  +-- a 0 followed by 1-9
  |      +-- a 1 followed by 0-2
  |      |
<-+--> <-+-->
      +-- vertical bar, this roughly means "OR" in this context

Note that trying to combine them in order to get a shorter expression will fail, by giving false positive matches for invalid input.

For instance, the pattern [0-1][0-9] would basically match the numbers 00-19, which is a bit more than what you want.

I tried finding a definite source for more information about character classes, but for now all I can give you is this Google Query for Regex Character Classes. Hopefully you'll be able to find some more information there to help you.

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

Use BigDecimal.valueOf(double d) instead of new BigDecimal(double d). The last one has precision errors by float and double.

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).


Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:


You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.


Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
        bDate = True
        bValue = True
        bChanged = False
        Dim sVal As String
        Dim dDate As Date
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
        sVal = CStr(inData.Value)
        dDate = Now()
        Set wb = inData.Worksheet.Parent
        Set dProps = wb.CustomDocumentProperties
    On Error Resume Next
        Set pValue = dProps.Item(sName)
        If Err.Number <> 0 Then
            bValue = False
        End If
    On Error GoTo 0
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    On Error Resume Next
        Set pDate = dProps.Item(sNameDate)
        If Err.Number <> 0 Then
            bDate = False
        End If
    On Error GoTo 0
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
        If bChanged Then
            pDate.Value = dDate
            dDate = pDate.Value
        End If
        UDF_Date = dDate
     End Function

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

Ternary operator in AngularJS templates

  <body ng-app="app">
  <button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'"  class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
    <div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
      <div class="panel-heading">Take Quiz</div>
      <div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">

        <button type="button" class="btn btn-default">Start Quiz</button>

Button toggle and change header of button and show/hide div panel. See the Plunkr

How to integrate SAP Crystal Reports in Visual Studio 2017

Please wait Support Pack 21 in September 2017

UPDATE: More info

VS 2017 - Tested opening existing app and it works, CR for VS is not integrated into the app so no new CR projects available- should be fully integrated in SP 21

About release


Moderator Don Williams said:

Not supported yet, I tried to get it into SP 20 but due to time constraints DEV can't get it into VS until SP 21, due out in September time...

Getting the number of filled cells in a column (VBA)

To find the last filled column use the following :

lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

What does "restore purchases" in In-App purchases mean?

You typically restore purchases with this code:

[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];

It will reinvoke -paymentQueue:updatedTransactions on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.

Not all types of In-App purchases can be restored.

Display a jpg image on a JPanel

I would use a Canvas that I add to the JPanel, and draw the image on the Canvas. But Canvas is a quite heavy object, sine it is from awt.

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

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

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

Does this give you a hint?

django no such table:

You can try this!

python migrate --run-syncdb

I have the same problem with Django 1.9 and 1.10. This code works!

jQuery - checkbox enable/disable

<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="chk9[120]" class="chkGroup">
<input type="checkbox" name="chk9[140]" class="chkGroup">
<input type="checkbox" name="chk9[150]" class="chkGroup">

$("#chkAll").click(function() {
   $(".chkGroup").attr("checked", this.checked);

With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:

$(".chkGroup").click(function() {
  $("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;

How does MySQL CASE work?

I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even


The response content cannot be parsed because the Internet Explorer engine is not available, or

It is sure because the Invoke-WebRequest command has a dependency on the Internet Explorer assemblies and are invoking it to parse the result as per default behaviour. As Matt suggest, you can simply launch IE and make your selection in the settings prompt which is popping up at first launch. And the error you experience will disappear.

But this is only possible if you run your powershell scripts as the same windows user as whom you launched the IE with. The IE settings are stored under your current windows profile. So if you, like me run your task in a scheduler on a server as the SYSTEM user, this will not work.

So here you will have to change your scripts and add the -UseBasicParsing argument, as ijn this example: $WebResponse = Invoke-WebRequest -Uri $url -TimeoutSec 1800 -ErrorAction:Stop -Method:Post -Headers $headers -UseBasicParsing

jquery can't get data attribute value

Changing the casing to all lowercases worked for me.

How to sleep for five seconds in a batch file/cmd

If you've got PowerShell on your system, you can just execute this command:

powershell -command "Start-Sleep -s 5"

Edit: people raised an issue where the amount of time powershell takes to start is significant compared to how long you're trying to wait for. If the accuracy of the wait time is important (ie a second or two extra delay is not acceptable), you can use this approach:

powershell -command "$sleepUntil = [DateTime]::Parse('%date% %time%').AddSeconds(5); $sleepDuration = $sleepUntil.Subtract((get-date)).TotalMilliseconds; start-sleep -m $sleepDuration"

This takes the time when the windows command was issued, and the powershell script sleeps until 5 seconds after that time. So as long as powershell takes less time to start than your sleep duration, this approach will work (it's around 600ms on my machine).

How can I search (case-insensitive) in a column using LIKE wildcard?

You don't need to ALTER any table. Just use the following queries, prior to the actual SELECT query that you want to use the wildcard:

    set names `utf8`;
    SET COLLATION_CONNECTION=utf8_general_ci;

Html.Textbox VS Html.TextboxFor

The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

Which characters are valid/invalid in a JSON key name?

It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.


var testObject = {
    "1tile": "test value"
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround

What is __gxx_personality_v0 for?

It is used in the stack unwiding tables, which you can see for instance in the assembly output of my answer to another question. As mentioned on that answer, its use is defined by the Itanium C++ ABI, where it is called the Personality Routine.

The reason it "works" by defining it as a global NULL void pointer is probably because nothing is throwing an exception. When something tries to throw an exception, then you will see it misbehave.

Of course, if nothing is using exceptions, you can disable them with -fno-exceptions (and if nothing is using RTTI, you can also add -fno-rtti). If you are using them, you have to (as other answers already noted) link with g++ instead of gcc, which will add -lstdc++ for you.