Programs & Examples On #Common controls

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I had a mismatch between projects: one with multi-byte character set, the other with Unicode. Correcting these to agree on Unicode corrected the problem.

How to get row index number in R?


This will give you the index of dataframe

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

What is offsetHeight, clientHeight, scrollHeight?

Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :

  • offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.

On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :

  • clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.

ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:

  • scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.

Java synchronized block vs. Collections.synchronizedMap

The way you have synchronized is correct. But there is a catch

  1. Synchronized wrapper provided by Collection framework ensures that the method calls I.e add/get/contains will run mutually exclusive.

However in real world you would generally query the map before putting in the value. Hence you would need to do two operations and hence a synchronized block is needed. So the way you have used it is correct. However.

  1. You could have used a concurrent implementation of Map available in Collection framework. 'ConcurrentHashMap' benefit is

a. It has a API 'putIfAbsent' which would do the same stuff but in a more efficient manner.

b. Its Efficient: dThe CocurrentMap just locks keys hence its not blocking the whole map's world. Where as you have blocked keys as well as values.

c. You could have passed the reference of your map object somewhere else in your codebase where you/other dev in your tean may end up using it incorrectly. I.e he may just all add() or get() without locking on the map's object. Hence his call won't run mutually exclusive to your sync block. But using a concurrent implementation gives you a peace of mind that it can never be used/implemented incorrectly.

Is there a way to catch the back button event in javascript?

Use the hashchange event:

