Programs & Examples On #Boost signals

Removing legend on charts with chart.js v2

You simply need to add that line legend: { display: false }

What is the purpose of the var keyword and when should I use it (or omit it)?

When Javascript is executed in a browser, all your code is surrounded by a with statement, like so:

with (window) {
    //Your code

More info on with - MDN

Since var declares a variable in the current scope , there is no difference between declaring var inside window and not declaring it at all.

The difference comes when you're not directly inside the window, e.g. inside a function or inside a block.

Using var lets you hide external variables that have the same name. In this way you can simulate a "private" variable, but that's another topic.

A rule of thumb is to always use var, because otherwise you run the risk of introducing subtle bugs.

EDIT: After the critiques I received, I would like to emphasize the following:

  • var declares a variable in the current scope
  • The global scope is window
  • Not using var implicitly declares var in the global scope (window)
  • Declaring a variable in the global scope (window) using var is the same as omitting it.
  • Declaring a variable in scopes different from window using var is not the same thing as declaring a variable without var
  • Always declare var explicitly because it's good practice

Test credit card numbers for use with PayPal sandbox

It turns out, after messing around with all of the settings in the test business account, that one (or more) of the fraud related settings in the payment receiving preferences / security settings screens were causing the test payments to fail (without any useful error).

How does the communication between a browser and a web server take place?

The links for specifications of each aspect of the question is as follows:

  • GET, POST verbs (among others) - The HTTP Specification exhaustively discusses all aspects of HTTP communication (the protocol for communication between the web server and the browser). It explains the Request message and Response message protocols.

  • Cookies - are set by attaching a Set-Cookie HTTP Header to the HTTP response.

  • QueryStrings - are the part of the URL in the HTTP request that follow the first occurrence of a "?" character. The linked specification is for section 3.4 of the URI specification.

  • Sessions - HTTP is a synchronous, stateless protocol. Sessions, or the illusion of state, can be created by (1) using cookies to store state data as plain text on the client's computer, (2) passing data-values in the URL and querystring of the request, (3) submitting POST requests with a collection of values that may indicate state and, (4) storing state information by a server-side persistence mechanism that is retrieved by a session-key (the session key is resolved from either the cookie, URL/Querystring or POST value collection.

An explanation of HTTP can go on for days, but I have attempted to provide a concise yet conceptually complete answer, and include the appropriate links for further reading of official specifications.

Any way to generate ant build.xml file automatically from Eclipse?

  • Select File > Export from main menu (or right click on the project name and select Export > Export…).
  • In the Export dialog, select General > Ant Buildfiles as follows: enter image description here

  • Click Next. In the Generate Ant Buildfilesscreen:

    • Check the project in list.
    • Uncheck the option "Create target to compile project using Eclipse compiler" - because we want to create a build file which is independent of Eclipse.
    • Leave the Name for Ant buildfile as default: build.xml

enter image description here

  • Click Finish, Eclipse will generate the build.xml file under project’s directory as follows:
    enter image description here
  • Double click on the build.xml file to open its content in Ant editor: enter image description here


Centering controls within a form in .NET (Winforms)?

Since you don't state if the form can resize or not there is an easy way if you don't care about resizing (if you do care, go with Mitch Wheats solution):

Select the control -> Format (menu option) -> Center in Window -> Horizontally or Vertically

Do something if screen width is less than 960 px

I know i'm late to answer this, but i hope it is of some help to anybody who have similar problem. It also works when page refreshes for any reason.


if ($(window).width() < 960 && $(window).load()) {

        if ($(window).width() < 960) {

$(window).resize(function() {
    if ($(window).width() < 960 && $(window).load()) {

        if ($(window).width() < 960) {


Spin or rotate an image on hover

Here is my code, this flips on hover and flips back off-hover.


.flip-container {
  background: transparent;
  display: inline-block;

.flip-this {
  position: relative;
  width: 100%;
  height: 100%;
  transition: transform 0.6s;
  transform-style: preserve-3d;

.flip-container:hover .flip-this {
  transition: 0.9s;
  transform: rotateY(180deg);


<div class="flip-container">
    <div class="flip-this">
        <img width="100" alt="Godot icon" src="">

Fiddle this

jQuery serialize does not register checkboxes

For ASP.NET MVC, we successfully save a form with checkboxes via an AJAX POST with the following, which is a combination of several methods referenced in this post, including @Jecoms suggestion:

var form = $('#myForm');
// Serialize the form into a JavaScript object using the jQuery.serializeObject plugin
var data = form.serializeObject();
// Change the submitted value of checkboxes to the value of the checked property
$('#myForm input[type=checkbox]').each( function () { data[] = this.checked; } );
// For a MVC controller, convert the JS object back into a query string using jQuery.param function
data = $.param(data);
// Perform AJAX POST with the form data
    async: true,
    url: 'mvcActionMethodURL',
    type: 'POST',
    data: data,
    success: function (data, textStatus, xhr) {

    error: function (xhr, status, error) {


Does Spring Data JPA have any way to count entites using method name resolving?

Working example

public interface TenantRepository extends JpaRepository< Tenant, Long > {
    List<Tenant>findByTenantName(String tenantName,Pageable pageRequest);
    long countByTenantName(String tenantName);

Calling from DAO layer

public long countByTenantName(String tenantName) {
    return repository.countByTenantName(tenantName);

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

Use Query.setParameterList(), Javadoc here.

There are four variants to pick from.

BACKUP LOG cannot be performed because there is no current database backup

Another cause for this is if you have the same database restored under a different name. Delete the existing one and then restoring solved it for me.

How to modify list entries during for loop?

One more for loop variant, looks cleaner to me than one with enumerate():

for idx in range(len(list)):
    list[idx]=... # set a new value
    # some other code which doesn't let you use a list comprehension

Limit the size of a file upload (html input element)

var uploadField = document.getElementById("file");

uploadField.onchange = function() {
    if(this.files[0].size > 2097152){
       alert("File is too big!");
       this.value = "";

This example should work fine. I set it up for roughly 2MB, 1MB in Bytes is 1,048,576 so you can multiply it by the limit you need.

Here is the jsfiddle example for more clearence:

How to add manifest permission to an application?

Permission name is CASE-SENSITIVE

In case somebody will struggle with same issue, it is case sensitive statement, so wrong case means your application won't get the permission.


<uses-permission android:name="ANDROID.PERMISSION.INTERNET" />


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

This issue may happen ie. on autocomplete in IDE

Module AppRegistry is not registered callable module (calling runApplication)

If you are using windows and running yarn open cmd on admin mode' terminate and Restart the node process by typing this command.

Find the node: killall -9 node force to kill : taskkill /f /im node.exe Reset the cache : yarn start --reset-cache

Navigate to your project directory: cd myapp Re-Run your App : yarn android

Pass Javascript variable to PHP via ajax

Pass the data like this to the ajax call (

data: { userID : userID }

And in your PHP do this:

    $uid = $_POST['userID'];

    // Do whatever you want with the $uid

isset() function's purpose is to check wheter the given variable exists, not to get its value.

Choosing the default value of an Enum type without having to change values

The default for an enum (in fact, any value type) is 0 -- even if that is not a valid value for that enum. It cannot be changed.

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

I know this is older, but wanted to contribute another possibly solution.

If you want to keep the project location, as I did, I found that copying the .project file from another project into the project's directory, then editing the .project file to name it properly, then choosing the Import Existing Projects into Workspace option worked for me.

In Windows, I used a file monitor to see what Eclipse was doing, and it was simply erroring out for some unknown reason when trying to create the .project file. So, I did that manually and it worked for me.

What does "hashable" mean in Python?

From the Python glossary:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

How to change indentation in Visual Studio Code?

You can change this in global User level or Workspace level.

Open the settings: Using the shortcut Ctrl , or clicking File > Preferences > Settings as shown below.

Settings on VS Code menu

Then, do the following 2 changes: (type tabSize in the search bar)

  1. Uncheck the checkbox of Detect Indentation
  2. Change the tab size to be 2/4 (Although I strongly think 2 is correct for JS :))

enter image description here

How to select the first element with a specific attribute using XPath

for ex.

<input b="demo">



How to load html string in a webview?

read from assets html file

ViewGroup webGroup;
  String content = readContent("content/ganji.html");

        final WebView webView = new WebView(this);
        webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);


Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.

You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       N(N), R(R)
       for (int c = 1; c <= R; ++c)

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;

       return ret;


   int N, R;
   combination_t curr;

int main(int argc, char **argv)
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
        combinations::combination_t c =;
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    return cs.generated;

test output:


How can one see the structure of a table in SQLite?

Invoke the sqlite3 utility on the database file, and use its special dot commands:

  • .tables will list tables
  • .schema [tablename] will show the CREATE statement(s) for a table or tables

There are many other useful builtin dot commands -- see the documentation at, section Special commands to sqlite3.


sqlite> entropy:~/Library/Mail>sqlite3 Envelope\ Index
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
addresses              ews_folders            subjects
alarms                 feeds                  threads
associations           mailboxes              todo_notes
attachments            messages               todos
calendars              properties             todos_deleted_log
events                 recipients             todos_server_snapshot
sqlite> .schema alarms
                     todo INTEGER, flags INTEGER, offset_days INTEGER,
                     reminder_date INTEGER, time INTEGER, argument,
                     unrecognized_data BLOB);
CREATE INDEX alarm_id_index ON alarms(alarm_id);
CREATE INDEX alarm_todo_index ON alarms(todo);

Note also that SQLite saves the schema and all information about tables in the database itself, in a magic table named sqlite_master, and it's also possible to execute normal SQL queries against that table. For example, the documentation link above shows how to derive the behavior of the .schema and .tables commands, using normal SQL commands (see section: Querying the database schema).

Replace whitespaces with tabs in linux

I think you can try with awk

awk -v OFS="\t" '$1=$1' file1

or SED if you preffer

sed 's/[:blank:]+/,/g' thefile.txt > the_modified_copy.txt

or even tr

tr -s '\t' < thefile.txt | tr '\t' ' ' > the_modified_copy.txt

or a simplified version of the tr solution sugested by Sam Bisbee

tr ' ' \\t < someFile > someFile

Node.js: get path from the request

req.protocol + '://' + req.get('host') + req.originalUrl


req.protocol + '://' + + req.originalUrl // I like this one as it survives from proxy server, getting the original host name

I want to vertical-align text in select box

I found that only adding padding-top pushed down the grey dropdown arrow box on the right, which was undesirable.

The method that worked for me was to go into the inspector and incrementally add padding until the text was centered. This will also reduce the size of the dropdown icon, but it will be centered as well so it isn't as visually disturbing.

How to create a drop shadow only on one side of an element?

You could also just do a gradient on the bottom - this was helpful for me because the shadow I wanted was on an element that was already semi-transparent, so I didn't have to worry about any clipping:

&:after {
      height: 8px;
      position: absolute;
      bottom: -8px;
      left: 0;
      background: linear-gradient(to bottom, rgba(0,0,0,0.65) 0%,rgba(0,0,0,0) 100%);

Just make the "bottom" and "height" properties match and set your rgba values to whatever you want them to be at the top / bottom of the shadow

How to get root access on Android emulator?

Use android image without PlayServices then you'll be able to run add root and access whatever you want.

Git/GitHub can't push to master

I added my pubkey to and this was successful:

ssh -T [email protected]

But I received the "You can't push" error after having wrongly done this:

git clone git://
git remote add origin [email protected]:mygithubacct/dotfiles.git
git push origin master

Instead of doing what I should have done:

mkdir dotfiles
cd dotfiles
git init
git remote add origin [email protected]:mygithubacct/dotfiles.git
git pull origin master
git push origin master

Is there a way to run Python on Android?

Didn't see this posted here, but you can do it with Pyside and Qt now that Qt works on Android thanks to Necessitas.

It seems like quite a kludge at the moment but could be a viable route eventually...

Opening popup windows in HTML

HTML alone does not support this. You need to use some JS.

And also consider nowadays people use popup blocker in browsers.

<a href="'document.aspx','mypopuptitle','width=600,height=400')">open popup</a>

Running multiple commands with xargs

I prefer style which allows dry run mode (without | sh) :

cat a.txt | xargs -I % echo "command1; command2; ... " | sh

Works with pipes too:

cat a.txt | xargs -I % echo "echo % | cat " | sh

Get clicked element using jQuery on event?

As simple as it can be

Use $(this) here too

$(document).on("click",".appDetails", function () {
   var clickedBtnID = $(this).attr('id'); // or var clickedBtnID =
   alert('you clicked on button #' + clickedBtnID);

HTML5: Slider with two inputs possible?

I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying @Wildhoney's code a bit and really like it.

function getVals(){_x000D_
  // Get slider values_x000D_
  var parent = this.parentNode;_x000D_
  var slides = parent.getElementsByTagName("input");_x000D_
    var slide1 = parseFloat( slides[0].value );_x000D_
    var slide2 = parseFloat( slides[1].value );_x000D_
  // Neither slider will clip the other, so make sure we determine which is larger_x000D_
  if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }_x000D_
  var displayElement = parent.getElementsByClassName("rangeValues")[0];_x000D_
      displayElement.innerHTML = slide1 + " - " + slide2;_x000D_
window.onload = function(){_x000D_
  // Initialize Sliders_x000D_
  var sliderSections = document.getElementsByClassName("range-slider");_x000D_
      for( var x = 0; x < sliderSections.length; x++ ){_x000D_
        var sliders = sliderSections[x].getElementsByTagName("input");_x000D_
        for( var y = 0; y < sliders.length; y++ ){_x000D_
          if( sliders[y].type ==="range" ){_x000D_
            sliders[y].oninput = getVals;_x000D_
            // Manually trigger event first time to display values_x000D_
  section.range-slider {_x000D_
    position: relative;_x000D_
    width: 200px;_x000D_
    height: 35px;_x000D_
    text-align: center;_x000D_
section.range-slider input {_x000D_
    pointer-events: none;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    left: 0;_x000D_
    top: 15px;_x000D_
    width: 200px;_x000D_
    outline: none;_x000D_
    height: 18px;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
section.range-slider input::-webkit-slider-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    outline: 0;_x000D_
section.range-slider input::-moz-range-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 10;_x000D_
    -moz-appearance: none;_x000D_
    width: 9px;_x000D_
section.range-slider input::-moz-range-track {_x000D_
    position: relative;_x000D_
    z-index: -1;_x000D_
    background-color: rgba(0, 0, 0, 1);_x000D_
    border: 0;_x000D_
section.range-slider input:last-of-type::-moz-range-track {_x000D_
    -moz-appearance: none;_x000D_
    background: none transparent;_x000D_
    border: 0;_x000D_
  section.range-slider input[type=range]::-moz-focus-outer {_x000D_
  border: 0;_x000D_
<!-- This block can be reused as many times as needed -->_x000D_
<section class="range-slider">_x000D_
  <span class="rangeValues"></span>_x000D_
  <input value="5" min="0" max="15" step="0.5" type="range">_x000D_
  <input value="10" min="0" max="15" step="0.5" type="range">_x000D_

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

I was facing the same error. The solution that worked for me is:

From the server end, while returning JSON response, change the content-type: text/html

Now the browsers (Chrome, Firefox and IE8) do not give an error.

Python pandas insert list into a cell

As mentionned in this post pandas: how to store a list in a dataframe?; the dtypes in the dataframe may influence the results, as well as calling a dataframe or not to be assigned to.

How to document a method with parameter(s)?

If you plan to use Sphinx to document your code, it is capable of producing nicely formatted HTML docs for your parameters with their 'signatures' feature.

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

  • ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row. An example might be SELECT @@IDENTITY AS 'Identity'.
  • ExecuteReader is used for any result set with multiple rows/columns (e.g., SELECT col1, col2 from sometable).
  • ExecuteNonQuery is typically used for SQL statements without results (e.g., UPDATE, INSERT, etc.).

How can I convert String[] to ArrayList<String>

List myList = new ArrayList();
Collections.addAll(myList, filesOrig); not found error

public static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=dbName";
public static final String USERNAME = "xxxx";
public static final String PASSWORD = "xxxx";

 *  This method
    @param args     command line argument
public static void main(String[] args)
        Connection connection;
        connection = DriverManager.getConnection(MainDriver.URL,MainDriver.USERNAME,
        String query ="select * from employee";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(query);
            System.out.print("First Name: " + resultSet.getString("first_name"));
            System.out.println("  Last Name: " + resultSet.getString("last_name"));                
   }catch(Exception ex)

How to retrieve a single file from a specific revision in Git?

Using git show

To complete your own answer, the syntax is indeed

git show object
git show $REV:$FILE
git show somebranch:from/the/root/myfile.txt
git show HEAD^^^:test/

The command takes the usual style of revision, meaning you can use any of the following:

  1. branch name (as suggested by ash)
  2. HEAD + x number of ^ characters
  3. The SHA1 hash of a given revision
  4. The first few (maybe 5) characters of a given SHA1 hash

Tip It's important to remember that when using "git show", always specify a path from the root of the repository, not your current directory position.

(Although Mike Morearty mentions that, at least with git, you can specify a relative path by putting "./" at the beginning of the path. For example:

git show HEAD^^:./


Using git restore

With Git 2.23+ (August 2019), you can also use git restore which replaces the confusing git checkout command

git restore -s <SHA1>     -- afile
git restore -s somebranch -- afile

That would restore on the working tree only the file as present in the "source" (-s) commit SHA1 or branch somebranch.
To restore also the index:

git restore -s <SHA1> -SW -- afile

(-SW: short for --staged --worktree)

Using low-level git plumbing commands

Before git1.5.x, this was done with some plumbing:

git ls-tree <rev>
show a list of one or more 'blob' objects within a commit

git cat-file blob <file-SHA1>
cat a file as it has been committed within a specific revision (similar to svn cat). use git ls-tree to retrieve the value of a given file-sha1

git cat-file -p $(git-ls-tree $REV $file | cut -d " " -f 3 | cut -f 1)::

git-ls-tree lists the object ID for $file in revision $REV, this is cut out of the output and used as an argument to git-cat-file, which should really be called git-cat-object, and simply dumps that object to stdout.

Note: since Git 2.11 (Q4 2016), you can apply a content filter to the git cat-file output.

See commit 3214594, commit 7bcf341 (09 Sep 2016), commit 7bcf341 (09 Sep 2016), and commit b9e62f6, commit 16dcc29 (24 Aug 2016) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 7889ed2, 21 Sep 2016)

git config diff.txt.textconv "tr A-Za-z N-ZA-Mn-za-m <"
git cat-file --textconv --batch

Note: "git cat-file --textconv" started segfaulting recently (2017), which has been corrected in Git 2.15 (Q4 2017)

See commit cc0ea7c (21 Sep 2017) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfbc2fc, 28 Sep 2017)

What is the difference between vmalloc and kmalloc?

Linux Kernel Development by Robert Love (Chapter 12, page 244 in 3rd edition) answers this very clearly.

Yes, physically contiguous memory is not required in many of the cases. Main reason for kmalloc being used more than vmalloc in kernel is performance. The book explains, when big memory chunks are allocated using vmalloc, kernel has to map the physically non-contiguous chunks (pages) into a single contiguous virtual memory region. Since the memory is virtually contiguous and physically non-contiguous, several virtual-to-physical address mappings will have to be added to the page table. And in the worst case, there will be (size of buffer/page size) number of mappings added to the page table.

This also adds pressure on TLB (the cache entries storing recent virtual to physical address mappings) when accessing this buffer. This can lead to thrashing.

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");

How to extract text from the PDF document?

I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :

Hope it helps everone

How to check if IsNumeric

You should use TryParse method which Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

    int intParsed;
    if(int.TryParse(txtMyText.Text.Trim(),out intParsed))
        // perform your code

How to split a string in shell and get the last field

$ echo "a b c d e" | tr ' ' '\n' | tail -1

Simply translate the delimiter into a newline and choose the last entry with tail -1.

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

I've discovered that if the filename has 300 in it, AdBlock blocks the page and throws a ERR_BLOCKED_BY_CLIENT error.

Convert object array to hash map, indexed by an attribute value of the Object

There are better ways to do this as explained by other posters. But if I want to stick to pure JS and ol' fashioned way then here it is:

var arr = [
    { key: 'foo', val: 'bar' },
    { key: 'hello', val: 'world' },
    { key: 'hello', val: 'universe' }

var map = {};
for (var i = 0; i < arr.length; i++) {
    var key = arr[i].key;
    var value = arr[i].val;

    if (key in map) {
    } else {
        map[key] = [value];


This app won't run unless you update Google Play Services (via Bazaar)

I have found a nice solution which let you test your app in the emulator and also doesn't require you to revert to the older version of the library. See an answer to Stack Overflow question Running Google Maps v2 on the Android emulator.

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java

How can I export the schema of a database in PostgreSQL?

I am running Postgres 9.6 where I had to export a particular schema along with data.

I used the following command:

pg_dump.exe -U username -d databasename -n schemaname > C:\mylocation\mydumpfilename.dmp

If you want only the schema without data, use the switch s instead of n

Below is the pg_dump switch list:

C:\Program Files\PostgreSQL\9.6\bin>pg_dump --help
pg_dump dumps a database as a text file or to other formats.

  pg_dump [OPTION]... [DBNAME]

General options:
  -f, --file=FILENAME          output file or directory name
  -F, --format=c|d|t|p         output file format (custom, directory, tar,
                               plain text (default))
  -j, --jobs=NUM               use this many parallel jobs to dump
  -v, --verbose                verbose mode
  -V, --version                output version information, then exit
  -Z, --compress=0-9           compression level for compressed formats
  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock
  -?, --help                   show this help, then exit

Options controlling the output content:
  -a, --data-only              dump only the data, not the schema
  -b, --blobs                  include large objects in dump
  -c, --clean                  clean (drop) database objects before recreating
  -C, --create                 include commands to create database in dump
  -E, --encoding=ENCODING      dump the data in encoding ENCODING
  -n, --schema=SCHEMA          dump the named schema(s) only
  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)
  -o, --oids                   include OIDs in dump
  -O, --no-owner               skip restoration of object ownership in
                               plain-text format
  -s, --schema-only            dump only the schema, no data
  -S, --superuser=NAME         superuser user name to use in plain-text format
  -t, --table=TABLE            dump the named table(s) only
  -T, --exclude-table=TABLE    do NOT dump the named table(s)
  -x, --no-privileges          do not dump privileges (grant/revoke)
  --binary-upgrade             for use by upgrade utilities only
  --column-inserts             dump data as INSERT commands with column names
  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting
  --disable-triggers           disable triggers during data-only restore
  --enable-row-security        enable row security (dump only content user has
                               access to)
  --exclude-table-data=TABLE   do NOT dump data for the named table(s)
  --if-exists                  use IF EXISTS when dropping objects
  --inserts                    dump data as INSERT commands, rather than COPY
  --no-security-labels         do not dump security label assignments
  --no-synchronized-snapshots  do not use synchronized snapshots in parallel jobs
  --no-tablespaces             do not dump tablespace assignments
  --no-unlogged-table-data     do not dump unlogged table data
  --quote-all-identifiers      quote all identifiers, even if not key words
  --section=SECTION            dump named section (pre-data, data, or post-data)
  --serializable-deferrable    wait until the dump can run without anomalies
  --snapshot=SNAPSHOT          use given snapshot for the dump
  --strict-names               require table and/or schema include patterns to
                               match at least one entity each
                               use SET SESSION AUTHORIZATION commands instead of
                               ALTER OWNER commands to set ownership

Connection options:
  -d, --dbname=DBNAME      database to dump
  -h, --host=HOSTNAME      database server host or socket directory
  -p, --port=PORT          database server port number
  -U, --username=NAME      connect as specified database user
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)
  --role=ROLENAME          do SET ROLE before dump

If no database name is supplied, then the PGDATABASE environment
variable value is used.

Report bugs to <[email protected]>.

taking input of a string word by word

(This is for the benefit of others who may refer)

You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.

using namespace std;

    char word[50];
        //Do stuff with word[]

Trying to load local JSON file to show data in a html page using JQuery

I have Used Following Methods But non of them worked:

   // 2 Method Failed

            '' +
            function (response) {
                console.log("> ", response);
// 3 Method Failed

    var jqxhr = $.getJSON( "./json/movies-coming-soon.json", function() {
  console.log( "success" );
  .done(function() {
    console.log( "second success" );
  .fail(function() {
    console.log( "error" );
  .always(function() {
    console.log( "complete" );

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {
  console.log( "second complete" );

// 4 Method Failed

   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: '',
   success: function(jsondata){

// 5 Method Failed

   url: '',
   headers: {  'Access-Control-Allow-Origin': 'htt://site allowed to access' },
   dataType: 'jsonp',
   /* etc */
   success: function(jsondata){


What worked For me to simply download chrome extension called "200 OK!" or Web server for chrome and write my code like this:

// Worked After local Web Server

        $(document).ready(function () {
            $.getJSON('./json/movies-coming-soon.json', function (data) {
              var movie_name = '';
              var movie_year = '';
                    movie_name += item.title + "  " + item.year + "<br> <br>"





Its because you can not access local file without running local web server as per CORS policy so in order to running it you must have some host server.

Java JTable setting Column Width

Reading the remark of Kleopatra (her 2nd time she suggested to have a look at javax.swing.JXTable, and now I Am sorry I didn't have a look the first time :) ) I suggest you follow the link

I had this solution for the same problem: (but I suggest you follow the link above) On resize the table, scale the table column widths to the current table total width. to do this I use a global array of ints for the (relative) column widths):

private int[] columnWidths=null;

I use this function to set the table column widths:

public void setColumnWidths(int[] widths){
    int nrCols=table.getModel().getColumnCount();

    //current width of the table:
    int totalWidth=table.getWidth();
    int totalWidthRequested=0;
    int nrRequestedWidths=columnWidths.length;
    int defaultWidth=(int)Math.floor((double)totalWidth/(double)nrCols);

    for(int col=0;col<nrCols;col++){
        int width = 0;
    //Note: for the not defined columns: use the defaultWidth
        log.fine("Setting column widths: nr of columns do not match column widths requested");
    //calculate the scale for the column width
    double factor=(double)totalWidth/(double)totalWidthRequested;

    for(int col=0;col<nrCols;col++){
        int width = defaultWidth;
            //scale the requested width to the current table width

When setting the data I call:


and on changing I call the ComponentListener set to the parent of the table (in my case the JScrollPane that is the container of my table):

public void componentResized(ComponentEvent componentEvent) {

note that the JTable table is also global:

private JTable table;

And here I set the listener:

    scrollPane=new JScrollPane(table);

IntelliJ does not show project folders

I have a better solution that worked for me and it might work for you. No need to delete the whole .idea folder as this way you lose the whole project. It is possible that you just accidentally excluded all folders in project settings. I also found that project folders disappeared. I was trying to find out how to disable indexing, so I was looking at Project Settings -> Modules and I clicked on Excluded to see if I could add the whole project there to ignore it for indexing. It didn't do anything and I couldn't drag and drop the folder under Excluded. What I didn't realize is that simply clicking "Excluded", IntelliJ automatically moves the folder to Excluded and all folders disappeared in Project Explorer. "Excluded" button changes background to gray, which means exclusion is active. This is a very poor user interface because it is hardly noticeable and clicking this button has a far-reaching impact on your project.


  1. Open Project Settings -> Modules
  2. If Excluded is highlighted, click on it
  3. Click Apply or Close

Result: Folders in your project show up again

Really bad bad bad UI design! Source and Excluded buttons look like tabs when they work in fact as "Checkboxes"!

Be careful, just clicking Sources or Excluded seems like an innocent selection of tab without any visible effect, yet it has far-reaching consequences, basically adding or removing files from the build process.

How do android screen coordinates work?

enter image description here

This image presents both orientation(Landscape/Portrait)

To get MaxX and MaxY, read on.

For Android device screen coordinates, below concept will work.

Display mdisp = getWindowManager().getDefaultDisplay();
Point mdispSize = new Point();
int maxX = mdispSize.x; 
int maxY = mdispSize.y;

EDIT:- ** **for devices supporting android api level older than 13. Can use below code.

    Display mdisp = getWindowManager().getDefaultDisplay();
    int maxX= mdisp.getWidth();
    int maxY= mdisp.getHeight();

(x,y) :-

1) (0,0) is top left corner.

2) (maxX,0) is top right corner

3) (0,maxY) is bottom left corner

4) (maxX,maxY) is bottom right corner

here maxX and maxY are screen maximum height and width in pixels, which we have retrieved in above given code.

How to reshape data from long to wide format

Using base R aggregate function:

aggregate(value ~ name, dat1, I)

# name           value.1  value.2  value.3  value.4
#1 firstName      0.4145  -0.4747   0.0659   -0.5024
#2 secondName    -0.8259   0.1669  -0.8962    0.1681

alert a variable value

Note, while the above answers are correct, if you want, you can do something like:

alert("The variable named x1 has value:  " + x1);

Best way to get application folder path

Note that not all of these methods will return the same value. In some cases, they can return the same value, but be careful, their purposes are different:


returns the StartupPath parameter (can be set when run the application)


returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).

How to update and delete a cookie?

The cookie API is kind of lame. Let me clarify...

You don't update cookies; you overwrite them:

    document.cookie = "username=Arnold"; // Create 'username' cookie
    document.cookie = "username=Chuck"; // Update, i.e. overwrite, the 'username' cookie to "Chuck"

You also don't delete cookies; you expire them by setting the expires key to a time in the past (-1 works too).


Call to undefined function oci_connect()

Simple steps

You need to enable the below extension in your php.ini


by removing the ";" so that the results will below:


Download Oracle Instant Client:- Preferably 32 bit. 32 bit will also work on 64 bit. You can just google: download oracle instant client windows 32 bit. Use version 11 of the client because extension=php_oci8_11.g.dll won't work with 12. Unzip the package into a location such as C:\Oracle\instantclient_11_2.

Finally modify the System's PATH Environment Variable with end location, under system variables not user variables

Then you need to restart the System for PATH changes to fully propagate.

If you just restart XAMPP/WAMP without restarting the machine the Client's DLL files (i.e. OCL.dll) will not be loaded (nor found) by PHP's php_oci8_11g.dll extension.

How do I get the path to the current script with Node.js?

Use __dirname!!


The directory name of the current module. This the same as the path.dirname() of the __filename.

Example: running node example.js from /Users/mjr

// Prints: /Users/mjr
// Prints: /Users/mjr

For ESModules you would want to use: import.meta.url

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

Valid characters in a Java class name

You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...

Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.

An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

However, see this question for whether or not you should do that.

How do I deal with installing peer dependencies in Angular CLI?

Peer dependency warnings, more often than not, can be ignored. The only time you will want to take action is if the peer dependency is missing entirely, or if the version of a peer dependency is higher than the version you have installed.

Let's take this warning as an example:

npm WARN @angular/[email protected] requires a peer of @angular/[email protected] but none is installed. You must install peer dependencies yourself.

With Angular, you would like the versions you are using to be consistent across all packages. If there are any incompatible versions, change the versions in your package.json, and run npm install so they are all synced up. I tend to keep my versions for Angular at the latest version, but you will need to make sure your versions are consistent for whatever version of Angular you require (which may not be the most recent).

In a situation like this:

npm WARN [email protected] requires a peer of @angular/core@^2.4.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.

If you are working with a version of Angular that is higher than 4.0.0, then you will likely have no issues. Nothing to do about this one then. If you are using an Angular version under 2.4.0, then you need to bring your version up. Update the package.json, and run npm install, or run npm install for the specific version you need. Like this:

npm install @angular/[email protected] --save

You can leave out the --save if you are running npm 5.0.0 or higher, that version saves the package in the dependencies section of the package.json automatically.

In this situation:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

You are running Windows, and fsevent requires OSX. This warning can be ignored.

Hope this helps, and have fun learning Angular!

Python multiprocessing PicklingError: Can't pickle <type 'function'>

I'd use pathos.multiprocesssing, instead of multiprocessing. pathos.multiprocessing is a fork of multiprocessing that uses dill. dill can serialize almost anything in python, so you are able to send a lot more around in parallel. The pathos fork also has the ability to work directly with multiple argument functions, as you need for class methods.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> p = Pool(4)
>>> class Test(object):
...   def plus(self, x, y): 
...     return x+y
>>> t = Test()
>>>, x, y)
[4, 6, 8, 10]
>>> class Foo(object):
...   @staticmethod
...   def work(self, x):
...     return x+1
>>> f = Foo()
>>> p.apipe(, f, 100)
<processing.pool.ApplyResult object at 0x10504f8d0>
>>> res = _
>>> res.get()

Get pathos (and if you like, dill) here:

Why functional languages?

Microsoft is really pushing F# with the next version on Visual Studio. It is a hybrid language such as Scala and integrates very nicely with the rest of the .net framework. I think a lot of Microsoft shops are going to use it to speed-up the development of highly parallel data-processing applications and functions.

Bootstrap Accordion button toggle "data-parent" not working

As Blazemonger said, #parent, .panel and .collapse have to be direct descendants. However, if You can't change Your html, You can do workaround using bootstrap events and methods with the following code:

$('#your-parent .collapse').on('', function (e) {
    var actives = $('#your-parent').find('.in, .collapsing');
    actives.each( function (index, element) {

How to fluently build JSON in Java?

The reference implementation includes a fluent interface. Check out JSONWriter and its toString-implementing subclass JSONStringer

How to get first and last day of previous month (with timestamp) in SQL Server


commons httpclient - Adding query string parameters to GET/POST request

Here is how you would add query string parameters using HttpClient 4.2 and later:

URIBuilder builder = new URIBuilder("");
builder.setParameter("parts", "all").setParameter("action", "finish");

HttpPost post = new HttpPost(;

The resulting URI would look like:

Is there a limit on an Excel worksheet's name length?

I use the following vba code where filename is a string containing the filename I want, and Function RemoveSpecialCharactersAndTruncate is defined below:

worksheet1.Name = RemoveSpecialCharactersAndTruncate(filename)

'Function to remove special characters from file before saving

Private Function RemoveSpecialCharactersAndTruncate$(ByVal FormattedString$)
    Dim IllegalCharacterSet$
    Dim i As Integer
'Set of illegal characters
    IllegalCharacterSet$ = "*." & Chr(34) & "//\[]:;|=,"
    'Iterate through illegal characters and replace any instances
    For i = 1 To Len(IllegalCharacterSet) - 1
        FormattedString$ = Replace(FormattedString$, Mid(IllegalCharacterSet, i, 1), "")
    'Return the value capped at 31 characters (Excel limit)
    RemoveSpecialCharactersAndTruncate$ = Left(FormattedString$, _
                           Application.WorksheetFunction.Min(Len(FormattedString), 31))
End Function

jQuery animated number counter from zero to value

You can get the element itself in .each(), try this instead of using this

$('.Count').each(function (index, value) {
    jQuery({ Counter: 0 }).animate({ Counter: value.text() }, {
        duration: 1000,
        easing: 'swing',
        step: function () {

How can I decrypt a password hash in PHP?

I need to decrypt a password. The password is crypted with password_hash function.

$password = 'examplepassword';
$crypted = password_hash($password, PASSWORD_DEFAULT);

Its not clear to me if you need password_verify, or you are trying to gain unauthorized access to the application or database. Other have talked about password_verify, so here's how you could gain unauthorized access. Its what bad guys often do when they try to gain access to a system.

First, create a list of plain text passwords. A plain text list can be found in a number of places due to the massive data breaches from companies like Adobe. Sort the list and then take the top 10,000 or 100,000 or so.

Second, create a list of digested passwords. Simply encrypt or hash the password. Based on your code above, it does not look like a salt is being used (or its a fixed salt). This makes the attack very easy.

Third, for each digested password in the list, perform a select in an attempt to find a user who is using the password:

$sql_script = 'select * from USERS where password="'.$digested_password.'"'

Fourth, profit.

So, rather than picking a user and trying to reverse their password, the bad guy picks a common password and tries to find a user who is using it. Odds are on the bad guy's side...

Because the bad guy does these things, it would behove you to not let users choose common passwords. In this case, take a look at ProCheck, EnFilter or Hyppocrates (et al). They are filtering libraries that reject bad passwords. ProCheck achieves very high compression, and can digest multi-million word password lists into a 30KB data file.

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

I thought I will share how I resolved the same issue "Error Could not open lib\amd64\jvm.cfg". I found the Java run time Jre7 is missing amd64 folder under lib. However, I have 1.7.0_25 JDK which is having jre folder and also having amd64.

I moved the original contents of jre7 folder to a backup file and copied everything from 1.7.0_25\jre.

Now I am not getting this error anymore and able to proceed with scene builder.

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

"Sub or Function not defined" when trying to run a VBA script in Outlook

I think you need to update your libraries so that your VBA code works, your using ms outlook

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

How to get host name with port from a http or https request

You can use HttpServletRequest.getScheme() to retrieve either "http" or "https".

Using it along with HttpServletRequest.getServerName() should be enough to rebuild the portion of the URL you need.

You don't need to explicitly put the port in the URL if you're using the standard ones (80 for http and 443 for https).

Edit: If your servlet container is behind a reverse proxy or load balancer that terminates the SSL, it's a bit trickier because the requests are forwarded to the servlet container as plain http. You have a few options:

1) Use HttpServletRequest.getHeader("x-forwarded-proto") instead; this only works if your load balancer sets the header correctly (Apache should afaik).

2) Configure a RemoteIpValve in JBoss/Tomcat that will make getScheme() work as expected. Again, this will only work if the load balancer sets the correct headers.

3) If the above don't work, you could configure two different connectors in Tomcat/JBoss, one for http and one for https, as described in this article.

How to manually reload Google Map with JavaScript

Yes, you can 'refresh' a Google Map like this:

google.maps.event.trigger(map, 'resize');

This basically sends a signal to your map to redraw it.

Hope that helps!

Simple linked list in C++

This is the most simple example I can think of in this case and is not tested. Please consider that this uses some bad practices and does not go the way you normally would go with C++ (initialize lists, separation of declaration and definition, and so on). But that are topics I can't cover here.

#include <iostream>
using namespace std;

class LinkedList{
    // Struct inside the class LinkedList
    // This is one node which is not needed by the caller. It is just
    // for internal work.
    struct Node {
        int x;
        Node *next;

// public member
    // constructor
        head = NULL; // set head to NULL

    // destructor
        Node *next = head;
        while(next) {              // iterate over all elements
            Node *deleteMe = next;
            next = next->next;     // save pointer to the next element
            delete deleteMe;       // delete the current entry
    // This prepends a new value at the beginning of the list
    void addValue(int val){
        Node *n = new Node();   // create new Node
        n->x = val;             // set value
        n->next = head;         // make the node point to the next node.
                                //  If the list is empty, this is NULL, so the end of the list --> OK
        head = n;               // last but not least, make the head point at the new node.

    // returns the first element in the list and deletes the Node.
    // caution, no error-checking here!
    int popValue(){
        Node *n = head;
        int ret = n->x;

        head = head->next;
        delete n;
        return ret;

// private member
    Node *head; // this is the private member variable. It is just a pointer to the first Node

int main() {
    LinkedList list;


    cout << list.popValue() << endl;
    cout << list.popValue() << endl;
    cout << list.popValue() << endl;
    // because there is no error checking in popValue(), the following
    // is undefined behavior. Probably the program will crash, because
    // there are no more values in the list.
    // cout << list.popValue() << endl;
    return 0;

I would strongly suggest you to read a little bit about C++ and Object oriented programming. A good starting point could be this:

EDIT: added a pop function and some output. As you can see the program pushes 3 values 5, 10, 20 and afterwards pops them. The order is reversed afterwards because this list works in stack mode (LIFO, Last in First out)

presentViewController and displaying navigation bar

If you use NavigationController in Swift 2.x

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let targetViewController = storyboard.instantiateViewControllerWithIdentifier("targetViewControllerID") as? TargetViewController
self.navigationController?.pushViewController(targetViewController!, animated: true)

How to access a dictionary key value present inside a list?

Index the list then the dict.

print L[1]['d']

cmake and libpthread

target_compile_options solution above is wrong, it won't link the library.




target_link_libraries(XXX PUBLIC pthread)


set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)

What is getattr() exactly and how do I use it?

I have tried in Python2.7.17

Some of the fellow folks already answered. However I have tried to call getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.

Example Code:

Example 1:

    class GETATT_VERIFY():
       name = "siva"
       def __init__(self):
           print "Ok"
       def set_value(self):
           self.value = "myself"
           print "oooh"
    obj = GETATT_VERIFY()
    print getattr(GETATT_VERIFY, 'name')
    getattr(obj, 'set_value')()
    print obj.value

what innerHTML is doing in javascript?

The innerHTML fetches content depending on the id/name and replaces them.

<!DOCTYPE html>_x000D_
 <title>Learn JavaScript</title>_x000D_
<button type = "button"_x000D_
onclick="document.getElementById('demo').innerHTML = Date()"> <!--fetches the content with id demo and changes the innerHTML content to Date()-->_x000D_
Click for date_x000D_
<h3 id = 'demo'>Before Button is clicked this content will be Displayed the inner content of h3 tag with id demo and once you click the button this will be replaced by the Date() ,which prints the current date and time </h3> _x000D_

When you click the button,the content in h3 will be replaced by innerHTML assignent i.e Date() .

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative -

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

password=yourpassword or exclude to force entry

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

FlutterError: Unable to load asset

I ran into this issue and very nearly gave up on Flutter until I stumbled upon the cause. In my case what I was doing was along the following lines

static Future<String> resourceText(String resName) async
  ZLibCodec zlc = new ZLibCodec(gzip:false,raw:true,level:9);
  var data= await rootBundle.load('assets/path/to/$resName');
  String result = new 
  return puzzle;
 } catch(e)
  debugPrint('Resource Error $resName $e');
  return ''; 

static Future<String> fallBackText(String textName) async
 if (testCondtion) return 'Some Required Text';
 else return resourceText('default');

where Some Required Text was a text string sent back if the testCondition was being met. Failing that I was trying to pick up default text from the app resources and send that back instead. My mistake was in the line return resourceText('default');. After changing it to read return await resourceText('default') things worked just as expected.

This issue arises from the fact that rootBundle.load operates asynchronously. In order to return its results correctly we need to await their availability which I had failed to do. It strikes me as slightly surprising that neither the Flutter VSCode plugin nor the Flutter build process flag up this as an error. While there may well be other reasons why rootBundle.load fails this answer will, hopefully, help others who are running into mysterious asset load failures in Flutter.

How to extract .war files in java? ZIP vs JAR

Like you said, a jar is a zip file (not a special type, but just a plain old zip), so either library could be made to work. The reasoning is that the average person, seeing a *.zip extension, tends to unzip it. Since the app server wants it unzipped, a simple rename keeps people from unzipping it simply out of habit. Likewise, *.war file also should remain uncompressed.

java.util.jar basically just adds additional functionality to with very little extra overhead. Let the java.util.jar be a helper in posting, etc... and use it.

Align text in JLabel to the right

This can be done in two ways.

JLabel Horizontal Alignment

You can use the JLabel constructor:

JLabel(String text, int horizontalAlignment) 

To align to the right:

JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);

JLabel also has setHorizontalAlignment:


This assumes the component takes up the whole width in the container.

Using Layout

A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout:

    Box box = Box.createVerticalBox();
    JLabel label1 = new JLabel("test1, the beginning");

    JLabel label2 = new JLabel("test2, some more");

    JLabel label3 = new JLabel("test3");


How to get the Full file path from URI

I had a hard time trying to figure this out on Xamarin. From the suggestions above I came up with this solution.

private string getRealPathFromURI(Android.Net.Uri contentUri)
    string filename = "";
    string thepath = "";
    Android.Net.Uri filePathUri;
    ICursor cursor = this.ContentResolver.Query(contentUri, null, null, null, null);

    if (cursor.MoveToFirst())
        int column_index = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
        filePathUri = Android.Net.Uri.Parse(cursor.GetString(column_index));
        filename = filePathUri.LastPathSegment;
        thepath = filePathUri.Path;

    return thepath;

Differences between dependencyManagement and dependencies in Maven

The difference between the two is best brought in what seems a necessary and sufficient definition of the dependencyManagement element available in Maven website docs:


"Default dependency information for projects that inherit from this one. The dependencies in this section are not immediately resolved. Instead, when a POM derived from this one declares a dependency described by a matching groupId and artifactId, the version and other values from this section are used for that dependency if they were not already specified." [ ]

It should be read along with some more information available on a different page:

“..the minimal set of information for matching a dependency reference against a dependencyManagement section is actually {groupId, artifactId, type, classifier}. In many cases, these dependencies will refer to jar artifacts with no classifier. This allows us to shorthand the identity set to {groupId, artifactId}, since the default for the type field is jar, and the default classifier is null.” [ ]

Thus, all the sub-elements (scope, exclusions etc.,) of a dependency element--other than groupId, artifactId, type, classifier, not just version--are available for lockdown/default at the point (and thus inherited from there onward) you specify the dependency within a dependencyElement. If you’d specified a dependency with the type and classifier sub-elements (see the first-cited webpage to check all sub-elements) as not jar and not null respectively, you’d need {groupId, artifactId, classifier, type} to reference (resolve) that dependency at any point in an inheritance originating from the dependencyManagement element. Else, {groupId, artifactId} would suffice if you do not intend to override the defaults for classifier and type (jar and null respectively). So default is a good keyword in that definition; any sub-element(s) (other than groupId, artifactId, classifier and type, of course) explicitly assigned value(s) at the point you reference a dependency override the defaults in the dependencyManagement element.

So, any dependency element outside of dependencyManagement, whether as a reference to some dependencyManagement element or as a standalone is immediately resolved (i.e. installed to the local repository and available for classpaths).

How to store arrays in MySQL?

A sidenote to consider, you can store arrays in Postgres.

Python - Check If Word Is In A String

This small function compares all search words in given text. If all search words are found in text, returns length of search, or False otherwise.

Also supports unicode string search.

def find_words(text, search):
    """Find exact words"""
    dText   = text.split()
    dSearch = search.split()

    found_word = 0

    for text_word in dText:
        for search_word in dSearch:
            if search_word == text_word:
                found_word += 1

    if found_word == len(dSearch):
        return lenSearch
        return False


find_words('çelik güray ankara', 'güray ankara')

file_get_contents behind a proxy?

Depending on how the proxy login works stream_context_set_default might help you.

$context  = stream_context_set_default(
      'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass')
$result = file_get_contents('http://..../...');

Posting raw image data as multipart/form-data in curl

In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.

This is the relevant part of the server code that helped:

if (isset($_POST['btnUpload']))
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
    $headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
    $postfields = array("filedata" => "@$filedata", "filename" => $filename);
    $ch = curl_init();
    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => true,
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $postfields,
        CURLOPT_INFILESIZE => $filesize,
    ); // cURL options
    curl_setopt_array($ch, $options);
        $info = curl_getinfo($ch);
        if ($info['http_code'] == 200)
            $errmsg = "File uploaded successfully";
        $errmsg = curl_error($ch);
    $errmsg = "Please select the file";

html form should look something like:

<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
  <td align="center">:</td>
  <td><input name="file" type="file" id="file"/></td>
  <td align="center">&nbsp;</td>
  <td><input name="btnUpload" type="submit" value="Upload" /></td>

How to create a laravel hashed password

ok, this is a extract from the make function in hash.php

    $work = str_pad(8, 2, '0', STR_PAD_LEFT);

    // Bcrypt expects the salt to be 22 base64 encoded characters including
    // dots and slashes. We will get rid of the plus signs included in the
    // base64 data and replace them with dots.
    if (function_exists('openssl_random_pseudo_bytes'))
        $salt = openssl_random_pseudo_bytes(16);
        $salt = Str::random(40);

    $salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);

    echo crypt('yourpassword', '$2a$'.$work.'$'.$salt);

Just copy/paste it into a php file and run it.

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

use global scope on your $con and put it inside your getPosts() function like so.

function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
        echo "<div class=\"blogsnippet\">";
        echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
        echo "</div>";

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

How to insert close button in popover for Bootstrap

This works with multiple popovers and I also added a little big of extra JS to handle the z-index issues that happen with overlapping popovers:


var $elements = $('.my-popover');
$elements.each(function () {
    var $element = $(this);

        html: true,
        placement: 'top',
        container: $('body'), // This is just so the btn-group doesn't get messed up... also makes sorting the z-index issue easier
        content: $('#content').html()

    $element.on('', function (e) {
        var popover = $'bs.popover');
        if (typeof popover !== "undefined") {
            var $tip = popover.tip();
            zindex = $tip.css('z-index');

            $tip.find('.close').bind('click', function () {

            $tip.mouseover(function (e) {
                $tip.css('z-index', function () {
                    return zindex + 1;
                .mouseout(function () {
                $tip.css('z-index', function () {
                    return zindex;


<div class="container-fluid">
    <div class="well popover-demo col-md-12">
        <div class="page-header">
             <h3 class="page-title">Bootstrap 3.1.1 Popovers with a close button</h3>

        <div class="btn-group">
            <button type="button" data-title="Popover One" class="btn btn-primary my-popover">Click me!</button>
            <button type="button" data-title="Popover Two" class="btn btn-primary my-popover">Click me!</button>
            <button type="button" data-title="Popover Three (and the last one gets a really long title!)" class="btn btn-primary my-popover">Click me!</button>
<div id="content" class="hidden">
    <button type="button" class="close">&times;</button>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>


/* Make the well behave for the demo */
 .popover-demo {
    margin-top: 5em
/* Popover styles */
 .popover .close {
    top: 8px;
    right: 10px;
.popover-title {
    padding-right: 30px;

How can I create 2 separate log files with one log4j config file?

Modify your file accordingly:


Change the log levels for each logger depending to your needs.

How to load external scripts dynamically in Angular?

You can use following technique to dynamically load JS scripts and libraries on demand in your Angular project. will contain the path of the script either locally or on a remote server and a name that will be used to load the script dynamically

 interface Scripts {
    name: string;
    src: string;
export const ScriptStore: Scripts[] = [
    {name: 'filepicker', src: ''},
    {name: 'rangeSlider', src: '../../../assets/js/ion.rangeSlider.min.js'}

script.service.ts is an injectable service that will handle the loading of script, copy script.service.ts as it is

import {Injectable} from "@angular/core";
import {ScriptStore} from "./";

declare var document: any;

export class ScriptService {

private scripts: any = {};

constructor() {
    ScriptStore.forEach((script: any) => {
        this.scripts[] = {
            loaded: false,
            src: script.src

load(...scripts: string[]) {
    var promises: any[] = [];
    scripts.forEach((script) => promises.push(this.loadScript(script)));
    return Promise.all(promises);

loadScript(name: string) {
    return new Promise((resolve, reject) => {
        //resolve if already loaded
        if (this.scripts[name].loaded) {
            resolve({script: name, loaded: true, status: 'Already Loaded'});
        else {
            //load script
            let script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = this.scripts[name].src;
            if (script.readyState) {  //IE
                script.onreadystatechange = () => {
                    if (script.readyState === "loaded" || script.readyState === "complete") {
                        script.onreadystatechange = null;
                        this.scripts[name].loaded = true;
                        resolve({script: name, loaded: true, status: 'Loaded'});
            } else {  //Others
                script.onload = () => {
                    this.scripts[name].loaded = true;
                    resolve({script: name, loaded: true, status: 'Loaded'});
            script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'});


Inject this ScriptService wherever you need it and load js libs like this

this.script.load('filepicker', 'rangeSlider').then(data => {
    console.log('script loaded ', data);
}).catch(error => console.log(error));

no matching function for call to ' '

You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);

cout << "Numarul complex este: " << firstComplexNumber << endl;
//                                  ^^^^^^^^^^^^^^^^^^ No need to dereference now

// ...

Complex::distanta(firstComplexNumber, secondComplexNumber);

Accessing dictionary value by index in python

While you can do

value = d.values()[index]

It should be faster to do

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

Also, note that this assumes that your index is not negative

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
  printf("%09.3f\n", 4917.24);
  return 0;


$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

Removing leading zeroes from a field in a SQL statement

I had the same need and used this:

        when left(column,1) = '0' 
        then right(column, (len(column)-1)) 
        else column 

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

You always need to check for XACT_STATE(), irrelevant of the XACT_ABORT setting. I have an example of a template for stored procedures that need to handle transactions in the TRY/CATCH context at Exception handling and nested transactions:

create procedure [usp_my_procedure_name]
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
            save transaction usp_my_procedure_name;

        -- Do the actual work here

        if @trancount = 0   
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(),
               @message = ERROR_MESSAGE(), 
               @xstate = XACT_STATE();
        if @xstate = -1
        if @xstate = 1 and @trancount = 0
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
    end catch   

how to convert an RGB image to numpy array?

You can also use matplotlib for this.

from matplotlib.image import imread

img = imread('abc.tiff')

output: <class 'numpy.ndarray'>

Pass entire form as data in jQuery Ajax function

A good jQuery option to do this is through FormData. This method is also suited when sending files through a form!

<form id='test' method='post' enctype='multipart/form-data'>
   <input type='text' name='testinput' id='testinput'>
   <button type='submit'>submit</button>

Your send function in jQuery would look like this:

$( 'form#test' ).submit( function(){
   var data = new FormData( $( 'form#test' )[ 0 ] );

   $.ajax( {
      processData: false,
      contentType: false,

      data: data,
      dataType: 'json',
      type: $( this ).attr( 'method' );
      url: 'yourapi.php',
      success: function( feedback ){
         console.log( "the feedback from your API: " + feedback );

to add data to your form you can either use a hidden input in your form, or you add it on the fly:

var data = new FormData( $( 'form#test' )[ 0 ] );
data.append( 'command', 'value_for_command' );

difference between primary key and unique key

A primary key’s main features are:

It must contain a unique value for each row of data. It cannot contain null values. Only one Primary key in a table.

A Unique key’s main features are:

It can also contain a unique value for each row of data.

It can also contain null values.

Multiple Unique keys in a table.

How to run .NET Core console app from the command line

You can also run your app like any other console applications but only after the publish.

Let's suppose you have the simple console app named MyTestConsoleApp. Open the package manager console and run the following command:

dotnet publish -c Debug -r win10-x64 

-c flag mean that you want to use the debug configuration (in other case you should use Release value) - r flag mean that your application will be runned on Windows platform with x64 architecture.

When the publish procedure will be finished your will see the *.exe file located in your bin/Debug/publish directory.

Now you can call it via command line tools. So open the CMD window (or terminal) move to the directory where your *.exe file is located and write the next command:

>> MyTestConsoleApp.exe argument-list

For example:

>> MyTestConsoleApp.exe --input some_text -r true

How can I get the max (or min) value in a vector?

Assuming cloud is int cloud[10] you can do it like this: int *p = max_element(cloud, cloud + 10);

How to append rows to an R data frame

Update with purrr, tidyr & dplyr

As the question is already dated (6 years), the answers are missing a solution with newer packages tidyr and purrr. So for people working with these packages, I want to add a solution to the previous answers - all quite interesting, especially .

The biggest advantage of purrr and tidyr are better readability IMHO. purrr replaces lapply with the more flexible map() family, tidyr offers the super-intuitive method add_row - just does what it says :)

map_df(1:1000, function(x) { df %>% add_row(x = x, y = toString(x)) })

This solution is short and intuitive to read, and it's relatively fast:

   map_df(1:1000, function(x) { df %>% add_row(x = x, y = toString(x)) })
   user  system elapsed 
   0.756   0.006   0.766

It scales almost linearly, so for 1e5 rows, the performance is:

  map_df(1:100000, function(x) { df %>% add_row(x = x, y = toString(x)) })
   user  system elapsed 
 76.035   0.259  76.489 

which would make it rank second right after data.table (if your ignore the placebo) in the benchmark by @Adam Ryczkowski:

nr  function      time
4   data.frame    228.251 
3   sqlite        133.716
2   data.table      3.059
1   rbindlist     169.998 
0   placebo         0.202

How to style a checkbox using CSS

SCSS / SASS Implementation

A more modern approach

For those using SCSS (or easily converted to SASS), the following will be helpful. Effectively, make an element next to the checkbox, which is the one that you will style. When the checkbox is clicked, the CSS restyles the sister element (to your new, checked style). Code is below:

label.checkbox {_x000D_
  input[type="checkbox"] {_x000D_
    visibility: hidden;_x000D_
    display: block;_x000D_
    height: 0;_x000D_
    width: 0;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    &:checked + span {_x000D_
      background: $accent;_x000D_
  span {_x000D_
    cursor: pointer;_x000D_
    height: 15px;_x000D_
    width: 15px;_x000D_
    border: 1px solid $accent;_x000D_
    border-radius: 2px;_x000D_
    display: inline-block;_x000D_
    transition: all 0.2s $interpol;_x000D_
<label class="checkbox">_x000D_
    <input type="checkbox" />_x000D_
    Label text_x000D_

Setting Environment Variables for Node to retrieve

Step 1: Add your environment variables to their appropriate file. For example, your staging environment could be called .env.staging, which contains the environment variables USER_ID and USER_KEY, specific to your staging environment.

Step 2: In your package.json file, add the following:

"scripts": {
  "build": "sh -ac '. ./.env.${REACT_APP_ENV}; react-scripts build'",
  "build:staging": "REACT_APP_ENV=staging npm run build",
  "build:production": "REACT_APP_ENV=production npm run build",

then call it in your deploy script like this:

npm run build:staging

Super simple set up and works like a charm!


How can I get sin, cos, and tan to use degrees instead of radians?

Create your own conversion function that applies the needed math, and invoke those instead.

Use of for_each on map elements

You can iterate through a std::map object. Each iterator will point to a std::pair<const T,S> where T and S are the same types you specified on your map.

Here this would be:

for (std::map<int, MyClass>::iterator it = Map.begin(); it != Map.end(); ++it)

If you still want to use std::for_each, pass a function that takes a std::pair<const int, MyClass>& as an argument instead.


void CallMyMethod(std::pair<const int, MyClass>& pair) // could be a class static method as well

And pass it to std::for_each:

std::for_each(Map.begin(), Map.end(), CallMyMethod);

Get IPv4 addresses from Dns.GetHostEntry()


lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0).ToString()


lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(1).ToString()

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<context:component-scan base-package="" /> 

tells Spring to scan those packages for Annotations.


registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.

This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.

You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.

Check out the 3.1 documentation to learn more.

Typescript es6 import module "File is not a module error"

How can I accomplish that?

Your example declares a TypeScript < 1.5 internal module, which is now called a namespace. The old module App {} syntax is now equivalent to namespace App {}. As a result, the following works:

// test.ts
export namespace App {
    export class SomeClass {
        getName(): string {
            return 'name';

// main.ts
import { App } from './test';
var a = new App.SomeClass();

That being said...

Try to avoid exporting namespaces and instead export modules (which were previously called external modules). If needs be you can use a namespace on import with the namespace import pattern like this:

// test.ts
export class SomeClass {
    getName(): string {
        return 'name';

// main.ts
import * as App from './test'; // namespace import pattern
var a = new App.SomeClass();

Powershell folder size of folders without listing Subdirectories

At the answer from @squicc if you amend this line: $topDir = Get-ChildItem -directory "C:\test" with -force then you will be able to see the hidden directories also. Without this, the size will be different when you run the solution from inside or outside the folder.

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

I've had the same problem, what I did:

Just added a condition if(!IsPostBack) and it works fine :)

Calculating distance between two geographic locations

I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.

C# example

    /// <summary>
    /// Calculates the distance between two locations using the Great Circle Distance algorithm
    /// <see cref=""/>
    /// </summary>
    /// <param name="first"></param>
    /// <param name="second"></param>
    /// <returns></returns>
    private static double DistanceBetween(GeoLocation first, GeoLocation second)
        double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));

        double centralAngleBetweenLocationsInRadians = Math.Acos(
            Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
            Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *

        const double earthRadiusInMeters = 6357 * 1000;

        return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;

    private static double ToRadians(double degrees)
        return degrees * Math.PI / 180;

Plotting in a non-blocking way with Matplotlib

I figured out that the plt.pause(0.001) command is the only thing needed and nothing else. and plt.draw() are unnecessary and / or blocking in one way or the other. So here is a code that draws and updates a figure and keeps going. Essentially plt.pause(0.001) seems to be the closest equivalent to matlab's drawnow.

Unfortunately those plots will not be interactive (they freeze), except you insert an input() command, but then the code will stop.

The documentation of the plt.pause(interval) command states:

If there is an active figure, it will be updated and displayed before the pause...... This can be used for crude animation.

and this is pretty much exactly what we want. Try this code:

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(0, 51)               # x coordinates  
for z in range(10, 50):

    y = np.power(x, z/10)          # y coordinates of plot for animation

    plt.cla()                      # delete previous plot
    plt.axis([-50, 50, 0, 10000])  # set axis limits, to avoid rescaling
    plt.plot(x, y)                 # generate new plot
    plt.pause(0.1)                 # pause 0.1 sec, to force a plot redraw

When to use self over $this?

I ran into the same question and the simple answer is:

  • $this requires an instance of the class
  • self:: doesn't

Whenever you are using static methods or static attributes and want to call them without having an object of the class instantiated you need to use self: to call them, because $this always requires on object to be created.

Adding custom HTTP headers using JavaScript

I think the easiest way to accomplish it is to use querystring instead of HTTP headers.

Add text to textarea - Jquery

Just append() the text nodes:


Dynamically converting java object of Object class to a given class when class name is known

private static <T extends Object> T cast(Object obj) {
    return (T) obj;

Bootstrap navbar Active State not working

the next answer is for those who have a multi-level menu:

var url = window.location.href;

var els = document.querySelectorAll(".dropdown-menu a");
for (var i = 0, l = els.length; i < l; i++) {
    var el = els[i];
    if (el.href === url) {
       var parent = el.closest(".main-nav"); // add this class for the top level "li" to get easy the parent

Exeample how it works

How to install a plugin in Jenkins manually

Update for Docker: use the script. It takes a list of plugin names minus the '-plugin' extension. See the description here. replaces the deprecated which now warns :

WARN: is deprecated, please switch to

To use a plugins.txt as per see this issue and this workaround:

RUN /usr/local/bin/ $(cat /usr/share/jenkins/plugins.txt | tr '\n' ' ')

Shortest way to check for null and assign another value if not

My guess is the best you can come up with is

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
                                                      : planRec.approved_by.ToString();

Of course since you're hinting at the fact that approved_by is an object (which cannot equal ""), this would be rewritten as

this.approved_by = (planRec.approved_by ?? string.Empty).ToString();

How can I parse a time string containing milliseconds in it with python?

My first thought was to try passing it '30/03/09 16:31:32.123' (with a period instead of a colon between the seconds and the milliseconds.) But that didn't work. A quick glance at the docs indicates that fractional seconds are ignored in any case...

Ah, version differences. This was reported as a bug and now in 2.6+ you can use "%S.%f" to parse it.

What does "#pragma comment" mean?

These link in the libraries selected in MSVC++.

Determine Whether Integer Is Between Two Other Integers?

The trouble with comparisons is that they can be difficult to debug when you put a >= where there should be a <=

#                             v---------- should be <
if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")

Python lets you just write what you mean in words

if number in xrange(10000, 30001): # ok you have to remember 30000 + 1 here :)

In Python3, you need to use range instead of xrange.

edit: People seem to be more concerned with microbench marks and how cool chaining operations. My answer is about defensive (less attack surface for bugs) programming.

As a result of a claim in the comments, I've added the micro benchmark here for Python3.5.2

$ python3.5 -m timeit "5 in range(10000, 30000)"
1000000 loops, best of 3: 0.266 usec per loop
$ python3.5 -m timeit "10000 <= 5 < 30000"
10000000 loops, best of 3: 0.0327 usec per loop

If you are worried about performance, you could compute the range once

$ python3.5 -m timeit -s "R=range(10000, 30000)" "5 in R"
10000000 loops, best of 3: 0.0551 usec per loop

How can I add a column that doesn't allow nulls in a Postgresql database?

Since rows already exist in the table, the ALTER statement is trying to insert NULL into the newly created column for all of the existing rows. You would have to add the column as allowing NULL, then fill the column with the values you want, and then set it to NOT NULL afterwards.

"Parameter not valid" exception loading System.Drawing.Image

Just Follow this to Insert values into database

//Connection String


sqlQuery = "INSERT INTO [dbo].[Client] ([Client_ID],[Client_Name],[Phone],[Address],[Image]) VALUES('" + txtClientID.Text + "','" + txtClientName.Text + "','" + txtPhoneno.Text + "','" + txtaddress.Text + "',@image)";

                cmd = new SqlCommand(sqlQuery, con);
                cmd.Parameters.Add("@image", SqlDbType.Image);
                cmd.Parameters["@image"].Value = img;
            //img is a byte object
           ** /*MemoryStream ms = new MemoryStream();
            byte[] img = ms.ToArray();*/**


What is the difference between HAVING and WHERE in SQL?

HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.


Your project contains error(s), please fix it before running it

I had the exact same problem after updating the SDK and ADT. My issue was resolved by deleting the .android folder (hidden) under C:\Users\USERNAME\

How to set and reference a variable in a Jenkinsfile

A complete example for scripted pipepline:

            withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
                sh 'bash'

How to prevent Right Click option using jquery

Try this:

    return false;

How do I navigate to a parent route from a child route?

Do you want a link/HTML or do you want to route imperatively/in code?

Link: The RouterLink directive always treats the provided link as a delta to the current URL:

[routerLink]="['./child']"     // or

// with route param     ../../parent;abc=xyz
[routerLink]="['../../parent', {abc: 'xyz'}]"
// with query param and fragment   ../../parent?p1=value1&p2=v2#frag
[routerLink]="['../../parent']" [queryParams]="{p1: 'value', p2: 'v2'}" fragment="frag"

With RouterLink, remember to import and use the directives array:

import { ROUTER_DIRECTIVES } from '@angular/router';
    directives: [ROUTER_DIRECTIVES],

Imperative: The navigate() method requires a starting point (i.e., the relativeTo parameter). If none is provided, the navigation is absolute:

import { Router, ActivatedRoute } from '@angular/router';
constructor(private router: Router, private route: ActivatedRoute) {}
this.router.navigate(["../../parent"], {relativeTo: this.route});
this.router.navigate(["../sibling"],   {relativeTo: this.route});
this.router.navigate(["./child"],      {relativeTo: this.route}); // or
this.router.navigate(["child"],        {relativeTo: this.route});

// with route param     ../../parent;abc=xyz
this.router.navigate(["../../parent", {abc: 'xyz'}], {relativeTo: this.route});
// with query param and fragment   ../../parent?p1=value1&p2=v2#frag
this.router.navigate(["../../parent"], {relativeTo: this.route, 
    queryParams: {p1: 'value', p2: 'v2'}, fragment: 'frag'});

// navigate without updating the URL 
this.router.navigate(["../../parent"], {relativeTo: this.route, skipLocationChange: true});

Ruby sleep or delay less than a second?

Pass float to sleep, like sleep 0.1

Why do some functions have underscores "__" before and after the function name?

The other respondents are correct in describing the double leading and trailing underscores as a naming convention for "special" or "magic" methods.

While you can call these methods directly ([10, 20].__len__() for example), the presence of the underscores is a hint that these methods are intended to be invoked indirectly (len([10, 20]) for example). Most python operators have an associated "magic" method (for example, a[x] is the usual way of invoking a.__getitem__(x)).

ASP.NET MVC controller actions that return JSON or partial html

Flexible approach to produce different outputs based on the request

public class AuctionsController : Controller
  public ActionResult Auction(long id)
    var db = new DataContext();
    var auction = db.Auctions.Find(id);

    // Respond to AJAX requests
    if (Request.IsAjaxRequest())
      return PartialView("Auction", auction);

    // Respond to JSON requests
    if (Request.IsJsonRequest())
      return Json(auction);

    // Default to a "normal" view with layout
    return View("Auction", auction);

The Request.IsAjaxRequest() method is quite simple: it merely checks the HTTP headers for the incoming request to see if the value of the X-Requested-With header is XMLHttpRequest, which is automatically appended by most browsers and AJAX frameworks.

Custom extension method to check whether the request is for json or not so that we can call it from anywhere, just like the Request.IsAjaxRequest() extension method:

using System;
using System.Web;

public static class JsonRequestExtensions
  public static bool IsJsonRequest(this HttpRequestBase request)
    return string.Equals(request["format"], "json");

Source :

How do I send email with JavaScript without opening the mail client?

You need a server-side support to achieve this. Basically your form should be posted (AJAX is fine as well) to the server and that server should connect via SMTP to some mail provider and send that e-mail.

Even if it was possible to send e-mails directly using JavaScript (that is from users computer), the user would still have to connect to some SMTP server (like, provide SMTP credentials, etc. This is normally handled on the server-side (in your application), which knows these credentials.

How to check for null/empty/whitespace values with a single test?

Use below query and it works

SELECT column_name FROM table_name where isnull(column_name,'') <> ''

TypeError: can't use a string pattern on a bytes-like object in re.findall()

The problem is that your regex is a string, but html is bytes:

>>> type(html)
<class 'bytes'>

Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.

You can either decode the bytes to a string:

html = html.decode('ISO-8859-1')  # encoding may vary!
title = re.findall(pattern, html)  # no more error

Or use a bytes regex:

regex = rb'<title>(,+?)</title>'
#        ^

In this particular context, you can get the encoding from the response headers:

with urllib.request.urlopen(url) as response:
    encoding ='charset', 'utf8')
    html =

See the urlopen documentation for more details.

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

There is also some more detail on the use of <mvc:annotation-driven /> in the Spring docs. In a nutshell, <mvc:annotation-driven /> gives you greater control over the inner workings of Spring MVC. You don't need to use it unless you need one or more of the features outlined in the aforementioned section of the docs.

Also, there are other "annotation-driven" tags available to provide additional functionality in other Spring modules. For example, <transaction:annotation-driven /> enables the use of the @Transaction annotation, <task:annotation-driven /> is required for @Scheduled et al...

How do I access refs of a child component in the parent component

I think this guide explains it pretty well

class Field extends Component {
  const { inputRef } = this.props;
  render() {
    return (
      <input type="text" ref={inputRef} />

class MyComponent extends Component {
  componentDidMount() {

  render() {
    return (
        Hello, <Field inputRef={node => this.inputNode = node} />

Detect click event inside iframe

The tinymce API takes care of many events in the editors iframe. I strongly suggest to use them. Here is an example for the click handler

// Adds an observer to the onclick event using tinyMCE.init
   setup : function(ed) {
      ed.onClick.add(function(ed, e) {
           console.debug('Iframe clicked:' +;

How do I get my C# program to sleep for 50 msec?


Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")

Just remove the ; to make it work for as well.

Polynomial time and exponential time

polynomial time O(n)^k means Number of operations are proportional to power k of the size of input

exponential time O(k)^n means Number of operations are proportional to the exponent of the size of input

How to cancel a local git commit

If you're in the middle of a commit (i.e. in your editor already), you can cancel it by deleting all lines above the first #. That will abort the commit.

So you can delete all lines so that the commit message is empty, then save the file:

It should look like this.

You'll then get a message that says Aborting commit due to empty commit message..


You can also delete all the lines and the result will be exactly the same.

To delete all lines in vim (if that is your default editor), once you're in the editor, type gg to go to the first line, then dG to delete all lines. Finally, write and quit the file with wq and your commit will be aborted.

How can I submit a POST form using the <a href="..."> tag?

I use a jQuery script to create "shadow" forms for my POSTable links.

Instead of <a href="/some/action?foo=bar">, I write <a data-post="/some/action" data-var-foo="bar" href="#do_action_foo_bar">. The script makes a hidden form with hidden inputs, and submits it when the link is clicked.

    .each(function() {
        let href = $(this).data("post"); if (!href) return;
        let $form = $("<form></form>").attr({ method:"POST",action:href }).css("display","none")
        let data = $(this).data()
        for (let dat in data) {
            if (dat.startsWith("postVar")) {
                let varname = dat.substring(7).toLowerCase()  // postVarId -> id
                let varval = data[dat]
                $form.append($("<input/>").attr({ type:"hidden",name:varname,value:varval }))
    .click(function(ev) {
        if ($(this).data("postform")) $(this).data("postform").submit(); else console.error("No .postform set in <a data-post>")
<script src=""></script>
<a data-post="/some/action" data-var-foo="bar" href="#do_action_foo_bar">click me</a>

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string


escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)


Available on npm as escape-string-regexp

npm install --save escape-string-regexp


See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.





Test Case: A typical url


>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");

  // test escapeRegExp("/path/to/res?search=this.that")

Specify the from user when sending email using the mail command

mail -r [email protected] -R [email protected]

-r = from-addr -R = reply-to addr

The author has indicated his version of mail doesn't support this flag. But if you have a version that does this works fine.

Android ClassNotFoundException: Didn't find class on path

I had this problem for quite a while, and like everybody else the answers above didn't apply to my project.

In my project I had linked up a project to my project and it was throwing ClassDefNotFoundError every time some code for the other project was executed.

So this was my solution. I went to project properties of my project and Java Build Path. Pressed the "Source"-tab and "link source" from src-folder of the other project to my own project and named a new folder "core-src".

Hopes this solution helps someone

How to read data from a file in Lua

You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.

local open =

local function read_file(path)
    local file = open(path, "rb") -- r read mode and b binary mode
    if not file then return nil end
    local content = file:read "*a" -- *a or *all reads the whole file
    return content

local fileContent = read_file("foo.html");
print (fileContent);

Detecting user leaving page with react-router

Using history.listen

For example like below:

In your component,

componentWillMount() {
    this.props.history.listen(() => {
      // Detecting, user has changed URL;

Mean filter for smoothing images in Matlab

I = imread('peppers.png');
H = fspecial('average', [5 5]);
I = imfilter(I, H);

Note that filters can be applied to intensity images (2D matrices) using filter2, while on multi-dimensional images (RGB images or 3D matrices) imfilter is used.

Also on Intel processors, imfilter can use the Intel Integrated Performance Primitives (IPP) library to accelerate execution.

Byte Array to Hex String

If you have a numpy array, you can do the following:

>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()

How to add white spaces in HTML paragraph

This can be done easily and cleanly with float.



    <li>Item 1 <span class="right">(1)</span></li>
    <li>Item 2 <span class="right">(2)</span></li>


ul {
    width: 10em
.right {
    float: right

What is the right way to check for a null string in Objective-C?

if(textfield.text.length == 0){
   //do your desired work

MongoDB: How to update multiple documents with a single command?

Thanks for sharing this, I used with 2.6.7 and following query just worked,

for all docs:

db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:true})

for single doc:

db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:false})

How to catch exception correctly from http.request()?

There are several ways to do this. Both are very simple. Each of the examples works great. You can copy it into your project and test it.

The first method is preferable, the second is a bit outdated, but so far it works too.

1) Solution 1

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

  declarations: [
  imports: [
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
export class AppModule { }

// File - product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators'; // Important! Be sure to connect operators

// There may be your any object. For example, we will have a product object
import { ProductModule } from './product.module';

export class ProductService{
    // Initialize the properties.
    constructor(private http: HttpClient, private product: ProductModule){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will get into catchError and catch them.
    getProducts(): Observable<ProductModule[]>{
        const url = 'YOUR URL HERE';
        return this.http.get<ProductModule[]>(url).pipe(
            tap((data: any) => {
            catchError((err) => {
                throw 'Error in source. Details: ' + err; // Use console.log(err) for detail

2) Solution 2. It is old way but still works.

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

  declarations: [
  imports: [
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
export class AppModule { }

// File - product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';

export class ProductService{
    // Initialize the properties.
    constructor(private http: Http){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will to into catch section and catch error.
        const url = '';
        return this.http.get(url).map(
            (response: Response) => {
                const data = response.json();
                return data;
            (error: Response) => {
                return Observable.throw(error);

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"


pip install --trusted-host --trusted-host --trusted-host -r requirements.txt -vvv

pip install --trusted-host --trusted-host --trusted-host <packageName> -vvv

So, Having 30+ answers to the question already, but nothing was working for me in June 2020 (while in lockdown ).
all were given in different moments of past. I will try to make this answer work for all times in future. The problem is while pip installs package it tries to connect with host URL where package is stored and doesn't trust the URL while downloading it.

There are two ways we can solve this: Easy and non-secure: 1. check which URL is hit by pip to download the package.

pip install <packageName> -vvv

if you will carefully check the output, you will see it might be going to some URL like or may be

if it is, just add trusted host option to the command like below:

pip install --trusted-host --trusted-host --trusted-host <packageName> -vvv

or if you are using requirements file:

pip install --trusted-host --trusted-host --trusted-host -r requirements.txt -vvv

Secure way:

Go to each of these URL and download their public cert (just google how to download), create a chain, store it as .pem file and run below command:

pip --cert YourPemFile.pem install <packageName>

OS X Terminal Colors

Check what $TERM gives: mine is xterm-color and ls -alG then does colorised output.

How to get POST data in WebAPI?

I had a problem with sending a request with multiple parameters.

I've solved it by sending a class, with the old parameters as properties.

<form action="http://localhost:12345/api/controller/method" method="post">
    <input type="hidden" name="name1" value="value1" />
    <input type="hidden" name="name2" value="value2" />
    <input type="submit" name="submit" value="Submit" />

Model class:

public class Model {
    public string Name1 { get; set; }
    public string Name2 { get; set; }


public void method(Model m) {
    string name = m.Name1;

Print second last column/field in awk

You weren't far from the result! This does it:

awk '{NF--; print $NF}' file

This decrements the number of fields in one, so that $NF contains the former penultimate.


Let's generate some numbers and print them on groups of 5:

$ seq 12 | xargs -n5
1 2 3 4 5
6 7 8 9 10
11 12

Let's print the penultimate on each line:

$ seq 12 | xargs -n5 | awk '{NF--; print $NF}'

Bootstrap 4 - Glyphicons migration?

If you are using Laravel 5.6, it comes with Bootstrap 4. All you need to is:

npm install and npm install open-iconic --save

At /resources/assets/sass/app.scss change the line of of Google font import on line 2 to

@import '~open-iconic/font/css/open-iconic-bootstrap';

All you need to do now is

npm run watch

and include

<link rel="stylesheet" href="{{asset('css/app.css')}}">

on top of master blade file and <script src="{{asset('js/app.js')}}"></script> before closing body tag. You will get Bootstrap 4 and icon.

Usage is <span class="oi oi-cog"></span>

Refer here for icon details: Open Iconic: Recommended by Bootstrap 4

If on other project than Laravel, you can just do import @import 'node_modules/open-iconic/font/css/open-iconic-bootstrap-min.css'; in your style file.

Hope this helps. Happy trying.

Why aren't Xcode breakpoints functioning?

if you using Xcode Version 11.1 (11A1027) make sure you are not using the app store credential(provisioning profiles) , because in this case build will be installed and no log or debugger will work, it took me hell lot of time to figure it out , updated Xcode has chagned . now build getting installed on the device without any warning.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e

You can read more about dictionaries here.

How to check which locks are held on a table

You can also use the built-in sp_who2 stored procedure to get current blocked and blocking processes on a SQL Server instance. Typically you'd run this alongside a SQL Profiler instance to find a blocking process and look at the most recent command that spid issued in profiler.

Full Page <iframe>

This is cross-browser and fully responsive:

    position: fixed;
    top: 0px;
    bottom: 0px;
    right: 0px;
    width: 100%;
    border: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    z-index: 999999;
    height: 100%;

Convert Go map to json

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

jsonString, err := json.Marshal(datas)

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

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

See this post for more details:

SQL Server Management Studio, how to get execution time down to milliseconds

I don't know about expanding the information bar.

But you can get the timings set as a default for all queries showing in the "Messages" tab.

When in a Query window, go to the Query Menu item, select "query options" then select "advanced" in the "Execution" group and check the "set statistics time" / "set statistics IO" check boxes. These values will then show up in the messages area for each query without having to remember to put in the set stats on and off.

You could also use Shift + Alt + S to enable client statistics at any time

Printing out a number in assembly language?

DOS Print 32 bit value stored in EAX with hexadecimal output (for 80386+)
(on 64 bit OS use DOSBOX)

    mov ax,@DATA        ; get the address of the data segment
    mov ds,ax           ; store the address in the data segment register
    mov eax,0FFFFFFFFh  ; 32 bit value (0 - FFFFFFFF) for example
; convert the value in EAX to hexadecimal ASCIIs
    mov di,OFFSET ASCII ; get the offset address
    mov cl,8            ; number of ASCII
P1: rol eax,4           ; 1 Nibble (start with highest byte)
    mov bl,al
    and bl,0Fh          ; only low-Nibble
    add bl,30h          ; convert to ASCII
    cmp bl,39h          ; above 9?
    jna short P2
    add bl,7            ; "A" to "F"
P2: mov [di],bl         ; store ASCII in buffer
    inc di              ; increase target address
    dec cl              ; decrease loop counter
    jnz P1              ; jump if cl is not equal 0 (zeroflag is not set)
; Print string
    mov ah,9            ; DS:DX->'$'-terminated string
    int 21h             ; maybe redirected under DOS 2+ for output to file
                        ; (using pipe character">") or output to printer

  ; terminate program...

ASCII DB "00000000",0Dh,0Ah,"$" ; buffer for ASCII string

Alternative string output directly to the videobuffer without using software interupts:

; Print string
    mov ax,0B800h       ; segment address of textmode video buffer
    mov es,ax           ; store address in extra segment register

    mov si,OFFSET ASCII ; get the offset address of the string

; using a fixed target address for example (screen page 0)
; Position`on screen = (Line_number*80*2) + (Row_number*2)

    mov di,(10*80*2)+(10*2)
    mov cl,8            ; number of ASCII
    cld                 ; clear direction flag

P3: lodsb  ; get the ASCII from the address in DS:SI + increase si
    stosb  ; write ASCII directly to the screen using ES:DI + increase di
    inc di ; step over attribut byte
    dec cl ; decrease counter
    jnz P3 ; repeat (print only 8 ASCII, not used bytes are: 0Dh,0Ah,"$")

; Hint: this directly output to the screen do not touch or move the cursor
; but feel free to modify..

UITableview: How to Disable Selection for Some Rows but Not Others

For Swift 4.0 for example:

cell.isUserInteractionEnabled = false
cell.contentView.alpha = 0.5

Adding click event for a button created dynamically using jQuery


$(document).on("click", "#btn_a", function(){
  alert ('button clicked');

to add the listener for the dynamically created button.


will give you the value of the button

Display / print all rows of a tibble (tbl_df)

You could also use

print(tbl_df(df), n=40)

or with the help of the pipe operator

df %>% tbl_df %>% print(n=40)

To print all rows specify tbl_df %>% print(n = Inf)

$(document).ready not Working

One possibility, take a look:

<script language="javascript" type="text/javascript" src="./jquery-3.1.1.slim.min.js" />


<script language="javascript" type="text/javascript" src="./jquery-3.1.1.slim.min.js"></script>

The first method is actually wrong, however the browser does not complain at all. You need to be sure that you are indeed closing the javascript tag in the proper way.

How to format a URL to get a file from Amazon S3?

Perhaps not what the OP was after, but for those searching the URL to simply access a readable object on S3 is more like:


Where <region> is something like s3-ap-southeast-2.

Click on the item in the S3 GUI to get the link for your bucket.

Installing Bootstrap 3 on Rails App

I think the most up to date gem for the new bootstrap version is form anjlab.

But I don't know if it currently works good with other gems like simple_form when you do rails generate simple_form:install --bootstrap, etc. you may have to edit some initializers or configurations to fit the new bootstrap version.

Center align a column in twitter bootstrap

The question is correctly answered here Center a column using Twitter Bootstrap 3

For odd rows: i.e., col-md-7 or col-large-9 use this

Add col-centered to the column you want centered.

<div class="col-lg-11 col-centered">    

And add this to your stylesheet:

float: none;
margin: 0 auto;

For even rows: i.e., col-md-6 or col-large-10 use this

Simply use bootstrap 3's offset col class. i.e.,

<div class="col-lg-10 col-lg-offset-1">

Check if user is using IE

This returns true for any version of Internet Explorer:

function isIE(userAgent) {
  userAgent = userAgent || navigator.userAgent;
  return userAgent.indexOf("MSIE ") > -1 || userAgent.indexOf("Trident/") > -1 || userAgent.indexOf("Edge/") > -1;

The userAgent parameter is optional and it defaults to the browser's user agent.

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


Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.

<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>

the reason i used php code in the middle is because i cant use it from the beginning..

the code below doesnt work for me:-

echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";

and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.

Which UUID version to use?

There are two different ways of generating a UUID.

If you just need a unique ID, you want a version 1 or version 4.

  • Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.

  • Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.

If you need to always generate the same UUID from a given name, you want a version 3 or version 5.

  • Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.

  • Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

The file extension tells you how the image is saved. Some of those formats just save the bits as they are, some compress the image in different ways, including lossless and lossy methods. The Web can tell you, although I know some of the patient responders will outline them here.

The web favors gif, jpg, and png, mostly. JPEG is the same (or very close) to jpg.

Pretty printing JSON from Jackson 2.2's ObjectMapper

the IDENT_OUTPUT did not do anything for me, and to give a complete answer that works with my jackson 2.2.3 jars:

public static void main(String[] args) throws IOException {

byte[] jsonBytes = Files.readAllBytes(Paths.get("C:\\data\\testfiles\\single-line.json"));

ObjectMapper objectMapper = new ObjectMapper();

Object json = objectMapper.readValue( jsonBytes, Object.class );

System.out.println( objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( json ) );

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

As explained in the section 9 of the official ECMA specification ( in JSON, the following chars have to be escaped:

  • U+0022 (", the quotation mark)
  • U+005C (\, the backslash or reverse solidus)
  • U+0000 to U+001F (the ASCII control characters)

In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:

  • U+002F (/)
  • U+0027 (')
  • U+003C (<)
  • U+003E (>)
  • U+0026 (&)
  • U+0085 (Next Line)
  • U+2028 (Line Separator)
  • U+2029 (Paragraph Separator)

Some of the above characters can be escaped with the following short escape sequences defined in the standard:

  • \" represents the quotation mark character (U+0022).
  • \\ represents the reverse solidus character (U+005C).
  • \/ represents the solidus character (U+002F).
  • \b represents the backspace character (U+0008).
  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).
  • \r represents the carriage return character (U+000D).
  • \t represents the character tabulation character (U+0009).

The other characters which need to be escaped will use the \uXXXX notation, that is \u followed by the four hexadecimal digits that encode the code point.

The \uXXXX can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).

How to set only time part of a DateTime variable in C#

you can't change the DateTime object, it's immutable. However, you can set it to a new value, for example:

var newDate = oldDate.Date + new TimeSpan(11, 30, 55);