window.addEventListener("hashchange", function(e) {
  // ...

If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.

Bootstrap change carousel height

From Bootstrap 4

    height: 200px;
.carousel-item img{
    height: 200px;

CSS: How to align vertically a "label" and "input" inside a "div"?

a more modern approach would be to use css flex-box.

div {_x000D_
  height: 50px;_x000D_
  background: grey;_x000D_
  display: flex;_x000D_
  align-items: center_x000D_
  <label for='name'>Name:</label>_x000D_
  <input type='text' id='name' />_x000D_

a more complex example... if you have multible elements in the flex flow, you can use align-self to align single elements differently to the specified align...

div {_x000D_
  display: flex;_x000D_
  align-items: center_x000D_
* {_x000D_
  margin: 10px_x000D_
label {_x000D_
  align-self: flex-start_x000D_
  <img src="" />_x000D_
  <input placeholder="Text" type="text" />_x000D_

its also super easy to center horizontally and vertically:

div {_x000D_
  background: grey;_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  <label for='name'>Name:</label>_x000D_
  <input type='text' id='name' />_x000D_

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

Where to find free public Web Services? -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.

Express.js - app.listen vs server.listen

I came with same question but after google, I found there is no big difference :)

From Github

If you wish to create both an HTTP and HTTPS server you may do so with the "http" and "https" modules as shown here.

 * Listen for connections.
 * A node `http.Server` is returned, with this
 * application (which is a `Function`) as its
 * callback. If you wish to create both an HTTP
 * and HTTPS server you may do so with the "http"
 * and "https" modules as shown here:
 *    var http = require('http')
 *      , https = require('https')
 *      , express = require('express')
 *      , app = express();
 *    http.createServer(app).listen(80);
 *    https.createServer({ ... }, app).listen(443);
 * @return {http.Server}
 * @api public

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);

Also if you want to work with see their example

See this

I prefer app.listen() :)

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

I answered a very similar question, and here is a way of doing this :

First, create a file where you would define your animations and export them. Just to make it more clear in your app.component.ts

In the following example, I used a max-height of the div that goes from 0px (when it's hidden), to 500px, but you would change that according to what you need.

This animation uses states (in and out), that will be toggle when we click on the button, which will run the animtion.


import { trigger, state, style, transition,
    animate, group, query, stagger, keyframes
} from '@angular/animations';

export const SlideInOutAnimation = [
    trigger('slideInOut', [
        state('in', style({
            'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
        state('out', style({
            'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
        transition('in => out', [group([
            animate('400ms ease-in-out', style({
                'opacity': '0'
            animate('600ms ease-in-out', style({
                'max-height': '0px'
            animate('700ms ease-in-out', style({
                'visibility': 'hidden'
        transition('out => in', [group([
            animate('1ms ease-in-out', style({
                'visibility': 'visible'
            animate('600ms ease-in-out', style({
                'max-height': '500px'
            animate('800ms ease-in-out', style({
                'opacity': '1'

Then in your app.component, we import the animation and create the method that will toggle the animation state.


import { SlideInOutAnimation } from './animations';

  animations: [SlideInOutAnimation]
export class AppComponent  {
  animationState = 'in';


  toggleShowDiv(divName: string) {
    if (divName === 'divA') {
      this.animationState = this.animationState === 'out' ? 'in' : 'out';

And here is how your app.component.html would look like :

<div class="wrapper">
  <button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
  <div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
  <div class="content">THIS IS CONTENT DIV</div>

slideInOut refers to the animation trigger defined in animations.ts

Here is a StackBlitz example I have created :

Side note : If an error ever occurs and asks you to add BrowserAnimationsModule, just import it in your app.module.ts:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

  imports: [ ..., BrowserAnimationsModule ],

How to save a Python interactive session?

There is a way to do it. Store the file in ~/.pystartup...

# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
# Store the file in ~/.pystartup, and set an environment variable to point
# to it:  "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.

import atexit
import os
import readline
import rlcompleter

historyPath = os.path.expanduser("~/.pyhistory")

def save_history(historyPath=historyPath):
    import readline

if os.path.exists(historyPath):

del os, atexit, readline, rlcompleter, save_history, historyPath

and then set the environment variable PYTHONSTARTUP in your shell (e.g. in ~/.bashrc):

export PYTHONSTARTUP=$HOME/.pystartup

You can also add this to get autocomplete for free:

readline.parse_and_bind('tab: complete')

Please note that this will only work on *nix systems. As readline is only available in Unix platform.

New Array from Index Range Swift

One more variant using extension and argument name range

This extension uses Range and ClosedRange

extension Array {

    subscript (range r: Range<Int>) -> Array {
        return Array(self[r])

    subscript (range r: ClosedRange<Int>) -> Array {
        return Array(self[r])


func testArraySubscriptRange() {
    let arr = ["1", "2", "3"]

    let result = arr[range: 1..<arr.count] as Array

    XCTAssertEqual(["2", "3"], result)

func testArraySubscriptClosedRange() {
    let arr = ["1", "2", "3"]

    let result = arr[range: 1...arr.count - 1] as Array

    XCTAssertEqual(["2", "3"], result)

Create HTML table using Javascript

In the html file there are three input boxes with userid,username,department respectively.

These inputboxes are used to get the input from the user.

The user can add any number of inputs to the page.

When clicking the button the script will enable the debugger mode.

In javascript, to enable the debugger mode, we have to add the following tag in the javascript.


    Tools->Internet Options-->Advanced-->uncheck
    Disable script debugging(Internet Explorer)
    Disable script debugging(Other)

    <html xmlns="" >

    <head runat="server">

    <title>Dynamic Table</title>

    <script language="javascript" type="text/javascript">

    // <!CDATA[

    function CmdAdd_onclick() {

    var newTable,startTag,endTag;

    //Creating a new table

    startTag="<TABLE id='mainTable'><TBODY><TR><TD style=\"WIDTH: 120px\">User ID</TD>
    <TD style=\"WIDTH: 120px\">User Name</TD><TD style=\"WIDTH: 120px\">Department</TD></TR>"



    var trContents;

    //Get the row contents








    // Add previous rows







    //Add the Latest row

    newTable+="<TR><TD style=\"WIDTH: 120px\" >" +
        document.getElementById('userid').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('username').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('department').value +"</TD><TR>";


    //Update the Previous Table With New Table.



    // ]]>




    <form id="form1" runat="server">


    <br />


    <input id="userid" type="text" /><br />


    <input id="username" type="text" /><br />


    <input id="department" type="text" />


    <input id="CmdAdd" type="button" value="Add" onclick="return CmdAdd_onclick()" />


    <div id="tableDiv" style="text-align:center" >

    <table id="mainTable">

    <tr style="width:120px " >

    <td >User ID</td>

    <td>User Name</td>








Return HTTP status code 201 in flask

Ripping off Luc's comment here, but to return a blank response, like a 201 the simplest option is to use the following return in your route.

return "", 201

So for example:

    @app.route('/database', methods=["PUT"])
    def database():
        return "", 201

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

javascript date to string

Relying on JQuery Datepicker, but it could be done easily:

var mydate = new Date();
$.datepicker.formatDate('yy-mm-dd', mydate);

Implementing SearchView in action bar

If anyone else is having a nullptr on the searchview variable, I found out that the item setup is a tiny bit different:





pre-android x:


For more information, it's updated documentation is located here.

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

maybe you forget to add parameter dataType:'json' in your $.ajax

   type: "POST",
   dataType: "json",
   url: url,
   data: { get_member: id },
   success: function( response ) 
     //some action here
   error: function( error )
     alert( error );

How to see full query from SHOW PROCESSLIST

Show Processlist fetches the information from another table. Here is how you can pull the data and look at 'INFO' column which contains the whole query :

select * from INFORMATION_SCHEMA.PROCESSLIST where db = 'somedb';

You can add any condition or ignore based on your requirement.

The output of the query is resulted as :

| ID    | USER | HOST            | DB     | COMMAND | TIME | STATE     | INFO                                                     |
|     5 | ssss | localhost:41060 | somedb | Sleep   |    3 |           | NULL                                                     |
| 58169 | root | localhost       | somedb | Query   |    0 | executing | select * from sometable where tblColumnName = 'someName' |

jquery change button color onclick


Use class, Demo:-


if you want to toggle the color each click, you can try this:-



Updated answer for your comment.


How to have multiple colors in a Windows batch file?

If you have a modern Windows (that has powershell installed), the following may work fine as well

call :PrintBright Something Something

  (do actual batch stuff here)

call :PrintBright Done!
goto :eof

powershell -Command Write-Host "%*" -foreground "White"

Adjust the color as you see fit.

How to clear mysql screen console in windows?

just type \system cls

took me a couple hours to get it jejej

Force LF eol in git repo and working copy

Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)

Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....

However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.

As you're partially working on Linux and Windows, make sure core.eol is set to native and core.autocrlf is set to true.

Then, replace the content of your .gitattributes file with the following

* text=auto

This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.

However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.

Provided you work on a C based image processing project, replace the content of your .gitattributes file with the following

* text=auto
*.txt text
*.c text
*.h text
*.jpg binary

This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.

In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.

As a real world example, you can also peek at this commit where those changes to a .gitattributes file are demonstrated.

UPDATE to the answer considering the following comment

I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory

Makes sense. Thanks for the clarification. In this specific context, the .gitattributes file by itself won't be enough.

Run the following commands against your repository

$ git config core.eol lf
$ git config core.autocrlf input

As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol will make sure text files bear LF line endings on checkouts. core.autocrlf will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.

Optionally, you can help Git distinguish what is a text file by creating a .gitattributes file containing something similar to the following:

# Autodetect text files
* text=auto

# ...Unless the name matches the following
# overriding patterns

# Definitively text files 
*.txt text
*.c text
*.h text

# Ensure those won't be messed up with
*.jpg binary
*.data binary

If you decided to create a .gitattributes file, commit it.

Lastly, ensure git status mentions "nothing to commit (working directory clean)", then perform the following operation

$ git checkout-index --force --all

This will recreate your files in your working directory, taking into account your config changes and the .gitattributes file and replacing any potential overlooked CRLF in your text files.

Once this is done, every text file in your working directory WILL bear LF line endings and git status should still consider the workdir as clean.

jQuery changing style of HTML element

Use this:

$('#navigation ul li').css('display', 'inline-block');

Also, as others have stated, if you want to make multiple css changes at once, that's when you would add the curly braces (for object notation), and it would look something like this (if you wanted to change, say, 'background-color' and 'position' in addition to 'display'):

$('#navigation ul li').css({'display': 'inline-block', 'background-color': '#fff', 'position': 'relative'}); //The specific CSS changes after the first one, are, of course, just examples.

Alternative Windows shells, besides CMD.EXE?

  1. Hard to copy and paste.

    Not true. Enable QuickEdit, either in the properties of the shortcut, or in the properties of the CMD window (right-click on the title bar), and you can mark text directly. Right-click copies marked text into the clipboard. When no text is marked, a right-click pastes text from the clipboard.

    enter image description here

  2. Hard to resize the window.

    True. Console2 (see below) does not have this limitation.

  3. Hard to open another window (no menu options do this).

    Not true. Use start cmd or define an alias if that's too much hassle:

    doskey nw=start cmd /k $*
  4. Seems to always start in C:\Windows\System32, which is super useless.

    Not true. Or rather, not true if you define a start directory in the properties of the shortcut

    enter image description here

    or by modifying the AutoRun registry value. Shift-right-click on a folder allows you to launch a command prompt in that folder.

  5. Weird scrolling. Sometimes it scrolls down really far into blank space, and you have to scroll up to where the window is actually populated

    Never happened to me.

An alternative to plain CMD is Console2, which uses CMD under the hood, but provides a lot more configuration options.

How to modify the nodejs request default timeout time?

With the latest NodeJS you can experiment with this monkey patch:

const http = require("http");
const originalOnSocket = http.ClientRequest.prototype.onSocket;
require("http").ClientRequest.prototype.onSocket = function(socket) {
    const that = this;
    socket.setTimeout(this.timeout ? this.timeout : 3000);
    socket.on('timeout', function() {
    });, socket);

How to revert a "git rm -r ."?


Since git rm . deletes all files in this and child directories in the working checkout as well as in the index, you need to undo each of these changes:

git reset HEAD . # This undoes the index changes
git checkout .   # This checks out files in this and child directories from the HEAD

This should do what you want. It does not affect parent folders of your checked-out code or index.

Old answer that wasn't:

reset HEAD

will do the trick, and will not erase any uncommitted changes you have made to your files.

after that you need to repeat any git add commands you had queued up.

JQuery addclass to selected div, remove class if another div is selected

You can use a single line to add and remove class on a div. Please remove a class first to add a new class.


How do you plot bar charts in gnuplot?

I would just like to expand upon the top answer, which uses GNUPlot to create a bar graph, for absolute beginners because I read the answer and was still confused from the deluge of syntax.

We begin by writing a text file of GNUplot commands. Lets call it commands.txt:

set term png
set output "graph.png"
set boxwidth 0.5
set style fill solid
plot "data.dat" using 1:3:xtic(2) with boxes

set term png will set GNUplot to output a .png file and set output "graph.png" is the name of the file it will output to.

The next two lines are rather self explanatory. The fifth line contains a lot of syntax.

plot "data.dat" using 1:3:xtic(2) with boxes

"data.dat" is the data file we are operating on. 1:3 indicates we will be using column 1 of data.dat for the x-coordinates and column 3 of data.dat for the y-coordinates. xtic() is a function that is responsible for numbering/labeling the x-axis. xtic(2), therefore, indicates that we will be using column 2 of data.dat for labels.

"data.dat" looks like this:

0 label       100
1 label2      450
2 "bar label" 75

To plot the graph, enter gnuplot commands.txt in terminal.

.NET Console Application Exit Event

The application is a server which simply runs until the system shuts down or it receives a Ctrl+C or the console window is closed.

Due to the extraordinary nature of the application, it is not feasible to "gracefully" exit. (It may be that I could code another application which would send a "server shutdown" message but that would be overkill for one application and still insufficient for certain circumstances like when the server (Actual OS) is actually shutting down.)

Because of these circumstances I added a "ConsoleCtrlHandler" where I stop my threads and clean up my COM objects etc...

Public Declare Auto Function SetConsoleCtrlHandler Lib "kernel32.dll" (ByVal Handler As HandlerRoutine, ByVal Add As Boolean) As Boolean

Public Delegate Function HandlerRoutine(ByVal CtrlType As CtrlTypes) As Boolean

Public Enum CtrlTypes
End Enum

Public Function ControlHandler(ByVal ctrlType As CtrlTypes) As Boolean
.clean up code here
End Function

Public Sub Main()
SetConsoleCtrlHandler(New HandlerRoutine(AddressOf ControlHandler), True)
End Sub

This setup seems to work out perfectly. Here is a link to some C# code for the same thing.

Prevent form redirect OR refresh on submit?

If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):

<input name="o" required="required" aria-required="true" type="text">

You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:

$('form').on('submit', function(event) {
   my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment

As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.

So if you want to get rid of these default pop-ups, use the click event on the submit button:

$('form input[type=submit]').on('click', function(event) {
   my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

Remove ListView items in Android

You can also use listView.setOnItemLongClickListener to delete selected item. Below is the code.

// listView = name of your ListView

  listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int 
        position, long id) {

        // it will get the position of selected item from the ListView

final int selected_item = position;

            new AlertDialog.Builder(MainActivity.this).
                    .setTitle("Are you sure...")
                    .setMessage("Do you want to delete the selected item..?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which)
                    .setNegativeButton("No" , null).show();

            return true;

Set cookie and get cookie with JavaScript

Check JavaScript Cookies on for setting and getting cookie values via JS.

Just use the setCookie and getCookie methods mentioned there.

So, the code will look something like:

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);

function cssSelected() {
    var cssSelected = $('#myList')[0].value;
    if (cssSelected !== "select") {
        setCookie("selectedCSS", cssSelected, 3);

$(document).ready(function() {
    $('#myList')[0].value = getCookie("selectedCSS");
<select id="myList" onchange="cssSelected();">
    <option value="select">--Select--</option>
    <option value="style-1.css">CSS1</option>
    <option value="style-2.css">CSS2</option>
    <option value="style-3.css">CSS3</option>
    <option value="style-4.css">CSS4</option>

How to compile without warnings being treated as errors?

Sure, find where -Werror is set and remove that flag. Then warnings will be only warnings.

How to force a UIViewController to Portrait orientation in iOS 6

I have a very good approach mixing and

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    NSUInteger orientations = UIInterfaceOrientationMaskAllButUpsideDown;

        UIViewController *presentedViewController = [self topViewControllerWithRootViewController:self.window.rootViewController];
        orientations = [presentedViewController supportedInterfaceOrientations];

    return orientations;

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;

and return whatever orientations you want to support for each UIViewController

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;

How to get status code from webclient?

Just in case someone else needs an F# version of the above described hack.

open System
open System.IO
open System.Net

type WebClientEx() =
     inherit WebClient ()
     [<DefaultValue>] val mutable m_Resp : WebResponse

     override x.GetWebResponse (req: WebRequest ) =
        x.m_Resp <- base.GetWebResponse(req)
        (req :?> HttpWebRequest).AllowAutoRedirect <- false;

     override x.GetWebResponse (req: WebRequest , ar: IAsyncResult  ) =
        x.m_Resp <- base.GetWebResponse(req, ar)
        (req :?> HttpWebRequest).AllowAutoRedirect <- false;

     member x.StatusCode with get() : HttpStatusCode = 
            if not (obj.ReferenceEquals (x.m_Resp, null)) && x.m_Resp.GetType() = typeof<HttpWebResponse> then
                (x.m_Resp :?> HttpWebResponse).StatusCode

let wc = new WebClientEx()
let st = wc.OpenRead("")
let sr = new StreamReader(st)
let res = sr.ReadToEnd()

Java synchronized method lock on object, or method?

Yes, it will block the other method because synchronized method applies to the WHOLE class object as pointed .... but anyway it will block the other thread execution ONLY while performing the sum in whatever method addA or addB it enters, because when it finish ... the one thread will FREE the object and the other thread will access the other method and so on perfectly working.

I mean the "synchronized" is made precisely for blocking the other thread from accessing another while in a specific code execution. SO FINALLY THIS CODE WILL WORK FINE.

As a final note, if there is an 'a' and 'b' variables, not just an unique variable 'a' or whatever other name, there is no need to synchronize this methods cause it is perfectly safe accesing other var (Other memory location).

class X {

private int a;
private int b;

public void addA(){

public void addB(){

Will work as well

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()


level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

Sending mass email using PHP

I already did it using Lotus Notus and PHP.

This solution works if you have access to the mail server or you can request something to the mail server Administrator:

1) Create a group in the mail server: Sales Department

2) Assign to the group the accounts you need to be in the group

3) Assign an internet address to the group: [email protected]

4) Create your PHP script using the mail function:

$to = "[email protected]";
mail($to, $subject, $message, $headers);

It worked for me and all the accounts included in the group receive the mail.

The best of the lucks.

Exiting out of a FOR loop in a batch file?

Based on Tim's second edit and this page you could do this:

@echo off
if "%1"=="loop" (
  for /l %%f in (1,1,1000000) do (
    echo %%f
    if exist %%f exit
  goto :eof
cmd /v:on /q /d /c "%0 loop"
echo done

This page suggests a way to use a goto inside a loop, it seems it does work, but it takes some time in a large loop. So internally it finishes the loop before the goto is executed.

PHP write file from input to txt

The problems you have are because of the extra <form> you have, that your data goes in GET method, and you are accessing the data in PHP using POST.

    <form action="myprocessingscript.php" method="POST">

How do I limit the number of returned items?

Find parameters

The parameters find function takes are as follows:

  1. conditions «Object».
  2. [projection] «Object|String» optional fields to return, see
  3. [options] «Object» optional see Query.prototype.setOptions()
  4. [callback] «Function»

How to limit

const Post = require('./models/Post');

  { published: true }, 
  { sort: { 'date': 'asc' }, limit: 20 },
  function(error, posts) {
   if (error) return `${error} while finding from post collection`;

   return posts; // posts with sorted length of 20

Extra Info

Mongoose allows you to query your collections in different ways like: Official Documentation

// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});

// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })

// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })

// passing options and executes
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});

// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});

// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

How to frame two for loops in list comprehension python

The best way to remember this is that the order of for loop inside the list comprehension is based on the order in which they appear in traditional loop approach. Outer most loop comes first, and then the inner loops subsequently.

So, the equivalent list comprehension would be:

[entry for tag in tags for entry in entries if tag in entry]

In general, if-else statement comes before the first for loop, and if you have just an if statement, it will come at the end. For e.g, if you would like to add an empty list, if tag is not in entry, you would do it like this:

[entry if tag in entry else [] for tag in tags for entry in entries]

Position an element relative to its container

You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:

    position: relative;
    left: 0px;  /* stick it wherever it was positioned by default */
    top: 0px;

    position: absolute;
    left: 10px;
    top: 10px;

Change Oracle port from port 8080

Login in with System Admin User Account and execute below SQL Procedure.

dbms_xdb.sethttpport('Your Port Number');

Then open the Browser and access the below URL

Sending email from Command-line via outlook without having to click send

Send SMS/Text Messages from Command Line with VBScript!

If VBA meets the rules for VB Script then it can be called from command line by simply placing it into a text file - in this case there's no need to specifically open Outlook.

I had a need to send automated text messages to myself from the command line, so I used the code below, which is just a compressed version of @Geoff's answer above.

Most mobile phone carriers worldwide provide an email address "version" of your mobile phone number. For example in Canada with Rogers or Chatr Wireless, an email sent to <YourPhoneNumber> will be immediately delivered to your Rogers/Chatr phone as a text message.

* You may need to "authorize" the first message on your phone, and some carriers may charge an additional fee for theses message although as far as I know, all Canadian carriers provide this little-known service for free. Check your carrier's website for details.

There are further instructions and various compiled lists of worldwide carrier's Email-to-Text addresses available online such as this and this and this.

Code & Instructions

  1. Copy the code below and paste into a new file in your favorite text editor.
  2. Save the file with any name with a .VBS extension, such as TextMyself.vbs.

That's all!
Just double-click the file to send a test message, or else run it from a batch file using START.

Sub SendMessage()
    Const EmailToSMSAddy = "[email protected]"
    Dim objOutlookRecip
    With CreateObject("Outlook.Application").CreateItem(0)
        Set objOutlookRecip = .Recipients.Add(EmailToSMSAddy)
        objOutlookRecip.Type = 1
        .Subject = "The computer needs your attention!"
        .Body = "Go see why Windows Command Line is texting you!"
    End With
End Sub

Example Batch File Usage:

START x:\mypath\TextMyself.vbs

Of course there are endless possible ways this could be adapted and customized to suit various practical or creative needs.

Uncaught ReferenceError: $ is not defined

If it's in wordpress, might be needed to change

$(document).ready(function() {



or add

var $ = jQuery;


$(document).ready(function() {

How to get local server host and port in Spring Boot?

An easy workaround, at least to get the running port, is to add the parameter javax.servlet.HttpServletRequest in the signature of one of the controller's methods. Once you have the HttpServletRequest instance is straightforward to get the baseUrl with this: request.getRequestURL().toString()

Have a look at this code:

@PostMapping(value = "/registration" , produces = "application/json")
public StringResponse register(@RequestBody RequestUserDTO userDTO, 
    HttpServletRequest request) {
//value: http://localhost:8080/registration
return "";

Directory index forbidden by Options directive

Either the main httpd.conf or the .htaccess file in this directory or a nearby parent directory probably includes:

Options -Indexes

Your host may have to set it to +Indexes if you don't have access in .htaccess and want to list & browse the directory contents, absent a default index.html, index.php, etc. If the directory should not have a default file and you don't enable Indexes, you may only directly target the filenames of contents within it.

The Indexes option is commonly disabled by default on many Apache installations.

Full details are available in the Apache core documentation on Options

Converting XML to JSON using Python?

This stuff here is actively maintained and so far is my favorite: xml2json in python

How to implement infinity in Java?

Since the class Number is not final, here is an idea, that I don't find yet in the other posts. Namely to subclass the class Number.

This would somehow deliver an object that can be treated as infinity for Integer, Long, Double, Float, BigInteger and BigDecimal.

Since there are only two values, we could use the singleton pattern:

public final class Infinity extends Number {
    public final static Infinity POSITIVE = new Infinity(false);
    public final static Infinity NEGATIVE = new Infinity(true);
    private boolean negative;
    private Infinity(boolean n) {
        negative = n;

Somehow I think the remaining methods intValue(), longValue() etc.. should then be overriden to throw an exceptions. So that the infinity value cannot be used without further precautions.

CORS with spring-boot and angularjs not working

Im using spring boot 2.1.0 and what worked for me was to

A. Add cors mappings by:

public class Config implements WebMvcConfigurer {
    public void addCorsMappings(CorsRegistry registry) {

B. Add below configuration to my HttpSecurity for spring security

.cors().configurationSource(new CorsConfigurationSource() {

    public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
        CorsConfiguration config = new CorsConfiguration();
        return config;

Also in case of a Zuul proxy you can use this INSTEAD OF A and B (just use HttpSecurity.cors() to enable it in Spring security):

public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);

How to get current screen width in CSS?

Use the CSS3 Viewport-percentage feature.

Viewport-Percentage Explanation

Assuming you want the body width size to be a ratio of the browser's view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.

<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
        @media screen and (min-width: 480px) {_x000D_
            body {_x000D_
                background-color: skyblue;_x000D_
                width: 90vw;_x000D_
                height: 90vh;_x000D_
                border: groove black;_x000D_
            div#main {_x000D_
                font-size: 3vw;_x000D_
    <div id="main">_x000D_
        Viewport-Percentage Test_x000D_

Private class declaration

You can.

package test;

public class Test {
    public static void main(String[] args) {
        B b = new B();

class B {
  // Essentially package-private - cannot be accessed anywhere else but inside the `test` package

Why doesn't logcat show anything in my Android?

I think, you haven't selected device or emulator , on which running your application,

In eclipse go to DDMS Perspective and select device or emulator on which you are running your application.

(Note: No need to restart the Eclipse)

How do you force a makefile to rebuild a target

The -B switch to make, whose long form is --always-make, tells make to disregard timestamps and make the specified targets. This may defeat the purpose of using make, but it may be what you need.

Transform only one axis to log10 scale with ggplot2

Another solution using scale_y_log10 with trans_breaks, trans_format and annotation_logticks()


m <- ggplot(diamonds, aes(y = price, x = color))

m + geom_boxplot() +
    breaks = scales::trans_breaks("log10", function(x) 10^x),
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  ) +
  theme_bw() +
  annotation_logticks(sides = 'lr') +
  theme(panel.grid.minor = element_blank())

When to use single quotes, double quotes, and backticks in MySQL

(There are good answers above regarding the SQL nature of your question, but this may also be relevant if you are new to PHP.)

Perhaps it is important to mention that PHP handles single and double quoted strings differently...

Single-quoted strings are 'literals' and are pretty much WYSIWYG strings. Double-quoted strings are interpreted by PHP for possible variable-substitution (backticks in PHP are not exactly strings; they execute a command in the shell and return the result).


$foo = "bar";
echo 'there is a $foo'; // There is a $foo
echo "there is a $foo"; // There is a bar
echo `ls -l`; // ... a directory list

create array from mysql query php

You may want to go look at the SQL Injection article on Wikipedia. Look under the "Hexadecimal Conversion" part to find a small function to do your SQL commands and return an array with the information in it.

I wrote the dosql() function because I got tired of having my SQL commands executing all over the place, forgetting to check for errors, and being able to log all of my commands to a log file for later viewing if need be. The routine is free for whoever wants to use it for whatever purpose. I actually have expanded on the function a bit because I wanted it to do more but this basic function is a good starting point for getting the output back from an SQL call.

How to create a folder with name as current date in batch (.bat) files

for /F “tokens=1-4 delims=/ ” %%A in (‘date /t’) do (
    set DateDay=%%A
    set DateMonth=%%B
    set DateYear=%%C
set CurrentDate=%DateDay%-%DateMonth%-%DateYear%
md %CurrentDate%

This will give you a newly created folder with today’s date, in the format of DD-MM-YY

Sourced from: Ali's Knowledge Base

How do I keep the screen on in my App?

No need to add permission and do tricks. Just use below text in your main layout.


a tag as a submit button?

Try this code:

<form id="myform">
  <!-- form elements -->
  <a href="#" onclick="document.getElementById('myform').submit()">Submit</a>

But users with disabled JavaScript won't be able to submit the form, so you could add the following code:

  <input type="submit" value="Submit form!" />

const char* concatenation

First of all, you have to create some dynamic memory space. Then you can just strcat the two strings into it. Or you can use the c++ "string" class. The old-school C way:

  char* catString = malloc(strlen(one)+strlen(two)+1);
  strcpy(catString, one);
  strcat(catString, two);
  // use the string then delete it when you're done.

New C++ way

  std::string three(one);
  three += two;

How do you clear Apache Maven's cache?

As some answers have pointed out, sometimes you really want to delete the local repository entirely, for example, there might be some artifacts that can't be purged as they are not anymore referenced by the pom.

If you want to have this deletion embedded in a maven phase, as for example clean you can use the maven-clean-plugin and access the repository through the settings, for example:

                    <echo>Base clean is attached to deleting local maven cache</echo>


Tell Ruby Program to Wait some amount of time

I find until very useful with sleep. example:

> time =
> sleep 2.seconds until > time + 10.seconds # breaks when true
# or something like
> sleep 1.seconds until !req.loading # suggested by ohsully

How can I get Apache gzip compression to work?

Try this :

SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript application/x-httpd-php
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip

jQuery Array of all selected checkboxes (by class)

You can use the :checkbox and :checked pseudo-selectors and the .class selector, with that you will make sure that you are getting the right elements, only checked checkboxes with the class you specify.

Then you can easily use the Traversing/map method to get an array of values:

var values = $('input:checkbox:checked.group1').map(function () {
  return this.value;
}).get(); // ["18", "55", "10"]

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Here is how to do a quick check to see if n.fn.init[0] is caused by your DOM-elements not loading in time. Delay your selector function by wrapping it in setTimeout function like this:

function timeout(){ 

    ...your selector function that returns n.fn.init[0] goes here...


setTimeout(timeout, 5000)

This will cause your selector function to execute with a 5 second delay, which should be enough for pretty much anything to load.

This is just a coarse hack to check if DOM is ready for your selector function or not. This is not a (permanent) solution.

The preferred ways to check if the DOM is loaded before executing your function are as follows:

1) Wrap your selector function in

$(document).ready(function(){  ... your selector function...  };

2) If that doesn't work, use DOMContentLoaded

3) Try window.onload, which waits for all the images to load first, so its least preferred

window.onload = function () {  ... your selector function...  }

4) If you are waiting for a library to load that loads in several steps or has some sort of delay of its own, then you might need some complicated custom solution. This is what happened to me with "MathJax" library. This question discusses how to check when MathJax library loaded its DOM elements, if it is of any help.

5) Finally, you can stick with hard-coded setTimeout function, making it maybe 1-3 seconds. This is actually the very least preferred method in my opinion.

This list of fixes is probably far from perfect so everyone is welcome to edit it.

How to deal with page breaks when printing a large HTML table

Well Guys... Most of the Solutions up here didn't worked for. So this is how things worked for me..


     <th style="border:none;height:26px;"></th>
     <th style="border:none;height:26px;"></th>
     <th style="border:1px solid black">ABC</th>
     <th style="border:1px solid black">ABC</th>



The first set of head is used as a dummy one so that there won't be a missing top border in 2nd head(i.e. original head) while page break.

How many characters in varchar(max)

See the MSDN reference table for maximum numbers/sizes.

Bytes per varchar(max), varbinary(max), xml, text, or image column: 2^31-1

There's a two-byte overhead for the column, so the actual data is 2^31-3 max bytes in length. Assuming you're using a single-byte character encoding, that's 2^31-3 characters total. (If you're using a character encoding that uses more than one byte per character, divide by the total number of bytes per character. If you're using a variable-length character encoding, all bets are off.)

Drop primary key using script in SQL Server database

You can look up the constraint name in the sys.key_constraints table:

FROM   sys.key_constraints
WHERE  [type] = 'PK'
       AND [parent_object_id] = Object_id('dbo.Student');

If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:


SELECT @table = N'dbo.Student';

SELECT @sql = 'ALTER TABLE ' + @table 
    + ' DROP CONSTRAINT ' + name + ';'
    FROM sys.key_constraints
    WHERE [type] = 'PK'
    AND [parent_object_id] = OBJECT_ID(@table);

EXEC sp_executeSQL @sql;

This code is from Aaron Bertrand (source).

Rename column SQL Server 2008

It would be a good suggestion to use an already built-in function but another way around is to:

  1. Create a new column with same data type and NEW NAME.
  2. Run an UPDATE/INSERT statement to copy all the data into new column.
  3. Drop the old column.

The benefit behind using the sp_rename is that it takes care of all the relations associated with it.

From the documentation:

sp_rename automatically renames the associated index whenever a PRIMARY KEY or UNIQUE constraint is renamed. If a renamed index is tied to a PRIMARY KEY constraint, the PRIMARY KEY constraint is also automatically renamed by sp_rename. sp_rename can be used to rename primary and secondary XML indexes.

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

If you are running this inside a transaction and a SQL statement before this drops/alters the table you can also get this message.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

How do you execute SQL from within a bash script?

If you do not want to install sqlplus on your server/machine then the following command-line tool can be your friend. It is a simple Java application, only Java 8 that you need in order to you can execute this tool.

The tool can be used to run any SQL from the Linux bash or Windows command line.


java -jar sql-runner-0.2.0-with-dependencies.jar \
     -j jdbc:oracle:thin:@//oracle-db:1521/ORCLPDB1.localdomain \
     -U "SYS as SYSDBA" \
     -P Oradoc_db1 \
      "select 1 from dual"

Documentation is here.

You can download the binary file from here.

Favorite Visual Studio keyboard shortcuts

Ctrl+K, Ctrl+C Comment a block

Ctrl+K, Ctrl+U Uncomment the block

How to show image using ImageView in Android

Drag image from your hard drive to Drawable folder in your project and in code use it like this:

ImageView image;

image = (ImageView) findViewById(;

How to use a variable in the replacement side of the Perl substitution operator?

See THIS previous SO post on using a variable on the replacement side of s///in Perl. Look both at the accepted answer and the rebuttal answer.

What you are trying to do is possible with the s///ee form that performs a double eval on the right hand string. See perlop quote like operators for more examples.

Be warned that there are security impilcations of evaland this will not work in taint mode.

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");

        } catch (Exception e) {

Regular expression for extracting tag attributes

Update (2020), Gyum Fox proposes (note did not exist when I wrote originally this answer)


Applied to:

<a href=test.html class=xyz>
<a href="test.html" class="xyz">
<a href='test.html' class="xyz">
<script type="text/javascript" defer async id="something" onload="alert('hello');"></script>
<img src="test.png">
<img src="a test.png">
<img src=test.png />
<img src=a test.png />
<img src=test.png >
<img src=a test.png >
<img src=test.png alt=crap >
<img src=a test.png alt=crap >

Original answer (2008): If you have an element like

<name attribute=value attribute="value" attribute='value'>

this regex could be used to find successively each attribute name and value


Applied on:

<a href=test.html class=xyz>
<a href="test.html" class="xyz">
<a href='test.html' class="xyz">

it would yield:

'href' => 'test.html'
'class' => 'xyz'

Note: This does not work with numeric attribute values e.g. <div id="1"> won't work.

Edited: Improved regex for getting attributes with no value and values with " ' " inside.

([^\r\n\t\f\v= '"]+)(?:=(["'])?((?:.(?!\2?\s+(?:\S+)=|\2))+.)\2?)?

Applied on:

<script type="text/javascript" defer async id="something" onload="alert('hello');"></script>

it would yield:

'type' => 'text/javascript'
'defer' => ''
'async' => ''
'id' => 'something'
'onload' => 'alert(\'hello\');'

How do emulators work and how are they written?

Something worth taking a look at is Imran Nazar's attempt at writing a Gameboy emulator in JavaScript.

How do I download NLTK data?

I think you must have named the file as (or the folder consists of a file with that name) so change it to any other name and try executing it....

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 

Keyboard shortcut to comment lines in Sublime Text 2

Max OS: If you want to toggle comment multiple individual lines versus block comment an entire selection, you can do multi line edit, shift+cmd+L, then cmd+/ in that sequence.

Apache won't run in xampp

Find out which other service uses port 80.

I have heard skype uses port 80. Check it there isn't another server or database running in the background on port 80.

Two good alternatives to xampp are wamp and easyphp. Out of that, wamp is the most user friendly and it also has a built in tool for checking if port 80 is in use and which service is currently using it.

Or disable iis. It has been known to use port 80 by default.

How to overcome root domain CNAME restrictions?

Thanks to both sipwiz and MrEvil. We developed a PHP script that will parse the URL that the user enters and paste www to the top of it. (e.g. if the customer enters, then it will redirect to So our customer point their root (e.g. to A record where our web redirector is) and then www CNAME to the real A record managed by us.

Below the code in case you are interested for future us.

$url = strtolower($_SERVER["HTTP_HOST"]);

if(strpos($url, "//") !== false) { // remove http://
  $url = substr($url, strpos($url, "//") + 2);

$urlPagePath = "";
if(strpos($url, "/") !== false) { // store post-domain page path to append later
  $urlPagePath = substr($url, strpos($url, "/"));
  $url = substr($url, 0, strpos($url,"/"));

$urlLast = substr($url, strrpos($url, "."));
$url = substr($url, 0, strrpos($url, "."));

if(strpos($url, ".") !== false) { // get rid of subdomain(s)
  $url = substr($url, strrpos($url, ".") + 1);

$url = "http://www." . $url . $urlLast . $urlPagePath;

header( "Location:{$url}");

Path.Combine absolute with relative path strings

Path.GetFullPath() does not work with relative paths.

Here's the solution that works with both relative + absolute paths. It works on both Linux + Windows and it keeps the .. as expected in the beginning of the text (at rest they will be normalized). The solution still relies on Path.GetFullPath to do the fix with a small workaround.

It's an extension method so use it like text.Canonicalize()

/// <summary>
///     Fixes "../.." etc
/// </summary>
public static string Canonicalize(this string path)
    if (path.IsAbsolutePath())
        return Path.GetFullPath(path);
    var fakeRoot = Environment.CurrentDirectory; // Gives us a cross platform full path
    var combined = Path.Combine(fakeRoot, path);
    combined = Path.GetFullPath(combined);
    return combined.RelativeTo(fakeRoot);
private static bool IsAbsolutePath(this string path)
    if (path == null) throw new ArgumentNullException(nameof(path));
        && !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)
        && !Path.GetPathRoot(path).Equals(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal);
private static string RelativeTo(this string filespec, string folder)
    var pathUri = new Uri(filespec);
    // Folders must end in a slash
    if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) folder += Path.DirectorySeparatorChar;
    var folderUri = new Uri(folder);
    return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString()
        .Replace('/', Path.DirectorySeparatorChar));

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 =
flt = lrg[lrg==0]
print - t0

t0 =
flt = np.array(filter(lambda x:x==0, lrg))
print - t0

I got

$ python

How to remove trailing whitespaces with sed?

At least on Mountain Lion, Viktor's answer will also remove the character 't' when it is at the end of a line. The following fixes that issue:

sed -i '' -e's/[[:space:]]*$//' "$1"

How to extract a string between two delimiters

  String s = "ABC[This is to extract]";

    int startIndex = s.indexOf('[');
    System.out.println("indexOf([) = " + startIndex);
    int endIndex = s.indexOf(']');
    System.out.println("indexOf(]) = " + endIndex);
    System.out.println(s.substring(startIndex + 1, endIndex));

C# compiler error: "not all code paths return a value"

class Program
    double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
    double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
    double[] result;

    public double[] CheckSorting()
        for(int i = 1; i < a.Length; i++)
            if (a[i] < a[i - 1])
                result = b;
                result = a;
        return result;

    static void Main(string[] args)
        Program checkSorting = new Program();

This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true

Get program path in VB.NET?

You can get path by this code

Dim CurDir as string = My.Application.Info.DirectoryPath

GUI Tool for PostgreSQL

Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.

Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.

Nodemailer with Gmail and NodeJS

I had the same problem. Allowing "less secure apps" in my Google security settings made it work!

Unable to install packages in latest version of RStudio and R Version.3.1.1

I think this is the "set it and forget it" solution:


Note that this isn't https. I was on a Linux machine, ssh'ing in. If I used https, it didn't work.

Change the Textbox height?


  1. Set the textboxes to multiline
  2. Change the height
  3. Change the font size. (so it fit into the big textboxes)
  4. Set the textboxes back to non-multiline

How to convert POJO to JSON and vice versa?

We can also make use of below given dependency and plugin in your pom file - I make use of maven. With the use of these you can generate POJO's as per your JSON Schema and then make use of code given below to populate request JSON object via src object specified as parameter to gson.toJson(Object src) or vice-versa. Look at the code below:

Gson gson = new GsonBuilder().create();
String payloadStr = gson.toJson(data.getMerchant().getStakeholder_list());

Gson gson2 = new Gson();
Error expectederr = gson2.fromJson(payloadStr, Error.class);

And the Maven settings:



Generate sql insert script from excel worksheet

I think importing using one of the methods mentioned is ideal if it truly is a large file, but you can use Excel to create insert statements:

="INSERT INTO table_name VALUES('"&A1&"','"&B1&"','"&C1&"')"

In MS SQL you can use:


To forego showing all the '1 row affected' comments. And if you are doing a lot of rows and it errors out, put a GO between statements every once in a while

Pushing to Git returning Error Code 403 fatal: HTTP request failed

Try below command using administrator permission. This command solved my issue. Hope it will resolve your problem.

git config --system --unset-all credential.helper

Lining up labels with radio buttons in bootstrap

Key insights for me were: - ensure that label content comes after the input-radio field - I tweaked my css to make everything a little closer {
    margin-left: 5px;

Convert seconds to hh:mm:ss in Python

Not being a Python person, but the easiest without any libraries is just:

total   = 3800
seconds = total % 60
total   = total - seconds
hours   = total / 3600
total   = total - (hours * 3600)
mins    = total / 60

Build error: "The process cannot access the file because it is being used by another process"

Just check the references and remove the self-reference to the project.

Explanation: My problem started after creating a custom control and drag and drop it to the toolbox palette for use it in design forms. First appeared a warning saying that there was a redundance between the custom control source file (.cs) and the projects executable (.exe). On executing/debugging appeared the error: unable to access the (.exe) because it's being used (and it was true).

I literally removed the whole source code regarding the custom control and the problem still remained, until I checked out the references and it was referencing itself in order to be "able to" get the former custom control. I removed the reference and done!!

Should I use int or Int32

I always use the system types - e.g., Int32 instead of int. I adopted this practice after reading Applied .NET Framework Programming - author Jeffrey Richter makes a good case for using the full type names. Here are the two points that stuck with me:

  1. Type names can vary between .NET languages. For example, in C#, long maps to System.Int64 while in C++ with managed extensions, long maps to Int32. Since languages can be mixed-and-matched while using .NET, you can be sure that using the explicit class name will always be clearer, no matter the reader's preferred language.

  2. Many framework methods have type names as part of their method names:

    BinaryReader br = new BinaryReader( /* ... */ );
    float val = br.ReadSingle();     // OK, but it looks a little odd...
    Single val = br.ReadSingle();    // OK, and is easier to read

password-check directive in angularjs

To add to the large number of already existing solutions, this works well for me.

(Jan Laussmann answer stopped working with the latest AngularJS beta releases).


angular.module('myApp').directive('matchValidator', [function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attr, ctrl) {
                var pwdWidget = elm.inheritedData('$formController')[attr.matchValidator];

                ctrl.$parsers.push(function(value) {
                    if (value === pwdWidget.$viewValue) {
                        ctrl.$setValidity('match', true); 
                        return value;

                    if (value && pwdWidget.$viewValue) {
                        ctrl.$setValidity('match', false);


                pwdWidget.$parsers.push(function(value) {
                    if (value && ctrl.$viewValue) {
                        ctrl.$setValidity('match', value === ctrl.$viewValue);
                    return value;


<input type="email" ng-model="value1" name="email" required>
<input type="email" ng-model="value2" name="emailConfirm" match-validator="email" required>

display error

<div ng-if="[[yourFormName]].emailConfirm.$error">
    <div ng-if="[[yourFormName]].emailConfirm.$error.match">
        Email addresses don't match.

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

In my case settings.gradle contained invalid configuration.

I changed:

include ':app''<somthing else>'


include ':app'

Error is gone. So maybe check your settings.gradle for potential errors. If this won't work try to remove cache and other tips.

Ajax Upload image

Image upload using ajax and check image format and upload max size   

<form class='form-horizontal' method="POST"  id='document_form' enctype="multipart/form-data">
                                    <div class='optionBox1'>
                                        <div class='row inviteInputWrap1 block1'>
                                            <div class='col-3'>
                                                <label class='col-form-label'>Name</label>
                                                <input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
                                            <div class='col-3'>
                                                <label class='col-form-label'>File</label>
                                                <input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
                                            <div class='col-3'>
                                                <span class='deleteInviteWrap1 remove1 d-none'>
                                                    <i class='fas fa-trash'></i>
                                        <div class='row'>
                                             <div class='col-8 pl-3 pb-4 mt-4'>
                                                <span class='btn btn-info add1 pr-3'>+ Add More</span>
                                                 <button class='btn btn-primary'>Submit</button> 
       submitHandler: function (form) 
                    url : "action1.php",
                    type : "POST",
                    data : new FormData(form),
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    processData: false,
                    success: function(data)
                        if(data.status =='success')
                                 swal("Document has been successfully uploaded!", {
                                    icon: "success",
                                swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
                        swal ( "Ops!" ,  "error in document upload." ,  "error" );
        rules: {
            "name[]": {
              required: true
          "file[]": {
              required: true,
              extension: "jpg,jpeg,png,pdf,doc",
              filesize :2000000 
        messages: {
            "name[]": {
            required: "Please enter name"
          "file[]": {
            required: "Please enter file",
            extension :'Please upload only jpg,jpeg,png,pdf,doc'
        errorElement: 'span',
        errorPlacement: function (error, element) {
        highlight: function (element, errorClass, validClass) {
        unhighlight: function (element, errorClass, validClass) {
      $.validator.addMethod('filesize', function(value, element, param) {
         return this.optional(element) || (element.files[0].size <= param)
        }, 'File size must be less than 2 MB');

How to print HTML content on click of a button, but not the page?

@media print {
print me
<h1 class="noPrint">
no print
<button onclick="window.print();" class="noPrint">
Print Me

I came across another elegant solution for this:

Place your printable part inside a div with an id like this:

<div id="printableArea">
      <h1>Print me</h1>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

Now let's create a really simple javascript:

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;


     document.body.innerHTML = originalContents;

SOURCE : SO Answer

How do I list all the files in a directory and subdirectories in reverse chronological order?

try this:

ls -ltraR |egrep -v '\.$|\.\.|\.:|\.\/|total' |sed '/^$/d'

How do you use window.postMessage across domains?

You should post a message from frame to parent, after loaded.

frame script:

$(document).ready(function() {
    window.parent.postMessage("I'm loaded", "*");

And listen it in parent:

function listenMessage(msg) {

if (window.addEventListener) {
    window.addEventListener("message", listenMessage, false);
} else {
    window.attachEvent("onmessage", listenMessage);

Use this link for more info:

How to add buttons at top of map fragment API v2 layout

Maybe a simpler solution is to set an overlay in front of your map using FrameLayout or RelativeLayout and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:

<FrameLayout xmlns:android=""
    tools:context=".MapActivity" >

    <fragment xmlns:map=""

        android:padding="4dp" >

            android:textColor="@color/textcolor_radiobutton" />
            android:background="#aaa" />

            android:textColor="@color/textcolor_radiobutton" />

            android:background="#aaa" />

            android:textColor="@color/textcolor_radiobutton" />
            android:background="#aaa" />

            android:textColor="@color/textcolor_radiobutton" />

Convert digits into words with JavaScript

Function that will work with decimal values also

function amountToWords(amountInDigits){
    // American Numbering System
    var th = ['','thousand','million', 'billion','trillion'];

    var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
    var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
    var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
    function toWords(s){
      s = s.toString();
      s = s.replace(/[\, ]/g,'');
      if (s != parseFloat(s))
      return 'not a number';
      var x = s.indexOf('.');
      if (x == -1) x = s.length;
      if (x > 15) return 'too big';
      var n = s.split('');
      var str = '';
      var sk = 0;
      for (var i=0; i < x; i++){
        if ((x-i)%3==2){
          if (n[i] == '1') {
            str += tn[Number(n[i+1])] + ' ';
            i++; sk=1;
          } else if (n[i]!=0) {
              str += tw[n[i]-2] + ' ';sk=1;
          } else if (n[i]!=0) {
            str += dg[n[i]] +' ';
            if ((x-i)%3==0)
            str += 'hundred ';
          } if ((x-i)%3==1) {
            if (sk) str += th[(x-i-1)/3] + ' ';sk=0;
        if (x != s.length) {
          var y = s.length;
          str += 'point ';
          for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';
        return str.replace(/\s+/g,' ');

      return toWords(amountInDigits);
<input type="text" name="number" placeholder="Number OR Amount" onkeyup="word.innerHTML=amountToWords(this.value)" />
<div id="word"></div>

What is a C++ delegate?

A delegate is a class that wraps a pointer or reference to an object instance, a member method of that object's class to be called on that object instance, and provides a method to trigger that call.

Here's an example:

template <class T>
class CCallback
    typedef void (T::*fn)( int anArg );

    CCallback(T& trg, fn op)
        : m_rTarget(trg)
        , m_Operation(op)

    void Execute( int in )
        (m_rTarget.*m_Operation)( in );


    CCallback( const CCallback& );

    T& m_rTarget;
    fn m_Operation;


class A
    virtual void Fn( int i )

int main( int /*argc*/, char * /*argv*/ )
    A a;
    CCallback<A> cbk( a, &A::Fn );
    cbk.Execute( 3 );

How to execute multiple commands in a single line

Googling gives me this:

Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)

Command A | Command B

Execute Command A, and redirect all its output into the input of Command B

Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B

Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B

enum Values to NSString (iOS)

Here is working code

//1st Approach
#define enumString(arg) (@""#arg)

//2nd Approach

+(NSString *)secondApproach_convertEnumToString:(StudentProgressReport)status {

    char *str = calloc(sizeof(kgood)+1, sizeof(char));
    int  goodsASInteger = NSSwapInt((unsigned int)kgood);
    memcpy(str, (const void*)&goodsASInteger, sizeof(goodsASInteger));
    NSLog(@"%s", str);
    NSString *enumString = [NSString stringWithUTF8String:str];

    return enumString;

//Third Approcah to enum to string
NSString *const kNitin = @"Nitin";
NSString *const kSara = @"Sara";

typedef NS_ENUM(NSUInteger, Name) {

+ (NSString *)thirdApproach_convertEnumToString :(Name)weekday {

    __strong NSString **pointer = (NSString **)&kNitin;
    pointer +=weekday;
    return *pointer;

Is this how you define a function in jQuery?

No, you can just write the function as:

$(document).ready(function() {

function MyBlah(blah) {

This calls the function MyBlah on content ready.

Better way to find last used row

This is the best way I've seen to find the last cell.

MsgBox ActiveSheet.UsedRage.SpecialCells(xlCellTypeLastCell).Row

One of the disadvantages to using this is that it's not always accurate. If you use it then delete the last few rows and use it again, it does not always update. Saving your workbook before using this seems to force it to update though.

Using the next bit of code after updating the table (or refreshing the query that feeds the table) forces everything to update before finding the last row. But, it's been reported that it makes excel crash. Either way, calling this before trying to find the last row will ensure the table has finished updating first.


Another way to get the last row for any given column, if you don't mind the overhead.

Function GetLastRow(col, row)
    ' col and row are where we will start.
    ' We will find the last row for the given column.
    Do Until ActiveSheet.Cells(row, col) = ""
        row = row + 1
    GetLastRow = row
End Function

Set height of <div> = to height of another <div> through .css

If you're open to using javascript then you can get the property on an element like this: document.GetElementByID('rightdiv').style.getPropertyValue('max-height');

And you can set the attribute on an element like this: .setAttribute('style','max-height:'+heightVariable+';');

Note: if you're simply looking to set both element's max-height property in one line, you can do so like this:

    min-height: 600px;   

class method generates "TypeError: ... got multiple values for keyword argument ..."

Thanks for the instructive posts. I'd just like to keep a note that if you're getting "TypeError: foodo() got multiple values for keyword argument 'thing'", it may also be that you're mistakenly passing the 'self' as a parameter when calling the function (probably because you copied the line from the class declaration - it's a common error when one's in a hurry).

Changing the image source using jQuery

Short but exact

$("#d1 img").click(e=> pic[[0]) ? 1:0] );

let pic=[
  "", // arbitrary - eg: "img1_on.gif",
  "", // arbitrary - eg: "img2_on.gif"

$("#d1 img").click(e=> pic[[0]) ? 1:0] );
<script src=""></script>

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>

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

Checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // checkbox status is checked.
                if (isChecked) {
                        //password is visible
                } else {
                        //password gets hided

Simple pthread! C++

Because the main thread exits.

Put a sleep in the main thread.

cout << "Hello";

return 0;

The POSIX standard does not specify what happens when the main thread exits.
But in most implementations this will cause all spawned threads to die.

So in the main thread you should wait for the thread to die before you exit. In this case the simplest solution is just to sleep and give the other thread a chance to execute. In real code you would use pthread_join();

#include <iostream>
#include <pthread.h>
using namespace std;

#if defined(__cplusplus)
extern "C"
void *print_message(void*)
    cout << "Threading\n";

int main() 
    pthread_t t1;

    pthread_create(&t1, NULL, &print_message, NULL);
    cout << "Hello";

    void* result;

    return 0;

mysql: get record count between two date-time

select * from yourtable 
   where created < now() 
     and created > concat(curdate(),' 4:30:00 AM') 

How can I compare two dates in PHP?

This works because of PHP's string comparison logic. Simply you can check...

if ($startdate < $date) {// do something} 
if ($startdate > $date) {// do something}

Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.

C# convert int to string with padding zeros?

Here I want to pad my number with 4 digit. For instance, if it is 1 then it should show as 0001, if it 11 it should show as 0011.

Below is the code that accomplishes this:

reciptno=1; // Pass only integer.

string formatted = string.Format("{0:0000}", reciptno);

TxtRecNo.Text = formatted; // Output=0001

I implemented this code to generate money receipt number for a PDF file.

Get my phone number in android

Method 1:

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

With below permission

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Method 2:

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

Try below code:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{""},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();

You will need to add these two permissions.

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />

Hope this helps, Thanks!

Can someone post a well formed crossdomain.xml sample?

If you're using webservices, you'll also need the 'allow-http-request-headers-from' element. Here's our default, development, 'allow everything' policy.

<?xml version="1.0" ?>
  <site-control permitted-cross-domain-policies="master-only"/>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="*"/>

JPA & Criteria API - Select only specific columns

First of all, I don't really see why you would want an object having only ID and Version, and all other props to be nulls. However, here is some code which will do that for you (which doesn't use JPA Em, but normal Hibernate. I assume you can find the equivalence in JPA or simply obtain the Hibernate Session obj from the em delegate Accessing Hibernate Session from EJB using EntityManager ):

List<T> results = session.createCriteria(entityClazz)
    .setProjection( Projections.projectionList()
        .add( Property.forName("ID") )
        .add( Property.forName("VERSION") )

This will return a list of Objects having their ID and Version set and all other props to null, as the aliasToBean transformer won't be able to find them. Again, I am uncertain I can think of a situation where I would want to do that.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

If you are using tomcat then along with project directory you should also copy the database connector jar file to tomcat/lib. this worked for me

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

I had this issue on resx files in my solution. I'm using Onedrive. However none of the above solutions fixed it.

The problem was the icon I used was in the MyWindow.resx files for the windows.

I removed that then grabbed the icon from the App Local Resources resource folder.

 private ResourceManager rm = App_LocalResources.LocalResources.ResourceManager;
this.Icon = (Icon)rm.GetObject("IconName");

This happened after an update to VS2019.

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"


var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();

How can I remove specific rules from iptables?

The best solution that works for me without any problems looks this way:
1. Add temporary rule with some comment:

comment=$(cat /proc/sys/kernel/random/uuid | sed 's/\-//g')
iptables -A ..... -m comment --comment "${comment}" -j REQUIRED_ACTION

2. When the rule added and you wish to remove it (or everything with this comment), do:

iptables-save | grep -v "${comment}" | iptables-restore

So, you'll 100% delete all rules that match the $comment and leave other lines untouched. This solution works for last 2 months with about 100 changes of rules per day - no issues.Hope, it helps

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

An explicit call to a parent class constructor is required any time the parent class lacks a no-argument constructor. You can either add a no-argument constructor to the parent class or explicitly call the parent class constructor in your child class.

CSS: create white glow around image

Use simple CSS3 (not supported in IE<9)

    box-shadow: 0px 0px 5px #fff;

This will put a white glow around every image in your document, use more specific selectors to choose which images you'd like the glow around. You can change the color of course :)

If you're worried about the users that don't have the latest versions of their browsers, use this:

-moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
box-shadow: 0px 0px 5px #fff;

For IE you can use a glow filter (not sure which browsers support it)


Play with the settings to see what suits you :)

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
<i class="glyphicon glyphicon-home white"></i>

How to plot data from multiple two column text files with legends in Matplotlib?

This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following:

import pylab

datalist = [ ( pylab.loadtxt(filename), label ) for filename, label in list_of_files ]

for data, label in datalist:
    pylab.plot( data[:,0], data[:,1], label=label )

pylab.title("Title of Plot")
pylab.xlabel("X Axis Label")
pylab.ylabel("Y Axis Label")

You also might want to add something like fmt='o' to the plot command, in order to change from a line to points. By default, matplotlib with pylab plots onto the same figure without clearing it, so you can just run the plot command multiple times.

Getting checkbox values on submit

If you want to turn specific values in to new variables if they have been selected:

// Retrieve array color[] and set as variable    
$colors = $_GET['color'];
// Use array_search to find the key for "red"
$key_red = array_search('red', $colors);
// If "red" exists, the key will be an integer (or FALSE)
if (is_int($key_red)) {
    $red_color = 'Red was selected';

JavaScript - get the first day of the week from current date

a more generalized version of this... this will give you any day in the current week based on what day you specify.

//returns the relative day in the week 0 = Sunday, 1 = Monday ... 6 = Saturday
function getRelativeDayInWeek(d,dy) {
  d = new Date(d);
  var day = d.getDay(),
      diff = d.getDate() - day + (day == 0 ? -6:dy); // adjust when day is sunday
  return new Date(d.setDate(diff));

var monday = getRelativeDayInWeek(new Date(),1);
var friday = getRelativeDayInWeek(new Date(),5);


How to browse localhost on Android device?

If your localhost is not running on the default HTTP port(which is port 80), you need to specify the port in your url to something that corresponds to the port on which your localhost is running. E.g. If your localhost is running on, say port 85, Your url should be

eval command in Bash and its typical uses

eval takes a string as its argument, and evaluates it as if you'd typed that string on a command line. (If you pass several arguments, they are first joined with spaces between them.)

${$n} is a syntax error in bash. Inside the braces, you can only have a variable name, with some possible prefix and suffixes, but you can't have arbitrary bash syntax and in particular you can't use variable expansion. There is a way of saying “the value of the variable whose name is in this variable”, though:

echo ${!n}

$(…) runs the command specified inside the parentheses in a subshell (i.e. in a separate process that inherits all settings such as variable values from the current shell), and gathers its output. So echo $($n) runs $n as a shell command, and displays its output. Since $n evaluates to 1, $($n) attempts to run the command 1, which does not exist.

eval echo \${$n} runs the parameters passed to eval. After expansion, the parameters are echo and ${1}. So eval echo \${$n} runs the command echo ${1}.

Note that most of the time, you must use double quotes around variable substitutions and command substitutions (i.e. anytime there's a $): "$foo", "$(foo)". Always put double quotes around variable and command substitutions, unless you know you need to leave them off. Without the double quotes, the shell performs field splitting (i.e. it splits value of the variable or the output from the command into separate words) and then treats each word as a wildcard pattern. For example:

$ ls
file1 file2 otherfile
$ set -- 'f* *'
$ echo "$1"
f* *
$ echo $1
file1 file2 file1 file2 otherfile
$ n=1
$ eval echo \${$n}
file1 file2 file1 file2 otherfile
$eval echo \"\${$n}\"
f* *
$ echo "${!n}"
f* *

eval is not used very often. In some shells, the most common use is to obtain the value of a variable whose name is not known until runtime. In bash, this is not necessary thanks to the ${!VAR} syntax. eval is still useful when you need to construct a longer command containing operators, reserved words, etc.

File Upload to HTTP server in iphone programming

ASIHTTPRequest is a great wrapper around the network APIs and makes it very easy to upload a file. Here's their example (but you can do this on the iPhone too - we save images to "disk" and later upload them.

ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

How do I post form data with fetch api?

To add on the good answers above you can also avoid setting explicitly the action in HTML and use an event handler in javascript, using "this" as the form to create the "FormData" object

Html form :

<form id="mainForm" class="" novalidate>
<!--Whatever here...-->

In your JS :

$("#mainForm").submit(function( event ) {
  const formData = new URLSearchParams(new FormData(this));
    {   method: 'POST',
        mode : 'same-origin',
        credentials: 'same-origin' ,
        body : formData
    .then(function(response) {
      return response.text()
    }).then(function(text) {
        //text is the server's response

How do C++ class members get initialized if I don't do it explicitly?

If it is on the stack, the contents of uninitialized members that don't have their own constructor will be random and undefined. Even if it is global, it would be a bad idea to rely on them being zeroed out. Whether it is on the stack or not, if a member has its own constructor, that will get called to initialize it.

So, if you have string* pname, the pointer will contain random junk. but for string name, the default constructor for string will be called, giving you an empty string. For your reference type variables, I'm not sure, but it'll probably be a reference to some random chunk of memory.

Call a function after previous function is complete

Specify an anonymous callback, and make function1 accept it:

    if (condition == 'true'){
        function1(someVariable, function() {
    else {

function function1(param, callback) { stuff

Can I fade in a background image (CSS: background-image) with jQuery?

I know i'm late, but I found a way using jquery which works on every browser(i tested it on chrome, firefox and Ie 9)and th fore-ground elements are always displayed instead of css3 transition property.

create 2 absolute wrapper and using z-index.

First set the elements that have to be in the fore-ground with the highest z-index property value, and the other elemets(all included in the body, so: body{}) with a lower z-index property value than the fore-ground elements'one , at least of 2 number lower.

HTML part:

         <div class="wrapper" id="wrapper1"></div>
         <div class="wrapper" id="wrapper2"></div>

css part:

        .fore-groundElements{              //select all fore-ground elements
                  z-index:0;               //>=0
                  background-size: cover;
                  background-size: 100% 100%;



              z-index:-3                          //<=-3

than the javascript/jquery one:

i needed to change the background image every three second so i used a set timeout.

this is the code:


  var main = function(){

             var imgPath=[imagesPath1,..,...];                 // the array in which store the image paths

             var newWrapper;                     // the wrapper to display 
             var currentWrapper;                 //the current displayed wrapper which has to be faded
             var l=2;                             // the next image index  to be displayed, it is set to 2 because the first two position of the array(first two images) start already setted up
             var imgNumber= imgPath.length;        //to know when the images are over and restart the carousel
             var currentImg;                       //the next image path to be displayed

             $('#wrapper1').css("background-image", 'url'+imgPath[0]);         //pre set the first wrapper background images
             $('#wrapper2').css("background-image", 'url'+imgPath[1]);          //pre set the first wrapper background images   

             setInterval(myfunction,3000);                //refresh the background image every three seconds

             function myfunction(){
                    if(l===imgNumber-1){               //restart the carousel if every single image has already been displayed                  

             if(l%2==0||l%2==2){                    //set the wrapper that will be displaied after the fadeOut callback function
            $(currentWrapper).fadeOut(1000,function(){               //fade out the current wrapper, so now the back-ground wrapper is fully displayed
                  $(newWrapper).css("z-index", "-1");                //move the shown wrapper in the fore-ground
                  $(currentWrapper).css("z-index","-2");             //move the hidden wrapper in the back ground
                  $(currentWrapper).css("background-image",'url'+currentImg);                   // sets up the next image that is now shown in the actually hidden background wrapper
                  $(currentWrapper).show();          //shows the background wrapper, which is not visible yet, and it will be shown the next time the setInterval event will be triggered
                  l++;                         //set the next image index that will be set the next time the setInterval event will be triggered 

         };                   //end of myFunction
  }                          //end of main

i hope that my answer is clear,if you need more explanation comment it.

sorry for my english :)

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

The reason that you get this error on OSX is the rvm-installed ruby.

If you run into this issue on OSX you can find a really broad explanation of it in this blog post:

The short version is that, for some versions of Ruby, RVM downloads pre-compiled binaries, which look for certificates in the wrong location. By forcing RVM to download the source and compile on your own machine, you ensure that the configuration for the certificate location is correct.

The command to do this is:

rvm install 2.2.0 --disable-binary

if you already have the version in question, you can re-install it with:

rvm reinstall 2.2.0 --disable-binary

(obviously, substitute your ruby version as needed).

Pandas: Creating DataFrame from Series

I guess anther way, possibly faster, to achieve this is 1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array) 2) Then use pd.DataFrame to create an instance directly from the dict without loop over each col and concat.

Assuming your mat looks like this (you can ignore this since your mat is loaded from file):

In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
   .....: 'b': np.random.randint(5, size=(4,2))}

In [136]: mat
{'a': array([[2, 0],
        [3, 4],
        [0, 1],
        [4, 2]]), 'b': array([[1, 0],
        [1, 1],
        [1, 0],
        [2, 1]])}

Then you can do:

In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})

In [138]: df
   a  b
0  0  0
1  4  1
2  1  0
3  2  1

[4 rows x 2 columns]

Map enum in JPA with fixed values?

For versions earlier than JPA 2.1, JPA provides only two ways to deal with enums, by their name or by their ordinal. And the standard JPA doesn't support custom types. So:

  • If you want to do custom type conversions, you'll have to use a provider extension (with Hibernate UserType, EclipseLink Converter, etc). (the second solution). ~or~
  • You'll have to use the @PrePersist and @PostLoad trick (the first solution). ~or~
  • Annotate getter and setter taking and returning the int value ~or~
  • Use an integer attribute at the entity level and perform a translation in getters and setters.

I'll illustrate the latest option (this is a basic implementation, tweak it as required):

@Table(name = "AUTHORITY_")
public class Authority implements Serializable {

    public enum Right {
        READ(100), WRITE(200), EDITOR (300);

        private int value;

        Right(int value) { this.value = value; }    

        public int getValue() { return value; }

        public static Right parse(int id) {
            Right right = null; // Default
            for (Right item : Right.values()) {
                if (item.getValue()==id) {
                    right = item;
            return right;


    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "AUTHORITY_ID")
    private Long id;

    @Column(name = "RIGHT_ID")
    private int rightId;

    public Right getRight () {
        return Right.parse(this.rightId);

    public void setRight(Right right) {
        this.rightId = right.getValue();


Get Image Height and Width as integer values?

PHP's getimagesize() returns an array of data. The first two items in the array are the two items you're interested in: the width and height. To get these, you would simply request the first two indexes in the returned array:

var $imagedata = getimagesize("someimage.jpg");

print "Image width  is: " . $imagedata[0];
print "Image height is: " . $imagedata[1];

For further information, see the documentation.

PHP class: Global variable as property in class

Try to avoid globals, instead you can use something like this

class myClass() {
 private $myNumber;

 public function setNumber($number) {
  $this->myNumber = $number;

Now you can call

$class = new myClass();

could not extract ResultSet in hibernate

I Used the following properties in my file and the issue got resolved




earlier was getting an error

There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; SQL [n/a]; nested exception is 
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(

int *array = new int[n]; what is this function actually doing?

It allocates space on the heap equal to an integer array of size N, and returns a pointer to it, which is assigned to int* type pointer called "array"

How to change the URL from "localhost" to something else, on a local system using wampserver?

They are probably using a virtual host (

You can go into your Apache configuration file (httpd.conf) or your virtual host configuration file (recommended) and add something like:

<VirtualHost *:80>
    DocumentRoot /www/ap-mispro
    ServerName ap-mispro

    # Other directives here

And when you call up http://ap-mispro/ you would see whatever is in C:/wamp/www/ap-mispro (assuming default directory structure). The ServerName and DocumentRoot do no have to have the same name at all. Other factors needed to make this work:

  1. You have to make sure httpd-vhosts.conf is included by httpd.conf for your changes in that file to take effect.
  2. When you make changes to either file, you have to restart Apache to see your changes.
  3. You have to change your hosts file for your computer to know where to go when you type http://ap-mispro into your browser. This change to your hosts file will only apply to your computer - not that it sounds like you are trying from anyone else's.

There are plenty more things to know about virtual hosts but this should get you started.

Add support library to Android Studio project

In Android Studio 1.0, this worked for me :-
Open the build.gradle (Module : app) file and paste this (at the end) :-

dependencies {
    compile ""

Note that this dependencies is different from the dependencies inside buildscript in build.gradle (Project)
When you edit the gradle file, a message shows that you must sync the file. Press "Sync now"

Source :

How to execute command stored in a variable?

Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the bash manpage):

  • initial word splitting
  • brace expansion
  • tilde expansion
  • parameter, variable and arithmetic expansion
  • command substitution
  • secondary word splitting
  • path expansion (aka globbing)
  • quote removal

Using $cmd directly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.

Using eval "$cmd" does nothing until the quote removal phase, where $cmd is returned as is, and passed as a parameter to eval, whose function is to run the whole chain again before executing.

So basically, they're the same in most cases, and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion:

$ cmd="echo foo{bar,baz}"
$ $cmd
$ eval "$cmd"
foobar foobaz

How to convert a GUID to a string in C#?

Here are examples of output from each of the format specifiers:

N: cd26ccf675d64521884f1693c62ed303
D: cd26ccf6-75d6-4521-884f-1693c62ed303
B: {cd26ccf6-75d6-4521-884f-1693c62ed303}
P: (cd26ccf6-75d6-4521-884f-1693c62ed303)
X: {0xcd26ccf6,0x75d6,0x4521,{0x88,0x4f,0x16,0x93,0xc6,0x2e,0xd3,0x03}}

The default is D.

Run this yourself.

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

Facebook Post Link Image

To change Title, Description and Image, we need to add some meta tags under head tag.

STEP 1 : Add meta tags under head tag

<meta property="og:url" content="" />
<meta property="og:image" content="" />
<meta property="og:title" content="Prepaid Phone Cards, low rates for International calls with Lucky Prepay" />
<meta property="og:description" content="Cheap prepaid Phone Cards. Low rates for international calls anywhere in the world." />

NEXT STEP : Click on below link

Add your URL in text box (e.g where you mentioned the tags. Click on DEBUG button.

Its done.

You can verify here

In above url, u = your website link

ENJOY !!!!

Bash script - variable content as a command to run

In the case where you have multiple variables containing the arguments for a command you're running, and not just a single string, you should not use eval directly, as it will fail in the following case:

function echo_arguments() {
  echo "Argument 1: $1"
  echo "Argument 2: $2"
  echo "Argument 3: $3"
  echo "Argument 4: $4"

# Note we are passing 3 arguments to `echo_arguments`, not 4
eval echo_arguments arg1 arg2 "Some arg"


Argument 1: arg1
Argument 2: arg2
Argument 3: Some
Argument 4: arg

Note that even though "Some arg" was passed as a single argument, eval read it as two.

Instead, you can just use the string as the command itself:

# The regular bash eval works by jamming all its arguments into a string then
# evaluating the string. This function treats its arguments as individual
# arguments to be passed to the command being run.
function eval_command() {

Note the difference between the output of eval and the new eval_command function:

eval_command echo_arguments arg1 arg2 "Some arg"


Argument 1: arg1
Argument 2: arg2
Argument 3: Some arg
Argument 4:

How to edit a JavaScript alert box title?

No, you can't.

It's a security/anti-phishing feature.

Is a view faster than a simple query?

Definitely a view is better than a nested query for SQL Server. Without knowing exactly why it is better (until I read Mark Brittingham's post), I had run some tests and experienced almost shocking performance improvements when using a view versus a nested query. After running each version of the query several hundred times in a row, the view version of the query completed in half the time. I'd say that's proof enough for me.

What is the difference between json.dump() and json.dumps() in python?

In memory usage and speed.

When you call jsonstr = json.dumps(mydata) it first creates a full copy of your data in memory and only then you file.write(jsonstr) it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.

When you call json.dump(mydata, file) -- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.

Source: I checked the source code of json.dump() and json.dumps() and also tested both the variants measuring the time with time.time() and watching the memory usage in htop.

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

Java: String - add character n-times

 String toAdd = "toAdd";
 StringBuilder s = new StringBuilder();
 for(int count = 0; count < MAX; count++) {
  String output = s.toString();

Check if string has space in between (or anywhere)

If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:

string s = "Hello There";
bool fHasSpace = s.Contains(" ");

If you're looking for ways to detect whitespace, there's several great options below.

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

For me, I have to run

sudo dpkg --add-architecture i386

before running Mike Tang's answer. Otherwise, I can't install ia32-libs.

Postgres FOR LOOP

Below is example you can use:

create temp table test2 (
  id1  numeric,
  id2  numeric,
  id3  numeric,
  id4  numeric,
  id5  numeric,
  id6  numeric,
  id7  numeric,
  id8  numeric,
  id9  numeric,
  id10 numeric) 
with (oids = false);

     i int;
for  i in 1..100000
    insert into test2  values (random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random());
end loop;

How to get integer values from a string in Python?

>>> import re
>>> string1 = "498results should get"
>>> int('\d+', string1).group())

If there are multiple integers in the string:

>>> map(int, re.findall(r'\d+', string1))

Disabling Minimize & Maximize On WinForm?

How to make form minimize when closing was already answered, but how to remove the minimize and maximize buttons wasn't.
FormBorderStyle: FixedDialog
MinimizeBox: false
MaximizeBox: false

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

post ajax data to PHP and return data

            type: "POST",
            data: {data:the_id},
            url: "http://localhost/test/index.php/data/count_votes",
            success: function(data){
               //data will contain the vote count echoed by the controller i.e.  
              //then append the result where ever you want like
              $("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller


in the controller

$data = $_POST['data'];  //$data will contain the_id
//do some processing
echo "yourVoteCount";


i think you are confusing




both the data are different for your own clarity sake you can modify it as


Pandas Replace NaN with blank/empty string

If you are converting DataFrame to JSON, NaN will give error so best solution is in this use case is to replace NaN with None.
Here is how:

df1 = df.where((pd.notnull(df)), None)

How to sparsely checkout only one single file from a git repository?

Originally, I mentioned in 2012 git archive (see Jared Forsyth's answer and Robert Knight's answer), since git1.7.9.5 (March 2012), Paul Brannan's answer:

git archive --format=tar --remote=origin HEAD:path/to/directory -- filename | tar -O -xf -

But: in 2013, that was no longer possible for remote URLs.
See the old page "Can I archive a repository?"

The current (2018) page "About archiving content and data on GitHub" recommends using third-party services like GHTorrent or GH Archive.

So you can also deal with local copies/clone:

You could alternatively do the following if you have a local copy of the bare repository as mentioned in this answer,

git --no-pager --git-dir /path/to/bar/repo.git show branch:path/to/file >file

Or you must clone first the repo, meaning you get the full history: - in the .git repo - in the working tree.

  • But then you can do a sparse checkout (if you are using Git1.7+),:
    • enable the sparse checkout option (git config core.sparsecheckout true)
    • adding what you want to see in the .git/info/sparse-checkout file
    • re-reading the working tree to only display what you need

To re-read the working tree:

$ git read-tree -m -u HEAD

That way, you end up with a working tree including precisely what you want (even if it is only one file)

Richard Gomes points (in the comments) to "How do I clone, fetch or sparse checkout a single directory or a list of directories from git repository?"

A bash function which avoids downloading the history, which retrieves a single branch and which retrieves a list of files or directories you need.

Can a for loop increment/decrement by more than one?

for (var i = 0; i < 10; i = i + 2) {
    // code here

Get connection status on client

You can check the socket.connected property:

var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
  console.log('check 2', socket.connected);

It's updated dynamically, if the connection is lost it'll be set to false until the client picks up the connection again. So easy to check for with setInterval or something like that.

Another solution would be to catch disconnect events and track the status yourself.

IntelliJ does not show 'Class' when we right click and select 'New'

Most of the people already gave the answer but this one is just for making someone's life easier.


Screenshot of how to add test sources

You must add the test folder as source.

  1. Right click on java directory under test
  2. Mark it as Tests
  3. Add src/test/java in Test Source Folders

Thats it, IntelliJ will consider them as test source.

Using LIKE operator with stored procedure parameters


village_name LIKE + @VILLAGE_NAME + '%';

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

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

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

SELECT CAST(add_date AS CHAR) as add_date

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

MySQL Constraints on Invalid Data:

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


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

MySQL 5.x Date and Time Types:

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


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

How to open VMDK File of the Google-Chrome-OS bundle 2012?

I was looking for a way to play VMDK files without the vmx file in VMware Player 5 and didn't find any explicit tutorial to do it. So after some time messing around with VMware PLayer 5, it turned out to be pretty simple, but not so intuitive. Here it is:

Create a new virtual machine from VMware Player 5; There's no need to install an OS, since you already have the VMDK (Virtual Machine Disk); Set the Virtual Machine to the OS you'll be playing (the one from the VMDK); After creating the VM with the remaining creation wizard options, go to your VM settings; There you can remove the existing hard drive and add a new one; Upon addition of the new hard drive, point it to your existing VMDK file.

And that's it.

If you have problems starting the VM because VMware Player can't lock the VMDK file, rename/delete the dir/files with extension *.lck from the directory where the *.vmdk file is located.

Hope this is helpful.

Ignore Duplicates and Create New List of Unique Values in Excel

Another approach, since Excel 2016, is to use Power Query.


  • select the data (including the field name),
  • use menu Data > From a table or a range,
  • (Excel will change your sheet into an Excel Table, which is very convenient),
  • in the Power Query Editor, right-click on ColumnA (the column header), and Remove duplicates,
  • in the menu, choose Close and load, choose where you want the result, and you're done, like this.
  • Whenever you want the result table to update, right-click it and choose Refresh.

Benefits :

  • it uses the CPU only when manually updated, which is very convenient for long lists,
  • if you're curious, this offers many other powerful options.

Drawbacks :

  • it doesn't update on the fly (you have to right-click and refresh the result table),
  • people with old version of Excel won't be able to refresh the results table.

Why is the default value of the string type null instead of an empty string?

Why the designers of C# chose to use null as the default value of strings?

Because strings are reference types, reference types are default value is null. Variables of reference types store references to the actual data.

Let's use default keyword for this case;

string str = default(string); 

str is a string, so it is a reference type, so default value is null.

int str = (default)(int);

str is an int, so it is a value type, so default value is zero.

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

To try to debug this error, first go to your android terminal / console and execute this command:


then if the output comes out as your app... it is your app causing the error. Try to look for empty Strings that you pass into the layout.

I had this exact same problem and it was my fault as I was passing an empty String into my layout. After changing the "" to " " this error went away.

If you don't get your app from the console output, then it is something else causing it (probably, as others said, the android keyboard)

What does -1 mean in numpy reshape?

The criterion to satisfy for providing the new shape is that 'The new shape should be compatible with the original shape'

numpy allow us to give one of new shape parameter as -1 (eg: (2,-1) or (-1,3) but not (-1, -1)). It simply means that it is an unknown dimension and we want numpy to figure it out. And numpy will figure this by looking at the 'length of the array and remaining dimensions' and making sure it satisfies the above mentioned criteria

Now see the example.

z = np.array([[1, 2, 3, 4],
         [5, 6, 7, 8],
         [9, 10, 11, 12]])
(3, 4)

Now trying to reshape with (-1) . Result new shape is (12,) and is compatible with original shape (3,4)

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

Now trying to reshape with (-1, 1) . We have provided column as 1 but rows as unknown . So we get result new shape as (12, 1).again compatible with original shape(3,4)

array([[ 1],
   [ 2],
   [ 3],
   [ 4],
   [ 5],
   [ 6],
   [ 7],
   [ 8],
   [ 9],

The above is consistent with numpy advice/error message, to use reshape(-1,1) for a single feature; i.e. single column

Reshape your data using array.reshape(-1, 1) if your data has a single feature

New shape as (-1, 2). row unknown, column 2. we get result new shape as (6, 2)

z.reshape(-1, 2)
array([[ 1,  2],
   [ 3,  4],
   [ 5,  6],
   [ 7,  8],
   [ 9, 10],
   [11, 12]])

Now trying to keep column as unknown. New shape as (1,-1). i.e, row is 1, column unknown. we get result new shape as (1, 12)

array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]])

The above is consistent with numpy advice/error message, to use reshape(1,-1) for a single sample; i.e. single row

Reshape your data using array.reshape(1, -1) if it contains a single sample

New shape (2, -1). Row 2, column unknown. we get result new shape as (2,6)

z.reshape(2, -1)
array([[ 1,  2,  3,  4,  5,  6],
   [ 7,  8,  9, 10, 11, 12]])

New shape as (3, -1). Row 3, column unknown. we get result new shape as (3,4)

z.reshape(3, -1)
array([[ 1,  2,  3,  4],
   [ 5,  6,  7,  8],
   [ 9, 10, 11, 12]])

And finally, if we try to provide both dimension as unknown i.e new shape as (-1,-1). It will throw an error

z.reshape(-1, -1)
ValueError: can only specify one unknown dimension

Swift - How to detect orientation changes

Swift 4+: I was using this for soft keyboard design, and for some reason the UIDevice.current.orientation.isLandscape method kept telling me it was Portrait, so here's what I used instead:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    if(size.width > self.view.frame.size.width){

How to use relative paths without including the context root name?

You start tomcat from some directory - which is the $cwd for tomcat. You can specify any path relative to this $cwd.

suppose you have

- tomcat
- cssStore

And suppose you start tomcat from ~/tomcat, using the command "bin/".

~/tomcat becomes the home directory ($cwd) for tomcat

You can access "../cssStore/file.css" from class files in your servlet now

Hope that helps, - M.S.

Get current time in hours and minutes

With bash version >= 4.2:

printf "%(%H:%M)T\n"


printf -v foo "%(%H:%M)T\n"
echo "$foo"

See: man bash

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

In my case, I was getting this error despite registering an existing instance for the interface in question.

Turned out, it was because I was using Unity in WebForms by way of the Unity.WebForms Nuget package, and I had specified a Hierarchical Lifetime manager for the dependency I was providing an instance for, yet a Transient lifetime manager for a subsequent type that depended on the previous type - not usually an issue - but with Unity.WebForms, the lifetime managers work a little differently... your injected types seem to require a Hierarchical lifetime manager, but a new container is still created for every web request (because of the architecture of web forms I guess) as explained excellently in this post.

Anyway, I resolved it by simply not specifying a lifetime manager for the types/instances when registering them.


container.RegisterInstance<IMapper>(MappingConfig.GetMapper(), new HierarchicalLifetimeManager());    
container.RegisterType<IUserContext, UserContext>(new TransientLifetimeManager());


container.RegisterType<IUserContext, UserContext>();

So that IMapper can be resolved successfully here:

public class UserContext : BaseContext, IUserContext
    public UserContext(IMapper _mapper) : base(_mapper)


How can I get the session object if I have the entity-manager?

I was working in Wildfly but I was using

org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();

and the correct was

org.hibernate.Session session = (Session) manager.getDelegate();

#pragma pack effect

Data elements (e.g. members of classes and structs) are typically aligned on WORD or DWORD boundaries for current generation processors in order to improve access times. Retrieving a DWORD at an address which isn't divisible by 4 requires at least one extra CPU cycle on a 32 bit processor. So, if you have e.g. three char members char a, b, c;, they actually tend to take 6 or 12 bytes of storage.

#pragma allows you to override this to achieve more efficient space usage, at the expense of access speed, or for consistency of stored data between different compiler targets. I had a lot of fun with this transitioning from 16 bit to 32 bit code; I expect porting to 64 bit code will cause the same kinds of headaches for some code.

What's the difference between ASCII and Unicode?

ASCII defines 128 characters, which map to the numbers 0–127. Unicode defines (less than) 221 characters, which, similarly, map to numbers 0–221 (though not all numbers are currently assigned, and some are reserved).

Unicode is a superset of ASCII, and the numbers 0–127 have the same meaning in ASCII as they have in Unicode. For example, the number 65 means "Latin capital 'A'".

Because Unicode characters don't generally fit into one 8-bit byte, there are numerous ways of storing Unicode characters in byte sequences, such as UTF-32 and UTF-8.

How can I convert a date to GMT?

Based on the accepted answer and the second highest scoring answer both are not perfect according to the comment so I mixed both to get something perfect:

var date = new Date(); //Current timestamp_x000D_
date = date.toGMTString(); _x000D_
//Based on the time zone where the date was created_x000D_
/*based on the comment getTimezoneOffset returns an offset based _x000D_
on the date it is called on, and the time zone of the computer the code is_x000D_
 running on. It does not supply the offset passed in when constructing a _x000D_
date from a string. */_x000D_
date = new Date(date); //will convert to present timestamp offset_x000D_
date = new Date(date.getTime() + (date.getTimezoneOffset() * 60 * 1000)); _x000D_

Simulating Key Press C#

Here's an example...

static class Program
    public static extern int SetForegroundWindow(IntPtr hWnd);

    static void Main()
            Process [] processes = Process.GetProcessesByName("iexplore");

            foreach(Process proc in processes)


a better one... less anoying...

static class Program
    const UInt32 WM_KEYDOWN = 0x0100;
    const int VK_F5 = 0x74;

    static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);

    static void Main()
            Process [] processes = Process.GetProcessesByName("iexplore");

            foreach(Process proc in processes)
                PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);


Max tcp/ip connections on Windows Server 2008

There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:

It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.

How can I create an MSI setup?

If you don't understand Windows Installer then I highly recommend The Definitive Guide to Windows Installer. You can't really use WiX without understanding MSI. Also worth downloading is the Windows Installer 4.5 SDK.

If you don't want to learn the Windows Installer fundamentals, then you'll need some wizard type package to hide all the nitty gritty details and hold your hand. There are plenty of options, some more expensive than others.

  • InstallShield
  • Advanced Installer
  • MSI Factory
  • etc..

However still I'd suggest picking up the above book and taking some time to understand what's going on "under the hood", it'll really help you figure out what's going wrong when customers start complaining that something is broken with the setup :)

HTML5 validation when the input type is not "submit"

You should use form tag enclosing your inputs. And input type submit.
This works.

<form id="testform">
<input type="text" id="example" name="example"  required>
<button type="submit"  onclick="submitform()" id="save">Save</button>

Since HTML5 Validation works only with submit button you have to keep it there. You can avoid the form submission though when valid by preventing the default action by writing event handler for form.

document.getElementById('testform').onsubmit= function(e){

This will give your validation when invalid and will not submit form when valid.