Programs & Examples On #Jquery ui

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library.

How to get the date from jQuery UI datepicker

Try this, works like charm, gives the date you have selected. onsubmit form try to get this value:-

var date = $("#scheduleDate").datepicker({ dateFormat: 'dd,MM,yyyy' }).val();

Reference here

How to get jQuery dropdown value onchange event

Try like this

 $("#drop").change(function () {
        var end = this.value;
        var firstDropVal = $('#pick').val();

jQuery UI Dialog - missing close icon

I had the same exact issue, Maybe you already chececked this but got it solved just by placing the "images" folder in the same location as the jquery-ui.css

jQuery datepicker set selected date, on the fly

This example shows of how to use default value in the dropdown calendar and value in the text box. It also shows how to set default value to previous date.

selectedDate is another variable that holds current selected date of the calendar control

    var date = new Date();
    date.setDate(date.getDate() - 1);

        dateFormat: "yy-mm-dd",
        defaultDate: date,
        onSelect: function () {
            selectedDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));

    $("#datepicker").datepicker("setDate", date);

jQuery Dialog Box

I encountered the same issue (dialog would only open once, after closing, it wouldn't open again), and tried the solutions above which did not fix my problem. I went back to the docs and realized I had a fundamental misunderstanding of how the dialog works.

The $('#myDiv').dialog() command creates/instantiates the dialog, but is not necessarily the proper way to open it. The proper way to open it is to instantiate the dialog with dialog(), then use dialog('open') to display it, and dialog('close') to close/hide it. This means you'll probably want to set the autoOpen option to false.

So the process is: instantiate the dialog on document ready, then listen for the click or whatever action you want to show the dialog. Then it will work, time after time!

<script type="text/javascript"> 
        jQuery(document).ready( function(){       
            jQuery("#myButton").click( showDialog );

            //variable to reference window
            $myWindow = jQuery('#myDiv');

            //instantiate the dialog
            $myWindow.dialog({ height: 350,
                width: 400,
                modal: true,
                position: 'center',
                title:'Hello World',
                overlay: { opacity: 0.5, background: 'black'}

    //function to show dialog   
    var showDialog = function() {
        //if the contents have been hidden with css, you need this
        //open the dialog

    //function to close dialog, probably called by a button in the dialog
    var closeDialog = function() {



<input id="myButton" name="myButton" value="Click Me" type="button" />
<div id="myDiv" style="display:none">
    <p>I am a modal dialog</p>

Moving from position A to position B slowly with animation

I don't understand why other answers are about relative coordinates change, not absolute like OP asked in title.

$("#Friends").animate( {top:
  "-=" + (parseInt($("#Friends").css("top")) - 100) + "px"
} );

Jquery UI datepicker. Disable array of Dates

beforeShowDate didn't work for me, so I went ahead and developed my own solution:

               minDate: date,
               changeDate: true,
               changeMonth: true,
               changeYear: true,
               yearRange: "-120:+1",
               onSelect: function(selectedDateFormatted){

                     var selectedDate = $("#embeded_calendar").datepicker('getDate');



              var excludedDates = [ "10-20-2017","10-21-2016", "11-21-2016"];

              deactivateDates(new Date());

            function deactivateDates(selectedDate){
                      var thisMonthExcludedDates = thisMonthDates(selectedDate);
                      thisMonthExcludedDates = getDaysfromDate(thisMonthExcludedDates);
                       var excludedTDs = page.find('td[data-handler="selectDay"]').filter(function(){
                           return $.inArray( $(this).text(), thisMonthExcludedDates) >= 0

                   }, 10);

            function thisMonthDates(date){
              return $.grep( excludedDates, function( n){
                var dateParts = n.split("-");
                return dateParts[0] == date.getMonth() + 1  && dateParts[2] == date.getYear() + 1900;

            function getDaysfromDate(datesArray){
                  return  $.map( datesArray, function( n){
                    return n.split("-")[1]; 

jQuery Mobile how to check if button is disabled?

I had the same problem and I found this is working:

if ($("#deliveryNext").attr('disabled')) {
  // do sth if disabled
} else {
  // do sth if enabled 

If this gives you undefined then you can use if condition also.

When you evaluate undefined it will return false.

how to add a day to a date using jquery datepicker

The datepicker('setDate') sets the date in the datepicket not in the input.

You should add the date and set it in the input.

var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);

how to get value of selected item in autocomplete

I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.

(function() {
    var lastText = '';

    $('#MyTextBox'), {
        source: MyData
    .on('autocompleteselect autocompletefocus', function(ev, ui) {
        lastText = ui.item.label;'autocomplete-item', ui.item);
    .keyup(function(ev) {
        if (lastText != jqTag.val()) {
            // Clear when they stop typing
  'autocomplete-item', null);

            // Pass the event on as autocompleteclear so callers can listen for select/clear
            var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
            return jqTag.trigger(clearEv);

With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.

jQuery UI DatePicker - Change Date Format

My option is given below:

$(document).ready(function () {_x000D_
  var userLang = navigator.language || navigator.userLanguage;_x000D_
  var options = $.extend({},_x000D_
    $.datepicker.regional["ja"], {_x000D_
      dateFormat: "yy/mm/dd",_x000D_
      changeMonth: true,_x000D_
      changeYear: true,_x000D_
      highlightWeek: true_x000D_
#ui-datepicker-div {_x000D_
  font-size: 14px;_x000D_
<!DOCTYPE html>_x000D_
    <meta charset="UTF-8">_x000D_
    <link rel="stylesheet" type="text/css"_x000D_
    <script src=""></script>_x000D_
    <script src=""></script>_x000D_
    <script src=""></script>_x000D_
<h3>Japanese JQuery UI Datepicker</h3>_x000D_
<input type="text" id="japaneseCalendar"/>_x000D_

How to get date, month, year in jQuery UI datepicker?

$("#date").datepicker('getDate').getMonth() + 1; 

The month on the datepicker is 0 based (0-11), so add 1 to get the month as it appears in the date.

Vertical Tabs with JQuery?

I wouldn't expect vertical tabs to need different Javascript from horizontal tabs. The only thing that would be different is the CSS for presenting the tabs and content on the page. JS for tabs generally does no more than show/hide/maybe load content.

jQuery UI Dialog with ASP.NET button postback

Fantastic! This solved my problem with ASP:Button event not firing inside jQuery modal. Please note, using the jQuery UI modal with the following allows the button event to fire:

// Dialog Link
$('#dialog_link').click(function () {
    return false;

The following line is the key to get this working!


Trees in Twitter Bootstrap

Another great Treeview jquery plugin is

For an advance view you should check jquery-treetable

JQuery datepicker not working

I was stuck on an issue where datepicker() appeared to be doing nothing. It turned out that the issue was that the input was inside a Bootstrap "input-group" div. Simply taking the input out of the input-group resolved the issue.

jQuery dialog popup

It's quite simple, first HTML must be added:

<div id="dialog"></div>

Then, it must be initialized:

<script type="text/javascript">
  jQuery( document ).ready( function() {
    jQuery( '#dialog' ).dialog( { 'autoOpen': false } );

After this you can show it by code:

jQuery( '#dialog' ).dialog( 'open' );

Styling JQuery UI Autocomplete

Are you looking for this selector?:

.ui-menu .ui-menu-item a{

Ugly demo:

Just replace with your code:

.ui-menu .ui-menu-item a{
    color: #96f226;
    border-radius: 0px;
    border: 1px solid #454545;


check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

jQuery UI Tabs - How to Get Currently Selected Tab Index

    load:  function(event, ui){  
        var anchor =".ui-tabs-anchor");  
        var url = anchor.attr('href');  

In the url variable you will get the current tab's HREF / URL

How to make <input type="date"> supported on all browsers? Any alternatives?

<title>Date picker works for all browsers(IE, Firefox, Chrome)</title>
    var datefield = document.createElement("input")
    datefield.setAttribute("type", "date")
    if (datefield.type != "date") { // if browser doesn't support input type="date", load files for jQuery UI Date Picker
        document.write('<link href="" rel="stylesheet" type="text/css" />\n')
        document.write('<script src=""><\/script>\n')
        document.write('<script src=""><\/script>\n')

    if (datefield.type != "date") { // if browser doesn't support input type="date", initialize date picker widget:
        jQuery(function($) { // on document.ready
                dateFormat: 'yy-mm-dd'
                dateFormat: 'yy-mm-dd'
    <input name="start_date" id="start_date" type="date" required>
    <input name="end_date" id="end_date" required>

animating addClass/removeClass with jQuery

I was looking into this but wanted to have a different transition rate for in and out.

This is what I ended up doing:

.addedClass {
    background: #5eb4fc;

// js
function setParentTransition(id, prop, delay, style, callback) {
    $(id).css({'-webkit-transition' : prop + ' ' + delay + ' ' + style});
    $(id).css({'-moz-transition' : prop + ' ' + delay + ' ' + style});
    $(id).css({'-o-transition' : prop + ' ' + delay + ' ' + style});
    $(id).css({'transition' : prop + ' ' + delay + ' ' + style});
setParentTransition(id, 'background', '0s', 'ease', function() {

setTimeout(function() {
    setParentTransition(id, 'background', '2s', 'ease', function() {

This instantly turns the background color to #5eb4fc and then slowly fades back to normal over 2 seconds.

Here's a fiddle

How to auto adjust the div size for all mobile / tablet display formats?

I don't have much time and your jsfidle did not work right now.
But maybe this will help you getting started.

First of all you should avoid to put css in your html tags. Like align="center".
Put stuff like that in your css since it is much clearer and won't deprecate that fast.

If you want to design responsive layouts you should use media queries wich were introduced in css3 and are supported very well by now.

Example css:

@media screen and (min-width: 100px) and (max-width: 199px)
        width: 25px;

@media screen and (min-width: 200px) and (max-width: 299px)
        width: 50px;

You can use any css you want inside a media query.

How to get child element by index in Jquery?

var node = document.getElementsByClassName("second")[0].firstElementChild

Disclaimer: Browser compliance on getElementsByClassName and firstElementChild are shaky. DOM-shims fix those problems though.

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

Prevent jQuery UI dialog from setting focus to first textbox

My workaround:

open: function(){

Passing data to a jQuery UI Dialog

You could do it like this:

  • mark the <a> with a class, say "cancel"
  • set up the dialog by acting on all elements with class="cancel":

    $('a.cancel').click(function() { 
      var a = this; 
        buttons: {
          "Yes": function() {
             window.location = a.href; 
      return false;

(plus your other options)

The key points here are:

  • make it as unobtrusive as possible
  • if all you need is the URL, you already have it in the href.

However, I recommend that you make this a POST instead of a GET, since a cancel action has side effects and thus doesn't comply with GET semantics...

Make JQuery UI Dialog automatically grow or shrink to fit its contents

var w = $('#dialogText').text().length;

$("#dialog").dialog('option', 'width', (w * 10));

did what i needed it to do for resizing the width of the dialog.

jquery dialog save cancel button styling

I'm using jQuery UI 1.8.13 and the following configuration works as I need:

var buttonsConfig = [
        text: "Ok",
        "class": "ok",
        click: function() {
        text: "Annulla",
        "class": "cancel",
        click: function() {

    buttons: buttonsConfig
// ...

ps: remember to wrap "class" with quotes because it's a reserved word in js!

setting min date in jquery datepicker

Just want to add this for the future programmer.

This code limits the date min and max. The year is fully controlled by getting the current year as max year.

Hope this could help to anyone.

Here's the code.

var dateToday = new Date();
var yrRange = '2014' + ":" + (dateToday.getFullYear());

$(function () {
        showOn: 'button',
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        buttonImageOnly: true,
        yearRange: yrRange,
        buttonImage: 'calendar3.png',
        buttonImageOnly: true,
        minDate: new Date(2014,1-1,1),
        maxDate: '+50Y',

How to get HTML 5 input type="date" working in Firefox and/or IE 10

Thank Alexander, I found a way how to modify format for en lang. (Didn't know which lang uses such format)

 $.webshims.formcfg = {
        en: {
            dFormat: '/',
            dateSigns: '/',
            patterns: {
                d: "yy/mm/dd"


Long Press in JavaScript?

For me it's work with that code (with jQuery):

var int       = null,
    fired     = false;

var longclickFilm = function($t) {
        $body.css('background', 'red');
    clickFilm = function($t) {
        $t  = $t.clone(false, false);
        var $to = $('footer > div:first');
    touchStartFilm = function(event) {
        fired     = false;
        int       = setTimeout(function($t) {
            fired = true;
        }, 2000, $(this)); // 2 sec for long click ?
        return false;
    touchEndFilm = function(event) {
        if (fired) return false;
        else  clickFilm($(this));
        return false;

$('ul#thelist .thumbBox')
    .live('mousedown touchstart', touchStartFilm)
    .live('mouseup touchend touchcancel', touchEndFilm);

How to implement "confirmation" dialog in Jquery UI dialog?

NOTE: Not enough rep to comment but BineG's answer works perfectly in resolving postback issues with ASPX pages as highlighted by Homer and echo. In honor, here's a variation using a dynamic dialog.

$('#submit-button').bind('click', function(ev) {
    var $btn = $(this);
    $("<div />").html("Are you sure?").dialog({
        modal: true,
        title: "Confirmation",
        buttons: [{
            text: "Ok",
            click: function() {
        }, {
            text: "Cancel",
            click: function() {

load external URL into modal jquery ui dialog

var page = "";

var $dialog = $('<div></div>')
               .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
                   autoOpen: false,
                   modal: true,
                   height: 625,
                   width: 500,
                   title: "Some title"

Use this inside a function. This is great if you really want to load an external URL as an IFRAME. Also make sure that in you custom jqueryUI you have the dialog.

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

  <thead class="ui-widget-header">
  <tbody class="ui-widget-content">

And you don't need to use any code...

Switch to selected tab by name in Jquery-UI Tabs

$('#tabs').tabs('select', index); 

Methods `'select' isn't support in jquery ui 1.10.0.

I use this code , and work correctly:

  $('#tabs').tabs({ active: index });

jQuery UI autocomplete with item and id

From the Overview tab of jQuery autocomplete plugin:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

So your "two-dimensional" array could look like:

var $local_source = [{
    value: 1,
    label: "c++"
}, {
    value: 2,
    label: "java"
}, {
    value: 3,
    label: "php"
}, {
    value: 4,
    label: "coldfusion"
}, {
    value: 5,
    label: "javascript"
}, {
    value: 6,
    label: "asp"
}, {
    value: 7,
    label: "ruby"

You can access the label and value properties inside focus and select event through the ui argument using ui.item.label and ui.item.value.


Seems like you have to "cancel" the focus and select events so that it does not place the id numbers inside the text boxes. While doing so you can copy the value in a hidden variable instead. Here is an example.

Icons missing in jQuery UI

Having the right CSS and JS libraries helps, this solved it for me

<link rel="stylesheet" href="//">
<script src="//"></script>
<script src="//"></script>

Revert a jQuery draggable object back to its original container on out event of droppable

In case anyone's interested, here's my solution to the problem. It works completely independently of the Draggable objects, by using events on the Droppable object instead. It works quite well:

$(function() {
        opacity: .4,
        create: function(){$(this).data('position',$(this).position())},

        over: function(event, ui) {
        drop:function(event, ui){
        out:function(event, ui){
            $(ui.helper).mouseup(function() {

function snapToMiddle(dragger, target){
    var topMove = target.position().top -'position').top + (target.outerHeight(true) - dragger.outerHeight(true)) / 2;
    var leftMove= target.position().left -'position').left + (target.outerWidth(true) - dragger.outerWidth(true)) / 2;
function snapToStart(dragger, target){

Detect if a jQuery UI dialog box is open

Nick Craver's comment is the simplest to avoid the error that occurs if the dialog has not yet been defined:

if ($('#elem').is(':visible')) { 
  // do something

You should set visibility in your CSS first though, using simply:

#elem { display: none; }

How do I empty an input value with jQuery?

           $('#upload input, #upload select').each(
                    var input = $(this);
                        document.getElementById(input.attr('id')).value = null;
                    }else if(input.attr('type')=='checkbox'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else if(input.attr('type')=='radio'){
                        document.getElementById(input.attr('id')).checked = false;
                        document.getElementById(input.attr('id')).value = '';
                        //alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I had this problem once before where one dialog box was throwing this error, while all the others were working perfectly. The answer was because I had another element with the same id="dialogBox" else ware on the page. I found this thread during a search, so hopefully this will help someone else.

Set initial value in datepicker with jquery?

From jQuery:

Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

Code examples

Initialize a datepicker with the defaultDate option specified.

$(".selector").datepicker({ defaultDate: +7 });

Get or set the defaultDate option, after init.

var defaultDate = $(".selector").datepicker("option", "defaultDate");
$(".selector").datepicker("option", "defaultDate", +7);

After the datepicker is intialized you should also be able to set the date with:

$(/*selector*/).datepicker("setDate" , date)

Combine multiple JavaScript files into one JS file

I usually have it on a Makefile:

# All .js compiled into a single one.

    @find ./path/of/js -type f -name "*.js" | xargs cat > $(compiled)

Then you run:

make compile

I hope it helps.

How to make jQuery UI nav menu horizontal?

You can do this:

/* Clearfix for the menu */
.ui-menu:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;

and also set:

.ui-menu .ui-menu-item {
    display: inline-block;
    float: left;
    margin: 0;
    padding: 0;
    width: auto;

How to remove close button on the jQuery UI dialog?

None of the above works. The solution that really works is:

  //this is your dialog:
    // Step 1. Add an extra class to our dialog to address the dialog directly. Make sure that this class is not used anywhere else:
    dialogClass: 'my-extra-class' 
  // Step 2. Hide the close 'X' button on the dialog that you marked with your extra class
  // Step 3. Enjoy your dialog without the 'X' link

Please check if it works for you.

Select and trigger click event of a radio button in jquery

Switch the order of the code: You're calling the click event before it is attached.

$(document).ready(function() {
      $("#checkbox_div input:radio").click(function() {



      $("input:radio:first").prop("checked", true).trigger("click");


jquery UI dialog: how to initialize without a title bar?

This worked for me:

    create: function (event, ui) {

jQuery UI Sortable Position

I wasn't quite sure where I would store the start position, so I want to elaborate on David Boikes comment. I found that I could store that variable in the ui.item object itself and retrieve it in the stop function as so:

$( "#sortable" ).sortable({
    start: function(event, ui) {
        ui.item.startPos = ui.item.index();
    stop: function(event, ui) {
        console.log("Start position: " + ui.item.startPos);
        console.log("New position: " + ui.item.index());

How to show all rows by default in JQuery DataTable


    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    iDisplayLength: -1

Or if using 1.10+

    paging: false

The option you should use is iDisplayLength:

  'iDisplayLength': 100

   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]

It will Load by default all entries.

    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    iDisplayLength: -1

Or if using 1.10+

    paging: false

If you want to load by default 25 not all do this.

    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]

How do I disable a jquery-ui draggable?

To enable/disable draggable in jQuery I used:

$("#draggable").draggable({ disabled: true });          

$("#draggable").draggable({ disabled: false });

@Calciphus answer didn't work for me with the opacity problem, so I used:

div.ui-state-disabled.ui-draggable-disabled {opacity: 1;}

Worked on mobile devices either.

Here is the code:

How to use radio on change event?

A simpler and cleaner way would be to use a class with @Ohgodwhy's answer

<input ... class="rButton">
<input ... class="rButton">


?$( ".rButton" ).change(function() {
    switch($(this).val()) {
        case 'allot' :
            alert("Allot Thai Gayo Bhai");
        case 'transfer' :
            alert("Transfer Thai Gayo");

jQuery multiselect drop down menu

You can use chosen.i download all file from this link Chosen download Link

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link href="prism.css" rel="stylesheet" type="text/css" />
    <link href="chosen.css" rel="stylesheet" type="text/css" />
    <script src="jquery-2.1.4.min.js" type="text/javascript"></script>
    <script src="chosen.jquery.js" type="text/javascript"></script>
    <script src="prism.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
    <form id="form1" runat="server">

<ion-view view-title="Profile">
<ion-content class="padding">

    <label class="item item-input">
        <div class="input-label">Enter Your Option</div>
            <select class="chzn-select" multiple="true" name="faculty" style="width:1000px;">
                <option value="Option 2.1">Option 2.1</option>
                <option value="Option 2.2">Option 2.2</option>
                <option value="Option 2.3">Option 2.3</option>

All file on all same folder

jQuery UI DatePicker to show month year only

Add one more simple solution

 $(function() {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'M yy'
    }).focus(function() {
        var thisCalendar = $(this);
        $('.ui-datepicker-close').click(function() {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
thisCalendar.datepicker('setDate', new Date(year, month, 1));

  • display only month/year
  • Adds the month year value to input box only on clicking of Done button
  • No "reopen" behavior when click "Done"
    another solution that work well for datepicker and monthpicker in the same page:(also avoid the bug of mutiple click on previous button in IE, that may occur if we use focus function)
    JS fiddle link

Can I make a <button> not submit a form?

Just use good old HTML:

<input type="button" value="Submit" />

Wrap it as the subject of a link, if you so desire:

<a href=""><input type="button" value="Submit" /></a>

Or if you decide you want javascript to provide some other functionality:

<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>

Best Practice to Organize Javascript Library & CSS Folder Structure

          bootstrap/--------------Libraries can have js/css/images------------
     common/--------------------common section will have application level resources             


This is how I organized my application's static resources.

How do I pre-populate a jQuery Datepicker textbox with today's date?

Try this

            changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: "dd-mm-yy",  showOn: "focus", yearRange: "-5:+10"

jQuery UI Dialog individual CSS styling

The standard way to do this is with jQuery UI's CSS Scopes:

<div class="myCssScope">
   <!-- dialog goes here -->

Unfortunately, the jQuery UI dialog moves the dialog DOM elements to the end of the document, to fix potential z-index issues. This means the scoping won't work (it will no longer have a ".myCssScope" ancestor).

Christoph Herold designed a workaround which I've implemented as a jQuery plugin, maybe that will help.

Getting value from JQUERY datepicker

If your selected elements are not one, you need use this way:

$('[type="date"]').change(function() {
    var date = $(this).datepicker("getDate");

Find out whether radio button is checked with JQuery?

$('#element').click(function() {
   if($('#radio_button').is(':checked')) { alert("it's checked"); }

How to change the pop-up position of the jQuery DatePicker control

First I think there should be a afterShowing method in the datepicker object, where you could change the position after jquery has done all its voodoo in the _showDatepicker method. Additionally, a parameter called preferedPosition would be also desirable, so you could set it and jquery modify it in case the dialog is rendered outside the viewport.

There's a "trick" to do this last thing. If you study the _showDatepicker method, you will see the use of a private variable $.datepikcer._pos. That variable will be setup if nobody has set it up before. If you modify that variable before showing the dialog, Jquery will take it and will try to allocate the dialog in that position, and if it renders out of the screen, it will adjust it to make sure it is visible. Sounds good, eh?

Problem is; _pos is private, but if you don't mind that. You can:

    beforeShow: function(input, inst)
        $.datepicker._pos = $.datepicker._findPos(input); //this is the default position
        $.datepicker._pos[0] = whatever; //left
        $.datepicker._pos[1] = whatever; //top

But be careful of Jquery-ui updates, because a change in the internal implementation of the _showDatepicker might break your code.

.datepicker('setdate') issues, in jQuery

function calenderEdit(dob) {
    var date= $('#'+dob).val();
        changeMonth: true,
        changeYear: true, yearRange: '1950:+10'
    }).datepicker("setDate", date);

jQuery UI - Close Dialog When Clicked Outside

I use this solution based in one posted here:

var g_divOpenDialog = null;
function _openDlg(l_d) {

      && !jQuery('.ui-dialog, a')
      && !jQuery('.ui-dialog').length

  setTimeout(function() {
    g_divOpenDialog = l_d;
  }, 500);
function _closeDlg() {
  g_divOpenDialog = null;

Form Submit jQuery does not work

if there is one error in the the submit function,the submit function will be execute. in other sentences prevent default(or return false) does not work when one error exist in submit function.

Convert string to number and add one

a nice way from :

adding a + before the string without using parseInt and parseFloat and radix and errors i faced for missing radix parameter


var number= +$('#inputForm').val();

Jquery Date picker Default Date

Use the defaultDate option

$( ".selector" ).datepicker({ defaultDate: '01/01/01' });

If you change your date format, make sure to change the input into defaultDate (e.g. '01-01-2001')

How can I position my jQuery dialog to center?

For Win7/IE9 environment just set in your css file:

.ui-dialog {
   top: 100px;
   left: 350px !important;

How to change a field name in JSON using Jackson

There is one more option to rename field:

Jackson MixIns.

Useful if you deal with third party classes, which you are not able to annotate, or you just do not want to pollute the class with Jackson specific annotations.

The Jackson documentation for Mixins is outdated, so this example can provide more clarity. In essence: you create mixin class which does the serialization in the way you want. Then register it to the ObjectMapper:

objectMapper.addMixIn(ThirdParty.class, MyMixIn.class);

Change table header color using bootstrap

In your CSS

th {
    background-color: blue;
    color: white;

How to change the text of a button in jQuery?

You can use




would work as well, but it's misleading (it gives the impression you could write something like

$("#btnAddProfile").html('Save <b>now</b>');

but of course you can't

How to Set Active Tab in jQuery Ui

Inside your function for the click action use

$( "#tabs" ).tabs({ active: # });

Where # is replaced by the tab index you want to select.

jQuery UI dialog positioning

You ca set top position in style for display on center, saw that the code:

.ui-dialog{top: 100px !important;}

This style should show dialog box 100px bellow from top.

jquery-ui-dialog - How to hook into dialog close event

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

Because no one actually created an answer with using .on() instead of bind() i decided to create one.

$('div#dialog').on('dialogclose', function(event) {
     //custom logic fired after dialog is closed.  

How to get the selected date value while using Bootstrap Datepicker?

If you already have a number of dates already highlighted and want to determine which date was last clicked then you'll need the following:


viewDate returns a JavaScript date object so you'll need to handle it accordingly.

jQuery datepicker to prevent past date

$("#datePicker").datePicker({startDate: new Date() });. This works for me

jQuery UI: Datepicker set year range dropdown to 100 years

You can set the year range using this option per documentation here

yearRange: '1950:2013', // specifying a hard coded year range

or this way

yearRange: "-100:+0", // last hundred years

From the Docs

Default: "c-10:c+10"

The range of years displayed in the year drop-down: either relative to today's year ("-nn:+nn"), relative to the currently selected year ("c-nn:c+nn"), absolute ("nnnn:nnnn"), or combinations of these formats ("nnnn:-nn"). Note that this option only affects what appears in the drop-down, to restrict which dates may be selected use the minDate and/or maxDate options.

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

It may have side effects if there are other listeners, and it doesn't feel as nice as interacting through the plugins API -- but it gives a less verbose code if you just "click" the tab, rather than count it's index and set it active afterwards, and it's pretty intuitive what's going on. Also it wont fail if the ui-guys decide to rename the option again.

$('#tabs a[href="#tabtwo"]').click();

It's intriguing, though, that the ui tabs code has a meta-function (_getIndex) with the comment:

"meta-function to give users option to provide a href string instead of a numerical index"

but does not use it when setting the active option, only when calling enable, disable and load.

jQuery UI 1.10: dialog and zIndex option

Add zIndex property to dialog object:

 zIndex: 10000

jQuery UI accordion that keeps multiple sections open?

Just call each section of the accordion as its own accordion. active: n will be 0 for the first one( so it will display) and 1, 2, 3, 4, etc for the rest. Since each one is it's own accordion, they will all have only 1 section, and the rest will be collapsed to start.

$('.accordian').each(function(n, el) {
    heightStyle: 'content',
    collapsible: true,
    active: n

Disable future dates after today in Jquery Ui Datepicker

This worked for me endDate: "today"

        format: "dd/mm/yyyy",
        autoclose: true,
        orientation: "top",
        endDate: "today"



jQuery check if an input is type checkbox?

Use this function:

function is_checkbox(selector) {
    var $result = $(selector);
    return $result[0] && $result[0].type === 'checkbox';

Or this jquery plugin:

$.fn.is_checkbox = function () { return':checkbox'); };

jQuery Date Picker - disable past dates

jQuery API documentation - datepicker

The minimum selectable date. When set to null, there is no minimum.

Multiple types supported:

Date: A date object containing the minimum date.
Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.
String: A string in the format defined by the dateFormat option, or a relative date.
Relative dates must contain value and period pairs; valid periods are y for years, m for months, w for weeks, and d for days. For example, +1m +7d represents one month and seven days from today.

In order not to display previous dates other than today

$('#datepicker').datepicker({minDate: 0});

Downloading jQuery UI CSS from Google's CDN

I would think so. Why not? Wouldn't be much of a CDN w/o offering the CSS to support the script files

This link suggests that they are:

We find it particularly exciting that the jQuery UI CSS themes are now hosted on Google's Ajax Libraries CDN.

jQuery UI DatePicker to show year only

  $(function() {
    $('#datepicker1').datepicker( {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));

Style should be

.ui-datepicker-calendar {
    display: none;

working demo

Jquery UI tooltip does not support html content

another solution will be to grab the text inside the title tag & then use .html() method of jQuery to construct the content of the tooltip.

$(function() {
    position: {
      using: function(position, feedback) {
        var txt = $(this).text();


How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

After wasting many hours, I came across this!


It translates tap events as click events. Remember to load the script after jquery.

I got this working on the iPad and iPhone

$('#movable').draggable({containment: "parent"});

Twitter Bootstrap vs jQuery UI?

You can use both with relatively few issues. Twitter Bootstrap uses jQuery 1.7.1 (as of this writing), and I can't think of any reasons why you cannot integrate additional Jquery UI components into your HTML templates.

I've been using a combination of HTML5 Boilerplate & Twitter Bootstrap built at This combines two awesome starter templates into one great starter project. Check out the details at and Or to get started right away, go to, click the "Bootstrap 2" button, and click "Download It". This will give you all the js and css you need to get started.

And don't be scared off by HTML5 and CSS3. Initializr and HTML5 Boilerplate include polyfills and IE specific code that will allow all features to work in IE 6, 7 8, and 9.

The use of LESS in Twitter Bootstrap is also optional. They use LESS to compile all the CSS that is used by Bootstrap, but if you just want to override or add your own styles, they provide an empty css file for that purpose.

There is also a blank js file (script.js) for you to add custom code. This is where you would add your handlers or selectors for additional jQueryUI components.

datetimepicker is not a function jquery

I had the same problem with bootstrap datetimepicker extension. Including moment.js before datetimepicker.js was the solution.

Remove Datepicker Function dynamically

Just bind the datepicker to a class rather than binding it to the id . Remove the class when you want to revoke the datepicker...

$("#ddlSearchType").change(function () { 
  if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date")                   { 
  } else { 

How to completely remove a dialog on close

You can do use


JQuery show and hide div on mouse click (animate)

Of course slideDown and slideUp don't do what you want, you said you want it to be left/right, not top/down.

If your edit to your question adding the jquery-ui tag means you're using jQuery UI, I'd go with nnnnnn's solution, using jQuery UI's slide effect.

If not:

Assuming the menu starts out visible (edit: oops, I see that isn't a valid assumption; see note below), if you want it to slide out to the left and then later slide back in from the left, you could do this: Live Example | Live Source

$(document).ready(function() {
    // Hide menu once we know its width
    $('#showmenu').click(function() {
        var $menu = $('.menu');
        if ($':visible')) {
            // Slide away
            $menu.animate({left: -($menu.outerWidth() + 10)}, function() {
        else {
            // Slide in
            ${left: 0});

You'll need to put position: relative on the menu element.

Note that I replaced your toggle with click, because that form of toggle was removed from jQuery.

If you want the menu to start out hidden, you can adjust the above. You want to know the element's width, basically, when putting it off-page.

This version doesn't care whether the menu is initially-visible or not: Live Copy | Live Source

<!DOCTYPE html>
<script src=""></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<div id="showmenu">Click Here</div>
<div class="menu" style="display: none; position: relative;"><ul><li>Button1</li><li>Button2</li><li>Button3</li></ul></div>
    $(document).ready(function() {
        var first = true;

        // Hide menu once we know its width
        $('#showmenu').click(function() {
            var $menu = $('.menu');
            if ($':visible')) {
                // Slide away
                $menu.animate({left: -($menu.outerWidth() + 10)}, function() {
            else {
                // Slide in
                $"left", -($menu.outerWidth() + 10)).animate({left: 0});

Jquery DatePicker Set default date

Today date:

$( ".selector" ).datepicker( "setDate", new Date());
// Or on the init
$( ".selector" ).datepicker({ defaultDate: new Date() });

15 days from today:

$( ".selector" ).datepicker( "setDate", 15);
// Or on the init
$( ".selector" ).datepicker({ defaultDate: 15 });

jQuery ui docs

Close dialog on click (anywhere)

Try this:

$(".ui-widget-overlay").click(function () {

jQuery ui dialog change title after load-callback

I tried to implement the result of Nick which is:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:

    $("#modal_popup").dialog('option', 'title', 'My New Title');
    $("#modal_popup").dialog({ width: 950, height: 550);

I fixed this by adding the title to the javascript function arguments of each dialog on the page:

function show_popup1() {
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});

function show_popup2() {
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});

How to disable manual input for JQuery UI Datepicker field?

I think you should add style="background:white;" to make looks like it is writable

<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly"   style="background:white;"/>

JQuery confirm dialog

Try this one

  .html('<div><h6>Yes or No?</h6></div>')
      modal: true, title: 'message', zIndex: 10000, autoOpen: true,
      width: 'auto', resizable: false,
      buttons: {
          Yes: function () {
          No: function () {
      close: function (event, ui) {


Change CSS properties on click

Try this:

$('#foo').css({backgroundColor:'red', color:'white',fontSize:'44px'});

jQuery UI Sortable, then write order into a database

Try with this solution: where new order is saved in some HMTL element. Then you submit the form with this data to some PHP script, and iterate trough it with for loop.

Note: I had to add another db field of type INT(11) which is updated(timestamp'ed) on each iteration - it serves for script to know which row is recenty updated, or else you end up with scrambled results.

Slide right to left?

Take a look at this working example on Fiddle, which uses jQuery UI. It is a solution I've used originally from left to right, but I've changed it to work from right to left.

It allows user to click on links quickly without breaking the animation among the available panels.

The JavaScript code is simple:

    // Mostra e nascondi view-news
    var active = "europa-view";
    $('a.view-list-item').click(function () {
        var divname=;
        $("#"+active ).hide("slide", { direction: "right" }, 1200);
        $("#"+divname).delay(400).show("slide", { direction: "right" }, 1200);
        active = divname;

Get HTML and CSS at the Fiddle link.

Added white background and left-padding just for better effect presentation.

jQuery UI Accordion Expand/Collapse All

I second bigvax comment earlier but you need to make sure that you add

        jQuery("#jQueryUIAccordion").({ active: false,
                              collapsible: true });

otherwise you wont be able to open the first accordion after collapsing them.

    $('.close').click(function () {
    $('.ui-accordion-header').removeClass('ui-accordion-header-active ui-state-active ui-corner-top').addClass('ui-corner-all').attr({'aria-selected':'false','tabindex':'-1'});
    $('.ui-accordion-header .ui-icon').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');

How can I know when an EditText loses focus?

Using Java 8 lambda expression:

editText.setOnFocusChangeListener((v, hasFocus) -> {
    if(!hasFocus) {
        String value = String.valueOf( editText.getText() );

How do I concatenate strings in Swift?

To print the combined string using


or String3 stores the output of combination of 2 strings

let strin3 = "\(string1)\(string2)"

CSS: On hover show and hide different div's at the same time?

if the other div is sibling/child, or any combination of, of the parent yes

    .showme{ _x000D_
        display: none;_x000D_
    .showhim:hover .showme{_x000D_
        display : block;_x000D_
    .showhim:hover .hideme{_x000D_
        display : none;_x000D_
    .showhim:hover ~ .hideme2{ _x000D_
    <div class="showhim">_x000D_
        HOVER ME_x000D_
        <div class="showme">hai</div> _x000D_
        <div class="hideme">bye</div>_x000D_
    <div class="hideme2">bye bye</div>

How to use GROUP BY to concatenate strings in SQL Server?

I ran into a couple of problems when I tried converting Kevin Fairchild's suggestion to work with strings containing spaces and special XML characters (&, <, >) which were encoded.

The final version of my code (which doesn't answer the original question but may be useful to someone) looks like this:

CREATE TABLE #YourTable ([ID] INT, [Name] VARCHAR(MAX), [Value] INT)

INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'Oranges & Lemons',4)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'1 < 2',8)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)

    SELECT ', ' + CAST([Name] AS VARCHAR(MAX))
    FROM #YourTable WHERE (ID = Results.ID) 
     /* Use .value to uncomment XML entities e.g. &gt; &lt; etc*/
  ,1,2,'') as NameValues
FROM    #YourTable Results


Rather than using a space as a delimiter and replacing all the spaces with commas, it just pre-pends a comma and space to each value then uses STUFF to remove the first two characters.

The XML encoding is taken care of automatically by using the TYPE directive.

SQL Call Stored Procedure for each Row without using a cursor

I usually do it this way when it's a quite a few rows:

  1. Select all sproc parameters in a dataset with SQL Management Studio
  2. Right-click -> Copy
  3. Paste in to excel
  4. Create single-row sql statements with a formula like '="EXEC schema.mysproc @param=" & A2' in a new excel column. (Where A2 is your excel column containing the parameter)
  5. Copy the list of excel statements into a new query in SQL Management Studio and execute.
  6. Done.

(On larger datasets i'd use one of the solutions mentioned above though).

Check if a string is a valid date using DateTime.TryParse

[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
    string[] formats = { "MM/dd/yyyy" };
    DateTime parsedDateTime;
    return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
                                   DateTimeStyles.None, out parsedDateTime);

Simply specify the date time formats that you wish to accept in the array named formats.

Setting top and left CSS attributes

You can also use the setProperty method like below

document.getElementById('divName').style.setProperty("top", "100px");

How do I run a PowerShell script when the computer starts?

What I do is create a shortcut that I place in shell:startup.

The shortcut has the following:

Target: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "C:\scripts\script.ps1"

(replacing scripts\scripts.ps1 with what you need)

Start In: C:\scripts

(replacing scripts with folder which has your script)

Who sets response content-type in Spring MVC (@ResponseBody)

According to the link " If a character encoding is not specified, the Servlet specification requires that an encoding of ISO-8859-1 is used ".If you are using spring 3.1 or later use the fallowing configuration to set charset=UTF-8 to response body
@RequestMapping(value = "your mapping url", produces = "text/plain;charset=UTF-8")

How can I break from a try/catch block without throwing an exception in Java

This is the code I usually do:

    throw null;//this line just works like a 'break'
  catch (NullReferenceException)
  catch (System.Exception ex)

Escaping HTML strings with jQuery

There is also the solution from mustache.js

var entityMap = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];

Replacing &nbsp; from javascript dom text node

var text = "&quot;&nbsp;&amp;&lt;&gt;";
text = text.replaceHtmlEntites();

String.prototype.replaceHtmlEntites = function() {
var s = this;
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {"nbsp": " ","amp" : "&","quot": "\"","lt"  : "<","gt"  : ">"};
return ( s.replace(translate_re, function(match, entity) {
  return translate[entity];
}) );

try this.....this worked for me

How to stop VBA code running?

what jamietre said, but

Private Sub SomeVBASub
    If not Cancel Then DoAnotherStuff
    If not Cancel Then AndFinallyDothis
End Sub

"elseif" syntax in JavaScript

Just add a space:

if (...) {

} else if (...) {

} else {


How to display my application's errors in JSF?

You also have to include the FormID in your call to addMessage().

 FacesContext.getCurrentInstance().addMessage("myform:newPassword1", new FacesMessage("Error: Your password is NOT strong enough."));

This should do the trick.


How to implement class constructor in Visual Basic?

If you mean VB 6, that would be Private Sub Class_Initialize().

If you mean VB.NET it is Public Sub New() or Shared Sub New().

T-SQL split string

All the functions for string splitting that use some kind of Loop-ing (iterations) have bad performance. They should be replaced with set-based solution.

This code executes excellent.

CREATE FUNCTION dbo.SplitStrings
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
        SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)

search in java ArrayList

Others have pointed out the error in your existing code, but I'd like to take two steps further. Firstly, assuming you're using Java 1.5+, you can achieve greater readability using the enhanced for loop:

Customer findCustomerByid(int id){    
    for (Customer customer : customers) {
        if (customer.getId() == id) {
            return customer;
    return null; 

This has also removed the micro-optimisation of returning null before looping - I doubt that you'll get any benefit from it, and it's more code. Likewise I've removed the exists flag: returning as soon as you know the answer makes the code simpler.

Note that in your original code I think you had a bug. Having found that the customer at index i had the right ID, you then returned the customer at index id - I doubt that this is really what you intended.

Secondly, if you're going to do a lot of lookups by ID, have you considered putting your customers into a Map<Integer, Customer>?

How to create a DB for MongoDB container on start up?

Given this .env file:


And this file:

mongo --eval "db.auth('$MONGO_INITDB_ROOT_USERNAME', '$MONGO_INITDB_ROOT_PASSWORD'); db = db.getSiblingDB('$DB_NAME'); db.createUser({ user: '$DB_USER', pwd: '$DB_PASSWORD', roles: [{ role: 'readWrite', db: '$DB_NAME' }] });"

This docker-compose.yml will create the admin database and admin user, authenticate as the admin user, then create the real database and add the real user:

version: '3'

#  app:
#    build: .
#    env_file: .env
#    environment:
#      DB_HOST: 'mongodb://mongodb'

    image: mongo:4
      MONGO_INITDB_ROOT_PASSWORD: admin-password
      - 27017:27017
      - db-data:/data/db
      - ./


Rotating x axis labels in R for barplot

In the documentation of Bar Plots we can read about the additional parameters (...) which can be passed to the function call:

...    arguments to be passed to/from other methods. For the default method these can 
       include further arguments (such as axes, asp and main) and graphical 
       parameters (see par) which are passed to plot.window(), title() and axis.

In the documentation of graphical parameters (documentation of par) we can see:

    numeric in {0,1,2,3}; the style of axis labels.

      always parallel to the axis [default],

      always horizontal,

      always perpendicular to the axis,

      always vertical.

    Also supported by mtext. Note that string/character rotation via argument srt to par does not affect the axis labels.

That is why passing las=2 is the right answer.

how to add picasso library in android studio

easiest way to add dependence

hope this help you or Ctrl + Alt + Shift + S => select Dependencies tab and find what you need ( see my image)

How can I execute a PHP function in a form action?

It's better something like the data to the self page and maybe do a check on user input.

    require_once ( 'username.php' );

    if(isset($_POST)) {
      echo "form post"; // ex $_POST['textfield']

    echo '
    <form name="form1" method="post" action="' . $_SERVER['PHP_SELF'] . '">
          <input type="text" name="textfield" id="textfield">
          <input type="submit" name="button" id="button" value="Submit">

How to tell Jackson to ignore a field during serialization if its value is null?

To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:



class Foo
  String bar;

Alternatively, you could use @JsonInclude in a getter so that the attribute would be shown if the value is not null.

A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.

Javascript Uncaught TypeError: Cannot read property '0' of undefined

There is no error when I use your code,

but I am calling the hasLetter method like this:


java.lang.OutOfMemoryError: GC overhead limit exceeded

For my case increasing the memory using -Xmx option was the solution.

I had a 10g file read in java and each time I got the same error. This happened when the value in the RES column in top command reached to the value set in -Xmx option. Then by increasing the memory using -Xmx option everything went fine.

There was another point as well. When I set JAVA_OPTS or CATALINA_OPTS in my user account and increased the amount of memory again I got the same error. Then, I printed the value of those environment variables in my code which gave me different values than what I set. The reason was that Tomcat was the root for that process and then as I was not a su-doer I asked the admin to increase the memory in in Tomcat.

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

This happens because of your application does not allow to append iframe from origin other than your application domain.

If your application have web.config then add the following tag in web.config

            <add name="X-Frame-Options" value="ALLOW" />

This will allow application to append iframe from other origin also. You can also use the following value for X-Frame-Option


how to count length of the JSON array element

First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :

obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;

Run a Command Prompt command from Desktop Shortcut

You can also create a shortcut on desktop that can run a specific command or even a batch file by just typing the command in "Type the Location of Item" bar in create shortcut wizard

  1. Right click on Desktop.
  2. Enter the command in "Type the Location of Item" bar.
  3. Double click the shortcut to run the command.

Found detailed Instructions here

How do I unlock a SQLite database?

Should be a database's internal problem...
For me it has been manifested after trying to browse database with "SQLite manager"...
So, if you can't find another process connect to database and you just can't fix it, just try this radical solution:

  1. Provide to export your tables (You can use "SQLite manager" on Firefox)
  2. If the migration alter your database scheme delete the last failed migration
  3. Rename your "database.sqlite" file
  4. Execute "rake db:migrate" to make a new working database
  5. Provide to give the right permissions to database for table's importing
  6. Import your backed up tables
  7. Write the new migration
  8. Execute it with "rake db:migrate"

What are XAND and XOR

OMG, a XAND gate does exist. My dad is taking a technological class for a job and there IS an XAND gate. People are saying that both OR and AND are complete opposites, so they expand that to the exclusive-gate logic:

XOR: One or another, but not both.

Xand: One and another, but not both.

This is incorrect. If you're going to change from XOR to XAND, you have to flip every instance of 'AND' and 'OR':

XOR: One or another, but not both.

XAND: One and another, but not one.

So, XAND is true when and only when both inputs are equal, either if the inputs are 0/0 or 1/1

Sql connection-string for localhost server

use this connection string :

Server=HARIHARAN-PC\SQLEXPRESS;Intial Catalog=persons;Integrated Security=True;

rename person with your database name

How to call an action after click() in Jquery?

you can write events on elements like chain,

   //action on click
   //action on mouseup (just before click event)

i've used it for removing cart items. same object, doing some action, after another action

Align DIV's to bottom or baseline

An old post but thought i would share an answer for anyone looking. And because when you use absolute things can go wrong. What I would do is


<div id="parentDiv"></div>
<div class="childDiv"></div>

The Css



And that would just sit that bottom div back up into the parent div. safe for most browsers too

Angular 5 Service to read local .json file

You have an alternative solution, importing directly your json.

To compile, declare this module in your typings.d.ts file

declare module "*.json" {
    const value: any;
    export default value;

In your code

import { data_json } from '../../path_of_your.json';


How to check which version of Keras is installed?

Python library authors put the version number in <module>.__version__. You can print it by running this on the command line:

python -c 'import keras; print(keras.__version__)'

If it's Windows terminal, enclose snippet with double-quotes like below

python -c "import keras; print(keras.__version__)"

How to use parameters with HttpPost

You can also use this approach in case you want to pass some http parameters and send a json request:

(note: I have added in some extra code just incase it helps any other future readers)

public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {

    //add the http parameters you wish to pass
    List<NameValuePair> postParameters = new ArrayList<>();
    postParameters.add(new BasicNameValuePair("param1", "param1_value"));
    postParameters.add(new BasicNameValuePair("param2", "param2_value"));

    //Build the server URI together with the parameters you wish to pass
    URIBuilder uriBuilder = new URIBuilder("");

    HttpPost postRequest = new HttpPost(;
    postRequest.setHeader("Content-Type", "application/json");

    //this is your JSON string you are sending as a request
    String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";

    //pass the json string request in the entity
    HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));

    //create a socketfactory in order to use an http connection manager
    PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainSocketFactory)

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);


    RequestConfig defaultRequestConfig = RequestConfig.custom()

    // Build the http client.
    CloseableHttpClient httpclient = HttpClients.custom()

    CloseableHttpResponse response = httpclient.execute(postRequest);

    //Read the response
    String responseString = "";

    int statusCode = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();

    HttpEntity responseHttpEntity = response.getEntity();

    InputStream content = responseHttpEntity.getContent();

    BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
    String line;

    while ((line = buffer.readLine()) != null) {
        responseString += line;

    //release all resources held by the responseHttpEntity

    //close the stream

    // Close the connection manager.

Convert string to BigDecimal in java

String currency = "135.69";
System.out.println(new BigDecimal(currency));

//will print 135.69

Check if argparse optional argument is set or not

I think using the option default=argparse.SUPPRESS makes most sense. Then, instead of checking if the argument is not None, one checks if the argument is in the resulting namespace.


import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--foo", default=argparse.SUPPRESS)
ns = parser.parse_args()

print("Parsed arguments: {}".format(ns))
print("foo in namespace?: {}".format("foo" in ns))


$ python --foo 1
Parsed arguments: Namespace(foo='1')
foo in namespace?: True
Argument is not supplied:
$ python
Parsed arguments: Namespace()
foo in namespace?: False

DateTime.TryParse issue with dates of yyyy-dd-MM format

You need to use the ParseExact method. This takes a string as its second argument that specifies the format the datetime is in, for example:

// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
   result = DateTime.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
catch (FormatException)
   Console.WriteLine("{0} is not in the correct format.", dateString);

If the user can specify a format in the UI, then you need to translate that to a string you can pass into this method. You can do that by either allowing the user to enter the format string directly - though this means that the conversion is more likely to fail as they will enter an invalid format string - or having a combo box that presents them with the possible choices and you set up the format strings for these choices.

If it's likely that the input will be incorrect (user input for example) it would be better to use TryParseExact rather than use exceptions to handle the error case:

// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
DateTime result;
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out result))
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
   Console.WriteLine("{0} is not in the correct format.", dateString);

A better alternative might be to not present the user with a choice of date formats, but use the overload that takes an array of formats:

// A list of possible American date formats - swap M and d for European formats
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
                   "MM/d/yyyy HH:mm:ss.ffffff" };
string dateString; // The string the date gets read into

    dateValue = DateTime.ParseExact(dateString, formats, 
                                    new CultureInfo("en-US"), 
    Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
catch (FormatException)
    Console.WriteLine("Unable to convert '{0}' to a date.", dateString);

If you read the possible formats out of a configuration file or database then you can add to these as you encounter all the different ways people want to enter dates.

Unable to set variables in bash script

Assignment in bash scripts cannot have spaces around the = and you probably want your date commands enclosed in backticks $():

day=$(date "+%d")
month=$(date "+%B")
year=$(date "+%Y")
ECHO "Network is $network" $network
ECHO "day is $day"
ECHO "Month is $month"
ECHO "YEAR is $year"
ECHO "source is $folderToBeMoved"
ECHO "dest is $newfoldername"
mkdir $newfoldername
cp -R $folderToBeMoved $newfoldername
if [-f $newfoldername/Primetime.eyetv]; then rm $folderToBeMoved; fi

With the last three lines commented out, for me this outputs:

Network is 
day is 16
Month is March
YEAR is 2010
source is /users/test/Documents/Archive/Primetime.eyetv
dest is /Volumes/Media/Network/ABC/March162010

MySQL - How to select data by string length

You are looking for CHAR_LENGTH() to get the number of characters in a string.

For multi-byte charsets LENGTH() will give you the number of bytes the string occupies, while CHAR_LENGTH() will return the number of characters.

Is there a max size for POST parameter content?

Yes there is 2MB max and it can be increased by configuration change like this. If your POST body is not in form of multipart file then you might need to add the max-http-post configuration for tomcat in the application yml configuration file.

Increase max size of each multipart file to 10MB and total payload size of 100MB max

      multipart:max-file-size: 10MB
      multipart:max-request-size: 100MB

Setting max size of post requests which might just be the formdata in string format to ~10 MB

        max-http-post-size: 100000000 # max-http-form-post-size: 10MB for new version

You might need to add this for the latest sprintboot version ->

server: tomcat: max-http-form-post-size: 10MB

What is a "method" in Python?

It's a function which is a member of a class:

class C:
    def my_method(self):
        print("I am a C")

c = C()
c.my_method()  # Prints("I am a C")

Simple as that!

(There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing from your question that you're not asking about that, but rather just the basics.)

Stored Procedure error ORA-06550

create or replace procedure point_triangle

dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);


How to check if a directory containing a file exist?

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

Just my two cents for future visitors who have this problem.

This is the correct syntax for PHP 5.3, for example if you call static method from the class name:


If you previously assign the ClassName to the $cnf variable, you can call the static method from it (we are talking about PHP 5.3):

$cnf = MyClassName;

However, this sintax doesn't work on PHP 5.2 or lower, and you need to use the following:

$cnf = MyClassName;
call_user_func(array($cnf, "getConfig", $key, ...otherposibleadditionalparameters... ));

Hope this helps people having this error in 5.2 version (don't know if this was openfrog's version).

$_POST Array from html form





by adding [] to the end of your form field names, PHP will automatically convert these variables into arrays.

Should each and every table have a primary key?

Just add it, you will be sorry later when you didn't (selecting, deleting. linking, etc)

What do 'real', 'user' and 'sys' mean in the output of time(1)?

I want to mention some other scenario when the real-time is much much bigger than user + sys. I've created a simple server which respondes after a long time

real 4.784
user 0.01s
sys  0.01s

the issue is that in this scenario the process waits for the response which is not on the user site nor in the system.

Something similar happens when you run the find command. In that case, the time is spent mostly on requesting and getting a response from SSD.

What is the proper way to format a multi-line dict in Python?

Generally, you would not include the comma after the final entry, but Python will correct that for you.

How to maintain aspect ratio using HTML IMG tag

None of the methods listed scale the image to the largest possible size that fits in a box while retaining the desired aspect ratio.

This cannot be done with the IMG tag (at least not without a bit of JavaScript), but it can be done as follows:

 <div style="background:center no-repeat url(...);background-size:contain;width:...;height:..."></div>

Find index of last occurrence of a sub-string using T-SQL

DECLARE @FilePath VARCHAR(50) = 'My\Super\Long\String\With\Long\Words'
DECLARE @FindChar VARCHAR(1) = '\'

SELECT LEN(@FilePath) - CHARINDEX(@FindChar,REVERSE(@FilePath)) AS LastOccuredAt

TCPDF Save file to folder?

You may try;


So for you, it will be like;

$this->Output(/kuitit/);  //or try ("/kuitit/")

Is a Python dictionary an example of a hash table?

Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.

That's why you can't use something 'not hashable' as a dict key, like a list:

>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable

You can read more about hash tables or check how it has been implemented in python and why it is implemented that way.

AngularJS toggle class using ng-class

As alternate solution, based on javascript logic operator '&&' which returns the last evaluation, you can also do this like so:

<i ng-class="autoScroll && 'icon-autoscroll' || !autoScroll && 'icon-autoscroll-disabled'"></i>

It's only slightly shorter syntax, but for me easier to read.

"No backupset selected to be restored" SQL Server 2012

I thought I was not stupid enough to mix up the versions - however, I didn't realize that on my new server, a SQL Server 2005 instance was already installed from birth named SQLEXPRESS. When trying to restore my SQL Server 2008 R2 backed up database in SSMS 2012 to the SQLEXPRESS instance, the list of backup sets was empty.

Eventually I realized that the SQLEXPRESS instance on the server was not a 2012 instance, but a 2005. I disconnected and connected to the actual 2012 instance (in my case named SQLEXPRESS2012), and it (obviously) worked.

Email address validation in C# MVC 4 application: with or without using Regex

Why not just use the EmailAttribute?

[Email(ErrorMessage = "Bad email")]
public string Email { get; set; }

Swift - Remove " character from string

If you want to remove more characters for example "a", "A", "b", "B", "c", "C" from string you can do it this way:

someString = someString.replacingOccurrences(of: "[abc]", with: "", options: [.regularExpression, .caseInsensitive])

How to hide console window in python?

This will hide your console. Implement these lines in your code first to start hiding your console at first.

import win32gui, win32con

the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)

Update May 2020 :

If you've got trouble on pip install win32con on Command Prompt, you can simply pip install pywin32.Then on your python script, execute import win32.lib.win32con as win32con instead of import win32con.

To show back your program again win32con.SW_SHOW works fine:

win32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)

Get file content from URL?

$url = "https://chart.googleapis....";
$json = file_get_contents($url);

Now you can either echo the $json variable, if you just want to display the output, or you can decode it, and do something with it, like so:

$data = json_decode($json);

Real escape string and PDO

PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.

Here is an excerpt from the PHP website:

    $conn = new PDO('sqlite:/home/lynn/music.sql3');

    /* Simple string */
    $string = 'Nice';
    print "Unquoted string: $string\n";
    print "Quoted string: " . $conn->quote($string) . "\n";

The above code will output:

Unquoted string: Nice
Quoted string: 'Nice'

Converting bytes to megabytes

BTW: Hard drive manufacturers don't count as authorities on this one!

Oh, yes they do (and the definition they assume from the S.I. is the correct one). On a related issue, see this post on CodingHorror.

How can I simulate mobile devices and debug in Firefox Browser?

Most web applications detects mobile devices based on the HTTP Headers.

If your web site also uses HTTP Headers to identify mobile device, you can do the following:

  1. Add Modify Headers plug in to your Firefox browser ( )
  2. Using plugin modify headers:
    • select Headers tab-> select Action 'ADD'
    • to simulate e.g. iPhone add a header with name User-Agent and value: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3
    • click 'Add' button
  3. After that you should be able to see mobile version of you web application in Firefox and use Firebug plugin.

Hope it helps!

How to set button click effect in Android?

Create your AlphaAnimation Object that decides how much will be the fading effect of the button, then let it start in the onClickListener of your buttons

For example :

private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);

// some code

public void onClick(View v) {

of course this is just a way, not the most preferred one, it's just easier

Confused about __str__ on list in Python

It provides human readable version of output rather "Object": Example:

class Pet(object):

    def __init__(self, name, species): = name
        self.species = species

    def getName(self):

    def getSpecies(self):
        return self.species

    def Norm(self):
        return "%s is a %s" % (, self.species)

if __name__=='__main__':
    a = Pet("jax", "human")
    print a 


<__main__.Pet object at 0x029E2F90>

while code with "str" return something different

class Pet(object):

    def __init__(self, name, species): = name
        self.species = species

    def getName(self):

    def getSpecies(self):
        return self.species

    def __str__(self):
        return "%s is a %s" % (, self.species)

if __name__=='__main__':
    a = Pet("jax", "human")
    print a 


jax is a human

Changing the default title of confirm() in JavaScript?

I know this is not possible for alert(), so I guess it is not possible for confirm either. Reason is security: it is not allowed for you to change it so you wouldn't present yourself as some system process or something.

Convert PDF to clean SVG?

Here is the NodeJS REST api for two PDF render scripts.

Scripts are: pdf2svg and Imagemagicks convert

Auto Generate Database Diagram MySQL

I've recently started using . It uses GraphViz, and it strikes me as having a good balance between usability and simplicity.

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

Eclipse: Enable autocomplete / content assist

  1. window->preferences->java->Editor->Contest Assist
  2. Enter in Auto activation triggers for java:
  3. Apply and Close

other method:
type initial letter then ctrl+spacebar for auto-complete options.

How can I disable a button in a jQuery dialog from a function?

This did the job for me:

$find("<%= btnPrint.ClientID %>").set_enabled(true);

Removing a model in rails (reverse of "rails g model Title...")

  1. To remove migration (if you already migrated the migration)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
  2. To remove Model

    rails d model name  #name => Your model name

E11000 duplicate key error index in mongodb mongoose

for future developers, i recommend, delete the index in INDEX TAB using compass... this NOT DELETE ANY document in your collection Manage Indexes

Can "git pull --all" update all my local branches?

It can be done using below script... It will first fetch all branches and checkout one by one and update by itself.

git branch -r | grep -v '\->' | while read remote; do git branch --track 
"${remote#origin/}" "$remote"; done

set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
branch_name=$(git branch | awk '{print $1" "}' | grep -v '*' | xargs)
for branch in $branch_name; do
   git checkout "$branch" || exit 1
   git rebase "origin/$branch" || exit 1
   git pull origin $branch|| exit 1
git checkout "$CURRENT" || exit 1
git pull || exit 1

How to convert a Date to a formatted string in

I like:

Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"

Easy to maintain if you need to use it in several parts of your code, date formats always seem to change sooner or later.

Delimiter must not be alphanumeric or backslash and preg_match

You need a delimiter for your pattern. It should be added at the start and end of the pattern like so:

$pattern = "/My name is '(.*)' and im fine/";  // With / as a delimeter 

In a javascript array, how do I get the last 5 elements, excluding the first element?

Try this:

var array = [1, 55, 77, 88, 76, 59];
var array_last_five;
array_last_five = array.slice(-5);
if (array.length < 6) {

Conditionally change img src based on model data

Another way ..

<img ng-src="{{!video.playing ? 'img/icons/play-rounded-button-outline.svg' : 'img/icons/pause-thin-rounded-button.svg'}}" />

How to search a string in multiple files and return the names of files in Powershell?

If you search into one directory, you can do it:

select-string -Path "c:\temp\*.*" -Pattern "result"  -List | select Path

Mapping composite keys using EF code first

For Mapping Composite primary key using Entity framework we can use two approaches.

1) By Overriding the OnModelCreating() Method

For ex: I have the model class named VehicleFeature as shown below.

public class VehicleFeature
    public int VehicleId { get; set; }
    public int FeatureId{get;set;}
    public Vehicle Vehicle{get;set;}
    public Feature Feature{get;set;}

The Code in my DBContext would be like ,

public class VegaDbContext : DbContext
    public DbSet<Make> Makes{get;set;}

    public DbSet<Feature> Features{get;set;}
    public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)        

    // we override the OnModelCreating method here.
    protected override void OnModelCreating(ModelBuilder modelBuilder)
        modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});

2) By Data Annotations.

public class VehicleFeature
    public int VehicleId { get; set; }
    public int FeatureId{get;set;}
    public Vehicle Vehicle{get;set;}
    public Feature Feature{get;set;}

Please refer the below links for the more information.


2) How to add a composite unique key using EF 6 Fluent Api?

Turning off eslint rule for a specific line

To disable all rules on a specific line:

alert('foo'); // eslint-disable-line

How to set array length in c# dynamically

You could use List inside the method and transform it to an array at the end. But i think if we talk about an max-value of 20, your code is faster.

    private Update BuildMetaData(MetaData[] nvPairs)
        Update update = new Update();
        List<InputProperty> ip = new List<InputProperty>();
        for (int i = 0; i < nvPairs.Length; i++)
            if (nvPairs[i] == null) break;
            ip[i] = new InputProperty();
            ip[i].Name = "udf:" + nvPairs[i].Name;
            ip[i].Val = nvPairs[i].Value;
        update.Items = ip.ToArray();
        return update;

Executing Batch File in C#


this simple line will execute the batch file.

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:


But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...

Docker error: invalid reference format: repository name must be lowercase

In my case I was trying to run postgres through docker. Initially I was running as :

docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=test_password POSTGRES_USER=test_user POSTGRES_DB=test_db --rm -v ~/docker/volumes/postgres:/var/lib/postgresql/data --name pg-docker postgres

I was missing -e after each environment variable. Changing the above command to the one below worked

docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=test_password -e POSTGRES_USER=test_user -e POSTGRES_DB=test_db --rm -v ~/docker/volumes/postgres:/var/lib/postgresql/data --name pg-docker postgres

How do I create a new column from the output of pandas groupby().sum()?

How do I create a new column with Groupby().Sum()?

There are two ways - one straightforward and the other slightly more interesting.

Everybody's Favorite: GroupBy.transform() with 'sum'

@Ed Chum's answer can be simplified, a bit. Call DataFrame.groupby rather than Series.groupby. This results in simpler syntax.

# The setup.
df[['Date', 'Data3']]

         Date  Data3
0  2015-05-08      5
1  2015-05-07      8
2  2015-05-06      6
3  2015-05-05      1
4  2015-05-08     50
5  2015-05-07    100
6  2015-05-06     60
7  2015-05-05    120


0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64 

It's a tad faster,

df2 = pd.concat([df] * 12345)

%timeit df2['Data3'].groupby(df['Date']).transform('sum')
%timeit df2.groupby('Date')['Data3'].transform('sum')

10.4 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.58 ms ± 559 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Unconventional, but Worth your Consideration: GroupBy.sum() +

I stumbled upon an interesting idiosyncrasy in the API. From what I tell, you can reproduce this on any major version over 0.20 (I tested this on 0.23 and 0.24). It seems like you consistently can shave off a few milliseconds of the time taken by transform if you instead use a direct function of GroupBy and broadcast it using map:'Date')['Data3'].sum())

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Date, dtype: int64

Compare with


0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64

My tests show that map is a bit faster if you can afford to use the direct GroupBy function (such as mean, min, max, first, etc). It is more or less faster for most general situations upto around ~200 thousand records. After that, the performance really depends on the data.

(Left: v0.23, Right: v0.24)

Nice alternative to know, and better if you have smaller frames with smaller numbers of groups. . . but I would recommend transform as a first choice. Thought this was worth sharing anyway.

Benchmarking code, for reference:

import perfplot
    setup=lambda n: pd.DataFrame({'A': np.random.choice(n//10, n), 'B': np.ones(n)}),
        lambda df: df.groupby('A')['B'].transform('sum'),
        lambda df:'A')['B'].sum()),
    labels=['GroupBy.transform', 'GroupBy.sum + map'],
    n_range=[2**k for k in range(5, 20)],

Split string based on a regular expression

By using (,), you are capturing the group, if you simply remove them you will not have this problem.

>>> str1 = "a    b     c      d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']

However there is no need for regex, str.split without any delimiter specified will split this by whitespace for you. This would be the best way in this case.

>>> str1.split()
['a', 'b', 'c', 'd']

If you really wanted regex you can use this ('\s' represents whitespace and it's clearer):

>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']

or you can find all non-whitespace characters

>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']

Set System.Drawing.Color values

You could do:

Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components

What's the difference between "Layers" and "Tiers"?

I use layers to describe the architect or technology stack within a component of my solutions. I use tiers to logically group those components typically when network or interprocess communication is involved.

How to copy a selection to the OS X clipboard

What worked for me in my .vimrc

set clipboard=unnamed
if has("unnamedplus") " X11 support
    set clipboard+=unnamedplus

Explode string by one or more spaces or tabs

The answers provided by other folks (Ben James) are quite good and I have used them. As user889030 points out, the last array element may be empty. Actually, the first and last array elements can be empty. The code below addresses both issues.

# Split an input string into an array of substrings using any set
# whitespace characters
function explode_whitespace($str) {  
  # Split the input string into an array
  $parts = preg_split('/\s+/', $str);
  # Get the size of the array of substrings
  $sizeParts = sizeof($parts);
  # Check if the last element of the array is a zero-length string
  if ($sizeParts > 0) {
    $lastPart = $parts[$sizeParts-1];
    if ($lastPart == '') {
    # Check if the first element of the array is a zero-length string
    if ($sizeParts > 0) {
      $firstPart = $parts[0];
      if ($firstPart == '') 
  return $parts;   

ERROR in Cannot find module 'node-sass'

There is an issue with downloading npm dependencies due to network which you have. try to download the npm dependencies in open network . you won't get any issue. i am also faced this similar issue and resolved finally.

use below commands: npm install (it will download all depedencies) npm start to start the angular application

GitLab remote: HTTP Basic: Access denied and fatal Authentication

Strangely enough, what worked for me was to sign out and sign back in to the GitLab web UI.

I have no earthly idea why this worked.

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

In your build.gradle file add useLibrary 'org.apache.http.legacy' as per Android 6.0 Changes > Apache HTTP Client Removal notes.

android {
    useLibrary 'org.apache.http.legacy'

To avoid missing link errors add to dependencies

dependencies {
    provided ''

using 'provided' the dependency will be not included in the apk

How to set time to midnight for current day?

Try this:

DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)

Output will be like:

07/29/2015 00:00:00

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

I do not like use pure "a" tag, too much typing. So I come with solution. In view it look

<%: Html.ActionLink(node.Name, "Show", "Browse", 
                    Dic.Route("id", node.Id), Dic.New("data-nodeId", node.Id)) %>

Implementation of Dic class

public static class Dic
    public static Dictionary<string, object> New(params object[] attrs)
        var res = new Dictionary<string, object>();
        for (var i = 0; i < attrs.Length; i = i + 2)
            res.Add(attrs[i].ToString(), attrs[i + 1]);
        return res;

    public static RouteValueDictionary Route(params object[] attrs)
        return new RouteValueDictionary(Dic.New(attrs));

HTML email with Javascript

Do not depend on this. Any good mail client will not support executable code within an email. Any knowledgeable user will not use a client that does.

Anaconda-Navigator - Ubuntu16.04

add anaconda installation path to .bashrc

export PATH="$PATH:/home/username/anaconda3/bin"

load in terminal

$ source ~/.bashrc

run from terminal

$ anaconda-navigator

Stop Visual Studio from launching a new browser window when starting debug?

In Visual Studio 2019, I resolved the same issue as below:

Go to your Visual Studio options Tools >>> Options >>> Project and Solutions >>> Web Projects then finally untick option >>> Stop debugger browser window is closed, close browser when debugging stops

Step 1:

enter image description here

Step 2: untick option >>> Stop debugger browser window is closed, close browser when debugging stops

enter image description here

Step 3:

Then finally click on >>> OK button, these are all the steps to resolve the issue.

How to check if Receiver is registered in Android?

You have to use try/catch:

try {
    if (receiver!=null) {
} catch (IllegalArgumentException e) {

How to force garbage collector to run?

System.GC.Collect() forces garbage collector to run. This is not recommended but can be used if situations arise.

How do you format code on save in VS Code

For eslint:

"editor.codeActionsOnSave": { "source.fixAll.eslint": true }

npm install error from the terminal

Running just "npm install" will look for dependencies listed in your package.json. The error you're getting says that you don't have a package.json file set up (or you're in the wrong directory).

If you're trying to install a specific package, you should use 'npm install {package name}'. See here for more info about the command.

Otherwise, you'll need to create a package.json file for your dependencies or go to the right directory and then run 'npm install'.

How to convert column with dtype as object to string in Pandas Dataframe

Not answering the question directly, but it might help someone else.

I have a column called Volume, having both - (invalid/NaN) and numbers formatted with ,

df['Volume'] = df['Volume'].astype('str')
df['Volume'] = df['Volume'].str.replace(',', '')
df['Volume'] = pd.to_numeric(df['Volume'], errors='coerce')

Casting to string is required for it to apply to str.replace


How to convert std::string to lower case?

As far as I see Boost libraries are really bad performance-wise. I have tested their unordered_map to STL and it was average 3 times slower (best case 2, worst was 10 times). Also this algorithm looks too low.

The difference is so big that I am sure whatever addition you will need to do to tolower to make it equal to boost "for your needs" will be way faster than boost.

I have done these tests on an Amazon EC2, therefore performance varied during the test but you still get the idea.

Elapsed time: 12365milliseconds
Elapsed time: 1640milliseconds
Elapsed time: 26978milliseconds
Elapsed time: 1646milliseconds
Elapsed time: 6957milliseconds
Elapsed time: 1634milliseconds
Elapsed time: 23177milliseconds
Elapsed time: 2421milliseconds
Elapsed time: 17342milliseconds
Elapsed time: 14132milliseconds
Elapsed time: 7355milliseconds
Elapsed time: 1645milliseconds

-O2 made it like this:

Elapsed time: 3769milliseconds
Elapsed time: 565milliseconds
Elapsed time: 3815milliseconds
Elapsed time: 565milliseconds
Elapsed time: 3643milliseconds
Elapsed time: 566milliseconds
Elapsed time: 22018milliseconds
Elapsed time: 566milliseconds
Elapsed time: 3845milliseconds
Elapsed time: 569milliseconds


string str;
for(long long i=0;i<1000000;i++)

for(long long i=0;i<1000000;i++)
    for(unsigned short loop=0;loop < str.size();loop++)

I guess I should to the tests on a dedicated machine but I will be using this EC2 so I do not really need to test it on my machine.

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

Using set_facts and with_items together in Ansible

Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.

- name: Set fact 4
    foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"

I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.

- name: build foo_string
    foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"

- name: set fact foo
    foo: "{{ foo_string.split(',') }}"

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This appears to be a UTF-8 encoding issue that may have been caused by a double-UTF8-encoding of the database file contents.

This situation could happen due to factors such as the character set that was or was not selected (for instance when a database backup file was created) and the file format and encoding database file was saved with.

I have seen these strange UTF-8 characters in the following scenario (the description may not be entirely accurate as I no longer have access to the database in question):

  • As I recall, there the database and tables had a "uft8_general_ci" collation.
  • Backup is made of the database.
  • Backup file is opened on Windows in UNIX file format and with ANSI encoding.
  • Database is restored on a new MySQL server by copy-pasting the contents from the database backup file into phpMyAdmin.

Looking into the file contents:

  • Opening the SQL backup file in a text editor shows that the SQL backup file has strange characters such as "sÃ¥". On a side note, you may get different results if opening the same file in another editor. I use TextPad here but opening the same file in SublimeText said "sÃ¥" because SublimeText correctly UTF8-encoded the file -- still, this is a bit confusing when you start trying to fix the issue in PHP because you don't see the right data in SublimeText at first. Anyways, that can be resolved by taking note of which encoding your text editor is using when presenting the file contents.
  • The strange characters are double-encoded UTF-8 characters, so in my case the first "Ã" part equals "Ã" and "Â¥" = "¥" (this is my first "encoding"). THe "Ã¥" characters equals the UTF-8 character for "å" (this is my second encoding).

So, the issue is that "false" (UTF8-encoded twice) utf-8 needs to be converted back into "correct" utf-8 (only UTF8-encoded once).

Trying to fix this in PHP turns out to be a bit challenging:

utf8_decode() is not able to process the characters.

// Fails silently (as in - nothing is output)
$str = "så";

$str = utf8_decode($str);
printf("\n%s", $str);

$str = utf8_decode($str);
printf("\n%s", $str);

iconv() fails with "Notice: iconv(): Detected an illegal character in input string".

echo iconv("UTF-8", "ISO-8859-1", "så");

Another fine and possible solution fails silently too in this scenario

$str = "så";
echo html_entity_decode(htmlentities($str, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-15');

mb_convert_encoding() silently: #

$str = "så";
echo mb_convert_encoding($str, 'ISO-8859-15', 'UTF-8');
// (No output)

Trying to fix the encoding in MySQL by converting the MySQL database characterset and collation to UTF-8 was unsuccessfully:

ALTER DATABASE myDatabase CHARACTER SET utf8 COLLATE utf8_unicode_ci;

I see a couple of ways to resolve this issue.

The first is to make a backup with correct encoding (the encoding needs to match the actual database and table encoding). You can verify the encoding by simply opening the resulting SQL file in a text editor.

The other is to replace double-UTF8-encoded characters with single-UTF8-encoded characters. This can be done manually in a text editor. To assist in this process, you can manually pick incorrect characters from Try UTF-8 Encoding Debugging Chart (it may be a matter of replacing 5-10 errors).

Finally, a script can assist in the process:

    $str = "så";
    // The two arrays can also be generated by double-encoding values in the first array and single-encoding values in the second array.
    $str = str_replace(["Ã","Â¥"], ["Ã","¥"], $str); 
    $str = utf8_decode($str);
    echo $str;
    // Output: "så" (correct)

How to convert a private key to an RSA private key?

Newer versions of OpenSSL say BEGIN PRIVATE KEY because they contain the private key + an OID that identifies the key type (this is known as PKCS8 format). To get the old style key (known as either PKCS1 or traditional OpenSSL format) you can do this:

openssl rsa -in server.key -out server_new.key

Alternately, if you have a PKCS1 key and want PKCS8:

openssl pkcs8 -topk8 -nocrypt -in privkey.pem

How do I run a command on an already existing Docker container?

Your container will exit as the command you gave it will end. Use the following options to keep it live:

  • -i Keep STDIN open even if not attached.
  • -t Allocate a pseudo-TTY.

So your new run command is:

docker run -it -d shykes/pybuilder bin/bash

If you would like to attach to an already running container:

docker exec -it CONTAINER_ID /bin/bash

In these examples /bin/bash is used as the command.

CSS3 selector :first-of-type with class name?

Not sure how to explain this but I ran into something similar today. Not being able to set .user:first-of-type{} while .user:last-of-type{} worked fine. This was fixed after I wrapped them inside a div without any class or styling:



<p>Not working while this P additional tag exists</p>

<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>

<p>Working while inside a div:</p>

<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>

Java double.MAX_VALUE?

this states that Account.deposit(Double.MAX_VALUE); it is setting deposit value to MAX value of Double procced for running tests.

React navigation goBack() and update parent state

EDITED: The best solution is using NavigationEvents, you don't need to create listeners manually :)

Calling a callback function is not highly recommended, check this example using a listener (Remember to remove all listeners from componentWillUnMount with this option)

Component A

navigateToComponentB() {
  const { navigation } = this.props
  this.navigationListener = navigation.addListener('willFocus', payload => {
    const { state } = payload
    const { params } = state
    //update state with the new params
    const { otherParam } = params
    this.setState({ otherParam })
  navigation.push('ComponentB', {
    returnToRoute: navigation.state,
    otherParam: this.state.otherParam
removeNavigationListener() {
  if (this.navigationListener) {
    this.navigationListener = null
componentWillUnmount() {

Commponent B

returnToComponentA() {
  const { navigation } = this.props
  const { routeName, key } = navigation.getParam('returnToRoute')
  navigation.navigate({ routeName, key, params: { otherParam: 123 } })

For more details of the previous example:

Regards, Nicholls

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Installing Pandas on Mac OSX

You can install python with homebrew:

brew install python

Make sure that OSX uses the correct path:

which python

Then you can use the pip tool to install pandas:

pip install pandas

Make sure that all dependencies are installed. I followed this tutorial:

Works fine on my machine.

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Here it goes.

// Select by value_x000D_
// Select by text_x000D_
<script src=""></script>_x000D_
<select name="options">_x000D_
      <option value="1">First</option>_x000D_
      <option value="2">Second</option>_x000D_
      <option value="3">Third</option>_x000D_

Count number of iterations in a foreach loop

foreach ($array as $value)
        $counter = 0;

//Sorry if the code isn't shown correctly. :P

//I like this version more, because the counter variable is IN the foreach, and not above.

How many bits is a "word"?

This is from the book Hackers: Heroes of the Computer Revolution by Steven Levy.

.. the memory had been reduced to 4096 "words" of eighteen bits each. (A "bit" is a binary digit, either a 1 or 0. A series of binary numbers is called a "word").

As the other answers suggest, a "word" does not seem to have a fixed length.

Set width to match constraints in ConstraintLayout

From the official doc:

Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".

So if you want achieve MATCH_PARENT effect, you can do this:

    app:layout_constraintStart_toStartOf="parent" />

Configuring Git over SSH to login once

Try ssh-add, you need ssh-agent to be running and holding your private key

(Ok, responding to the updated question, you first run ssh-keygen to generate a public and private key as Jefromi explained. You put the public key on the server. You should use a passphrase, if you don't you have the equivalent of a plain-text password in your private key. But when you do, then you need as a practical matter ssh-agent as explained below.)

You want to be running ssh-agent in the background as you log in. Once you log in, the idea is to run ssh-add once and only once, in order to give the agent your passphrase, to decode your key. The agent then just sits in memory with your key unlocked and loaded, ready to use every time you ssh somewhere.

All ssh-family commands1 will then consult the agent and automatically be able to use your private key.

On OSX (err, macOS), GNOME and KDE systems, ssh-agent is usually launched automatically for you. I will go through the details in case, like me, you also have a Cygwin or other windows environment where this most certainly is not done for you.

Start here: man ssh-agent.

There are various ways to automatically run the agent. As the man page explains, you can run it so that it is a parent of all your login session's other processes. That way, the environment variables it provides will automatically be in all your shells. When you (later) invoke ssh-add or ssh both will have access to the agent because they all have the environment variables with magic socket pathnames or whatever.

Alternatively, you can run the agent as an ordinary child, save the environment settings in a file, and source that file in every shell when it starts.

My OSX and Ubuntu systems automatically do the agent launch setup, so all I have to do is run ssh-add once. Try running ssh-add and see if it works, if so, then you just need to do that once per reboot.

My Cygwin system needed it done manually, so I did this in my .profile and I have .bashrc source .profile:

. .agent > /dev/null
ps -p $SSH_AGENT_PID | grep ssh-agent > /dev/null || {
        ssh-agent > .agent
        . .agent > /dev/null

The .agent file is created automatically by the script; it contains the environment variables definitions and exports. The above tries to source the .agent file, and then tries to ps(1) the agent. If it doesn't work it starts an agent and creates a new agent file. You can also just run ssh-add and if it fails start an agent.

1. And even local and remote sudo with the right pam extension.

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

I.e. for Visual Studio 2013 I would reference this assembly:


You can find it i.e. here:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\BugAid Software\BugAid\1.0

and don't forget to implement:

using Microsoft.VisualStudio;

How do I use the new computeIfAbsent function?

Suppose you have the following code:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Test {
    public static void main(String[] s) {
        Map<String, Boolean> whoLetDogsOut = new ConcurrentHashMap<>();
        whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
        whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
    static boolean f(String s) {
        System.out.println("creating a value for \""+s+'"');
        return s.isEmpty();

Then you will see the message creating a value for "snoop" exactly once as on the second invocation of computeIfAbsent there is already a value for that key. The k in the lambda expression k -> f(k) is just a placeolder (parameter) for the key which the map will pass to your lambda for computing the value. So in the example the key is passed to the function invocation.

Alternatively you could write: whoLetDogsOut.computeIfAbsent("snoop", k -> k.isEmpty()); to achieve the same result without a helper method (but you won’t see the debugging output then). And even simpler, as it is a simple delegation to an existing method you could write: whoLetDogsOut.computeIfAbsent("snoop", String::isEmpty); This delegation does not need any parameters to be written.

To be closer to the example in your question, you could write it as whoLetDogsOut.computeIfAbsent("snoop", key -> tryToLetOut(key)); (it doesn’t matter whether you name the parameter k or key). Or write it as whoLetDogsOut.computeIfAbsent("snoop", MyClass::tryToLetOut); if tryToLetOut is static or whoLetDogsOut.computeIfAbsent("snoop", this::tryToLetOut); if tryToLetOut is an instance method.

How can I increase a scrollbar's width using CSS?


If the scrollbar is not the browser scrollbar, then it will be built of regular HTML elements (probably divs and spans) and can thus be styled (or will be Flash, Java, etc and can be customized as per those environments).

The specifics depend on the DOM structure used.

Angularjs simple file download causes router to redirect

We also had to develop a solution which would even work with APIs requiring authentication (see this article)

Using AngularJS in a nutshell here is how we did it:

Step 1: Create a dedicated directive

// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
    restrict: 'E',
    templateUrl: '/path/to/pdfDownload.tpl.html',
    scope: true,
    link: function(scope, element, attr) {
        var anchor = element.children()[0];

        // When the download starts, disable the link
        scope.$on('download-start', function() {
            $(anchor).attr('disabled', 'disabled');

        // When the download finishes, attach the data to the link. Enable the link and change its appearance.
        scope.$on('downloaded', function(event, data) {
                href: 'data:application/pdf;base64,' + data,
                download: attr.filename

            // Also overwrite the download pdf function to do nothing.
            scope.downloadPdf = function() {
    controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
        $scope.downloadPdf = function() {
            $http.get($attrs.url).then(function(response) {

Step 2: Create a template

<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>

Step 3: Use it

<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>

This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.

Our example uses PDF files, but apparently you could provide any binary format given it's properly encoded.

ORA-00918: column ambiguously defined in SELECT *

A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting * your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.

The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: as COACHES_ID.

Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT * is regarded as bad practice in production code: explicitly named columns are much safer.

XPath using starts-with function



Multiple line code example in Javadoc comment

The java source has lots of good examples for this. Here's an example from the head of "":

 * is equivalent to:
 * <p><blockquote><pre>
 *     char data[] = {'a', 'b', 'c'};
 *     String str = new String(data);
 * </pre></blockquote><p>
 * Here are some more examples of how strings can be used:
 * <p><blockquote><pre>
 *     System.out.println("abc");
 *     String cde = "cde";
 *     System.out.println("abc" + cde);
 *     String c = "abc".substring(2,3);
 *     String d = cde.substring(1, 2);
 * </pre></blockquote>

Update row with data from another row in the same table

Update MyTable
Set Value = (
                Select Min( T2.Value )
                From MyTable As T2
                Where T2.Id <> MyTable.Id
                    And T2.Name = MyTable.Name
Where ( Value Is Null Or Value = '' )
    And Exists  (
                Select 1
                From MyTable As T3
                Where T3.Id <> MyTable.Id
                    And T3.Name = MyTable.Name

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

May not be the exactly same problem. but there is a nice article on the same line Here

C# Remove object from list of objects

First you have to find out the object in the list. Then you can remove from the list.

       var item = myList.Find(x=>x.ItemName == obj.ItemName);

How to transfer data from JSP to servlet when submitting HTML form

Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet and inside it you will have two methods that look like

public void doPost(HttpServletRequest req, HttpServletResponse resp){



public void doGet(HttpServletRequest req, HttpServletResponse resp){


One of them is called to handle GET operations and another is used to handle POST operations. You will then use the HttpServletRequest object to get the parameters that were passed as part of the form like so:

String name = req.getParameter("name");

Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.

Linq code to select one item

I'll tell you what worked for me:

int id = int.Parse(insertItem.OwnerTableView.DataKeyValues[insertItem.ItemIndex]["id_usuario"].ToString());

var query = user.First(x => x.id_usuario == id);
tbUsername.Text = query.username;
tbEmail.Text =;
tbPassword.Text = query.password;

My id is the row I want to query, in this case I got it from a radGrid, then I used it to query, but this query returns a row, then you can assign the values you got from the query to textbox, or anything, I had to assign those to textbox.

Display a message in Visual Studio's output window when not debug mode?

For me this was the fact that debug.writeline shows in the Immediate window, not the Output. My installation of VS2013 by default doesn't even show an option to open the Immediate window, so you have to do the following:

Select Tools -> Customize 
Commands Tab
View | Other Windows menu bar dropdown
Add Command...
The Immediate option is in the Debug section.

Once you have Ok'd that, you can go to View -> Other Windows and select the Immediate Window and hey presto all of the debug output can be seen.

Unfortunately for me it also showed about 50 errors that I wasn't aware of in my project... maybe I'll just turn it off again :-)

Cause of a process being a deadlock victim

The answers here are worth a try, but you should also review your code. Specifically have a read of Polyfun's answer here: How to get rid of deadlock in a SQL Server 2005 and C# application?

It explains the concurrency issue, and how the usage of "with (updlock)" in your queries might correct your deadlock situation - depending really on exactly what your code is doing. If your code does follow this pattern, this is likely a better fix to make, before resorting to dirty reads, etc.

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

    .GroupBy(r => new { Col1 = r["Col1"], Col2 = r["Col2"] })
    .Select(g =>
        var row = dt.NewRow();

        row["PK"] = g.Min(r => r.Field<int>("PK"));
        row["Col1"] = g.Key.Col1;
        row["Col2"] = g.Key.Col2;

        return row;


Python String and Integer concatenation

for i in range (1,10):

To get string0, string1 ..... string10, you could do like

>>> ["string"+str(i) for i in range(11)]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10']

message box in jquery

TypeError: 'NoneType' object is not iterable in Python

It means the value of data is None.

How to style a select tag's option element?

Since version 49+, Chrome has supported styling <option> elements with font-weight. Source:

New SELECT Popup: font-weight style should be applied.

This CL removes themeChromiumSkia.css. |!important| in it prevented to apply font-weight. Now html.css has |font-weight:normal|, and |!important| should be unnecessary.

There was a Chrome stylesheet, themeChromiumSkia.css, that used font-weight: normal !important; in it all this time. It was introduced to the stable Chrome channel in version 49.0.

Are there best practices for (Java) package organization?

I'm not aware of standard practices for package organization. I generally create packages that cover some reasonably broad spectrum, but I can differentiate within a project. For example, a personal project I'm currently working on has a package devoted to my customized UI controls (full of classes subclassing swing classes). I've got a package devoted to my database management stuff, I've got a package for a set of listeners/events that I've created, and so on.

On the other hand I've had a coworker create a new package for almost everything he did. Each different MVC he wanted got its own package, and it seemed a MVC set was the only grouping of classes allowed to be in the same package. I recall at one point he had 5 different packages that each had a single class in them. I think his method is a little bit on the extreme (and the team forced him to reduce his package count when we simply couldn't handle it), but for a nontrivial application, so would putting everything in the same package. It's a balance point you and your teammates have to find for yourself.

One thing you can do is try to step back and think: if you were a new member introduced to the project, or your project was released as open source or an API, how easy/difficult would it be to find what you want? Because for me, that's what I really want out of packages: organization. Similar to how I store files in folder on my computer, I expect to be able to find them again without having to search my entire drive. I expect to be able to find the class I want without having to search the list of all classes in the package.

Post an object as data using Jquery Ajax

All arrays passed to php must be object literals. Here's an example from JS/jQuery:

var myarray = {};  //must be declared as an object literal first

myarray[fld1] = val;  // then you can add elements and values
myarray[fld2] = val;
myarray[fld3] = Array();  // array assigned to an element must also be declared as object literal


It can now be sent via Ajax in the data: parameter as follows:

data: { new_name: myarray },

php picks this up and reads it as a normal array without any decoding necessary. Here's an example:

$array = $_POST['new_name'];  // myarray became new_name (see above)
$fld1 = array['fld1'];
$fld2 = array['fld2'];

However, when you return an array to jQuery via Ajax it must first be encoded using json. Here's an example in php:

$return_array = json_encode($return_aray));

And the output from that looks something like this:

{"fname":"James","lname":"Feducia","vip":"true","owner":"false","cell_phone":"(801) 666-0909","email":"[email protected]", "contact_pk":"","travel_agent":""}

{again we see the object literal encoding tags} now this can be read by JS/jQuery as an array without any further action inside JS/JQuery... Here's an example in jquery ajax:

success: function(result) {
alert( "Return Values: " + result['fname'] + " " + result['lname'] );

How can I reduce the waiting (ttfb) time

I have met the same problem. My project is running on the local server. I checked my php code.

$db = mysqli_connect('localhost', 'root', 'root', 'smart');

I use localhost to connect to my local database. That maybe the cause of the problem which you're describing. You can modify your HOSTS file. Add the line localhost.

Send array with Ajax to PHP script

If you have been trying to send a one dimentional array and jquery was converting it to comma separated values >:( then follow the code below and an actual array will be submitted to php and not all the comma separated bull**it.

Say you have to attach a single dimentional array named myvals.

jQuery('#someform').on('submit', function (e) {
    var data = $(this).serializeArray();

    var myvals = [21, 52, 13, 24, 75]; // This array could come from anywhere you choose 
    for (i = 0; i < myvals.length; i++) {
            name: "myvals[]", // These blank empty brackets are imp!
            value: myvals[i]

    type: "post",
    url: jQuery(this).attr('action'),
    dataType: "json",
    data: data, // You have to just pass our data variable plain and simple no Rube Goldberg sh*t.
    success: function (r) {

Now inside php when you do this


You will get ..

    [someinputinsidetheform] => 023
    [anotherforminput] => 111
    [myvals] => Array
            [0] => 21
            [1] => 52
            [2] => 13
            [3] => 24
            [4] => 75

Pardon my language, but there are hell lot of Rube-Goldberg solutions scattered all over the web and specially on SO, but none of them are elegant or solve the problem of actually posting a one dimensional array to php via ajax post. Don't forget to spread this solution.

How do I write stderr to a file while using "tee" with a pipe?

The following will work for KornShell(ksh) where the process substitution is not available,

# create a combined(stdin and stdout) collector
exec 3 <> combined.log

# stream stderr instead of stdout to tee, while draining all stdout to the collector
./ 2>&1 1>&3 | tee -a stderr.log 1>&3

# cleanup collector
exec 3>&-

The real trick here, is the sequence of the 2>&1 1>&3 which in our case redirects the stderr to stdout and redirects the stdout to descriptor 3. At this point the stderr and stdout are not combined yet.

In effect, the stderr(as stdin) is passed to tee where it logs to stderr.log and also redirects to descriptor 3.

And descriptor 3 is logging it to combined.log all the time. So the combined.log contains both stdout and stderr.

How to call Makefile from another Makefile?

It seems clear that $(TESTS) is empty so your 1.4.0 makefile is effectively


  rm -f  gtest.a gtest_main.a *.o

Indeed, all has nothing to do. and clean does exactly what it says rm -f gtest.a ...

How to print to console using swift playground?

You may still have trouble displaying the output in the Assistant Editor. Rather than wrapping the string in println(), simply output the string. For example:

for index in 1...5 {
    "The number is \(index)"

Will write (5 times) in the playground area. This will allow you to display it in the Assistant Editor (via the little circle on the far right edge).

However, if you were to println("The number is \(index)") you wouldn't be able to visualize it in the Assistant Editor.

Check the current number of connections to MongoDb

db.runCommand( { "connPoolStats" : 1 } )

    "numClientConnections" : 0,
    "numAScopedConnections" : 0,
    "totalInUse" : 0,
    "totalAvailable" : 0,
    "totalCreated" : 0,
    "hosts" : {

    "replicaSets" : {

    "ok" : 1

Fetch: reject promise and catch the error if status is not OK?

Thanks for the help everyone, rejecting the promise in .catch() solved my issue:

export function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`${id}/`)
                .then(res => res.json())    
                .catch(error => {
                    return Promise.reject()

function status(res) {
    if (!res.ok) {
        throw new Error(res.statusText);
    return res;

Key Shortcut for Eclipse Imports

Ctrl+Space : Show Imports

This displays imports as you're typing a non-standard class name provided the proper references have been added to the project.

This works on partial or complete class names as you are typing them or after the fact (Just place the cursor back on the class name with squigglies).

OR, AND Operator

Logical OR is ||, logical AND is &&. If you need the negation NOT, prefix your expression with !.


X = (A && B) || C || !D;

Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).

If you wanted bit-wise AND/OR/NOT, you would use &, | and ~. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.

How to determine the number of days in a month in SQL Server?

select first_day=dateadd(dd,-1*datepart(dd,getdate())+1,getdate()), last_day=dateadd(dd,-1*datepart(dd,dateadd(mm,1,getdate())),dateadd(mm,1,getdate())), no_of_days = 1+datediff(dd,dateadd(dd,-1*datepart(dd,getdate())+1,getdate()),dateadd(dd,-1*datepart(dd,dateadd(mm,1,getdate())),dateadd(mm,1,getdate())))

replace any date with getdate to get the no of months in that particular date

Flutter command not found

Just revert to chsh -s /bin/bash from chsh -s /bin/zsh,

Run one command

chsh -s /bin/bash

Your facing this problem just because of you have change shell from /bash to /zsh in macOs. If you run this command again it will change the path again. So just run one command and problem solve.

error: RPC failed; curl transfer closed with outstanding read data remaining

Tried all of the answers on here. I was trying to add cocoapods onto my machine.

I didn't have an SSH key so thanks @Do Nhu Vy

And finally used

git clone ~/.cocoapods/repos/master

to finally fix the issue found

Force IE9 to emulate IE8. Possible?

Yes. Recent versions of IE (IE8 or above) let you adjust that. Here's how:

  • Fire up Internet Explorer.
  • Click the 'Tools' menu, then click 'Developer Tools'. Alternatively, just press F12.

That should open the Developer Tools window. That window has two menu items that are of interest:

  • Browser Mode. This setting determines the value of the user-agent header sent for every request.
  • Document Mode. This setting determines how the rendering engine renders the page.

More at

Can I change the headers of the HTTP request sent by the browser?

I don't think it's possible to do it in the way you are trying to do it.

Indication of the accepted data format is usually done through adding the extension to the resource name. So, if you have resource like


and GET /resources/resource returns its HTML representation, to indicate that you want its XML representation instead, you can use following pattern:


You have to do the accepted content type determination magic on the server side, then.

Or use Javascript as James suggests.

Where is debug.keystore in Android Studio

The default keystore file: debug.keystore is present in the folder .android which is usually located in the default home folder of your operating system of the user who installed that Android SDK.

In my Ubuntu PC, it's location is /home/dhananjay/.android

Whereas in the Windows PC it is located at C:\Users\dhananjay\.android

Take a screenshot via a Python script on Linux

Try it:


import gtk.gdk
import time
import random
import socket
import fcntl
import struct
import getpass
import os
import paramiko     

while 1:
    # generate a random time between 120 and 300 sec
    random_time = random.randrange(20,25)
    # wait between 120 and 300 seconds (or between 2 and 5 minutes) 

    print "Next picture in: %.2f minutes" % (float(random_time) / 60)

    w = gtk.gdk.get_default_root_window()   
    sz = w.get_size()
    print "The size of the window is %d x %d" % sz
    pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
    pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
    ts = time.asctime( time.localtime(time.time()) )
    date = time.strftime("%d-%m-%Y")
    timer = time.strftime("%I:%M:%S%p")
    filename = timer
    filename += ".png"

    if (pb != None):
        username = getpass.getuser() #Get username
        newpath = r'screenshots/'+username+'/'+date #screenshot save path
        if not os.path.exists(newpath): os.makedirs(newpath)
        saveas = os.path.join(newpath,filename)
        print saveas,"png")
        print "Unable to get the screenshot."

How can I control the speed that bootstrap carousel slides in items?

In your CSS:

.carousel-item {
    transition-duration: 1.5s, 1.5s;

Take care, the time is included in data-interval defined for the carousel.

Hope it helps... :)

How to run a python script from IDLE interactive shell?

execFile('') does the job for me. A thing to note is to enter the complete directory name of the .py file if it isnt in the Python folder itself (atleast this is the case on Windows)

For example, execFile('C:/')

LaTeX table positioning

In my case I was having an issue where the table was not being displayed right after the paragraph I inserted it, so I simply changed




Checking for a null object in C++

You can use a special designated object as the null object in case of references as follows:

class SomeClass

        int operator==(SomeClass &object)
            if(this == &object) 
                    return true;

            return false;

    static SomeClass NullObject;

SomeClass SomeClass::NullObject;

void print(SomeClass &val)
    if(val == SomeClass::NullObject)
        printf("\nNOT NULL");

Using print statements only to debug

A simple way to do this is to call a logging function:

DEBUG = True

def log(s):
    if DEBUG:
        print s

log("hello world")

Then you can change the value of DEBUG and run your code with or without logging.

The standard logging module has a more elaborate mechanism for this.

CSS - Expand float child DIV height to parent's height

CSS table display is ideal for this:

.parent {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
.parent > div {_x000D_
  display: table-cell;_x000D_
.child-left {_x000D_
  background: powderblue;_x000D_
.child-right {_x000D_
  background: papayawhip;_x000D_
<div class="parent">_x000D_
  <div class="child-left">Short</div>_x000D_
  <div class="child-right">Tall<br>Tall</div>_x000D_

Original answer (assumed any column could be taller):

You're trying to make the parent's height dependent on the children's height and children's height dependent on parent's height. Won't compute. CSS Faux columns is the best solution. There's more than one way of doing that. I'd rather not use JavaScript.

Environment variable in Jenkins Pipeline

To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.

One safe way to alter the environment is:

 withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'

This approach does not poison the env after the command execution.

Difference between volatile and synchronized in Java


There are 3 main issues with multithreading:

1) Race Conditions

2) Caching / stale memory

3) Complier and CPU optimisations

volatile can solve 2 & 3, but can't solve 1. synchronized/explicit locks can solve 1, 2 & 3.


1) Consider this thread unsafe code:


While it may look like one operation, it's actually 3: reading the current value of x from memory, adding 1 to it, and saving it back to memory. If few threads try to do it at the same time, the result of the operation is undefined. If x originally was 1, after 2 threads operating the code it may be 2 and it may be 3, depending on which thread completed which part of the operation before control was transferred to the other thread. This is a form of race condition.

Using synchronized on a block of code makes it atomic - meaning it make it as if the 3 operations happen at once, and there's no way for another thread to come in the middle and interfere. So if x was 1, and 2 threads try to preform x++ we know in the end it will be equal to 3. So it solves the race condition problem.

synchronized (this) {
   x++; // no problem now

Marking x as volatile does not make x++; atomic, so it doesn't solve this problem.

2) In addition, threads have their own context - i.e. they can cache values from main memory. That means that a few threads can have copies of a variable, but they operate on their working copy without sharing the new state of the variable among other threads.

Consider that on one thread, x = 10;. And somewhat later, in another thread, x = 20;. The change in value of x might not appear in the first thread, because the other thread has saved the new value to its working memory, but hasn't copied it to the main memory. Or that it did copy it to the main memory, but the first thread hasn't updated its working copy. So if now the first thread checks if (x == 20) the answer will be false.

Marking a variable as volatile basically tells all threads to do read and write operations on main memory only. synchronized tells every thread to go update their value from main memory when they enter the block, and flush the result back to main memory when they exit the block.

Note that unlike data races, stale memory is not so easy to (re)produce, as flushes to main memory occur anyway.

3) The complier and CPU can (without any form of synchronization between threads) treat all code as single threaded. Meaning it can look at some code, that is very meaningful in a multithreading aspect, and treat it as if it’s single threaded, where it’s not so meaningful. So it can look at a code and decide, in sake of optimisation, to reorder it, or even remove parts of it completely, if it doesn’t know that this code is designed to work on multiple threads.

Consider the following code:

boolean b = false;
int x = 10;

void threadA() {
    x = 20;
    b = true;

void threadB() {
    if (b) {

You would think that threadB could only print 20 (or not print anything at all if threadB if-check is executed before setting b to true), as b is set to true only after x is set to 20, but the compiler/CPU might decide to reorder threadA, in that case threadB could also print 10. Marking b as volatile ensures that it won’t be reordered (or discarded in certain cases). Which mean threadB could only print 20 (or nothing at all). Marking the methods as syncrhonized will achieve the same result. Also marking a variable as volatile only ensures that it won’t get reordered, but everything before/after it can still be reordered, so synchronization can be more suited in some scenarios.

Note that before Java 5 New Memory Model, volatile didn’t solve this issue.

When should I use a List vs a LinkedList

When you need built-in indexed access, sorting (and after this binary searching), and "ToArray()" method, you should use List.

How can I select an element with multiple classes in jQuery?

For the case

<element class="a">
  <element class="b c">

You would need to put a space in between .a and .b.c

$('.a .b.c')

Common MySQL fields and their appropriate data types

I am doing about the same thing, and here's what I did.

I used separate tables for name, address, email, and numbers, each with a NameID column that is a foreign key on everything except the Name table, on which it is the primary clustered key. I used MainName and FirstName instead of LastName and FirstName to allow for business entries as well as personal entries, but you may not have a need for that.

The NameID column gets to be a smallint in all the tables because I'm fairly certain I won't make more than 32000 entries. Almost everything else is varchar(n) ranging from 20 to 200, depending on what you wanna store (Birthdays, comments, emails, really long names). That is really dependent on what kind of stuff you're storing.

The Numbers table is where I deviate from that. I set it up to have five columns labeled NameID, Phone#, CountryCode, Extension, and PhoneType. I already discussed NameID. Phone# is varchar(12) with a check constraint looking something like this: CHECK (Phone# like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'). This ensures that only what I want makes it into the database and the data stays very consistent. The extension and country codes I called nullable smallints, but those could be varchar if you wanted to. PhoneType is varchar(20) and is not nullable.

Hope this helps!

How can I combine multiple nested Substitute functions in Excel?

Thanks for the idea of breaking down a formula Werner!

Using Alt+Enter allows one to put each bit of a complex substitute formula on separate lines: they become easier to follow and automatically line themselves up when Enter is pressed.

Just make sure you have enough end statements to match the number of substitute( lines either side of the cell reference.

As in this example:




which works fine as is, but one can always delete the extra paragraphs manually:


Name > substitute()

[American Samoa] > American Samoa

What are the sizes used for the iOS application splash screen?

You can make them 1024 x 768. You can also check "Status bar is initially hidden" in the plist file.

In PHP, what is a closure and why does it use the "use" identifier?

The function () use () {} is like closure for PHP.

Without use, function cannot access parent scope variable

$s = "hello";
$f = function () {
    echo $s;

$f(); // Notice: Undefined variable: s
$s = "hello";
$f = function () use ($s) {
    echo $s;

$f(); // hello

The use variable's value is from when the function is defined, not when called

$s = "hello";
$f = function () use ($s) {
    echo $s;

$s = "how are you?";
$f(); // hello

use variable by-reference with &

$s = "hello";
$f = function () use (&$s) {
    echo $s;

$s = "how are you?";
$f(); // how are you?

How do I write good/correct package files

Your should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

Is it possible to change javascript variable values while debugging in Google Chrome?

Why is this answer still getting upvotes?

Per Mikaël Mayer's answer, this is no longer a problem, and my answer is obsolete (go() now returns 30 after mucking with the console). This was fixed in July 2013, according to the bug report linked above in gabrielmaldi's comment. It alarms me that I'm still getting upvotes - makes me think the upvoter doesn't understand either the question or my answer.

I'll leave my original answer here for historical reasons, but go upvote Mikaël's answer instead.

The trick is that you can't change a local variable directly, but you can modify the properties of an object. You can also modify the value of a global variable:

var g_n = 0;
function go()
    var n = 0;
    var o = { n: 0 };
    return g_n + n + o.n;  // breakpoint here


> g_n = 10
> g_n
> n = 10
> n
> o.n = 10
> o.n

Check the result of go() after setting the breakpoint and running those calls in the console, and you'll find that the result is 20, rather than 0 (but sadly, not 30).

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

A simple way to enable polymorphic serialization / deserialization via Jackson library is to globally configure the Jackson object mapper (jackson.databind.ObjectMapper) to add information, such as the concrete class type, for certain kinds of classes, such as abstract classes.

To do that, just make sure your mapper is configured correctly. For example:

Option 1: Support polymorphic serialization / deserialization for abstract classes (and Object typed classes)


Option 2: Support polymorphic serialization / deserialization for abstract classes (and Object typed classes), and arrays of those types.



How to spyOn a value property (rather than a method) with Jasmine

I'm using a kendo grid and therefore can't change the implementation to a getter method but I want to test around this (mocking the grid) and not test the grid itself. I was using a spy object but this doesn't support property mocking so I do this:

    this.$scope.ticketsGrid = { 
        showColumn: jasmine.createSpy('showColumn'),
        hideColumn: jasmine.createSpy('hideColumn'),
        select: jasmine.createSpy('select'),
        dataItem: jasmine.createSpy('dataItem'),
        _data: []

It's a bit long winded but it works a treat

How to handle onchange event on input type=file in jQuery?

This jsfiddle works fine for me.

$(document).delegate(':file', 'change', function() {

Note: .delegate() is the fastest event-binding method for jQuery < 1.7: event-binding methods

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

With Bootstrap 4 .hidden-* classes were completely removed (yes, they were replaced by hidden-*-* but those classes are also gone from v4 alphas).

Starting with v4-beta, you can combine .d-*-none and .d-*-block classes to achieve the same result.

visible-* was removed as well; instead of using explicit .visible-* classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:

<div class="col d-none d-sm-block">
    <span class="vcard">
<div class="col d-none d-xl-block">
    <div class="d-none d-md-block">
    <div class="d-none d-sm-block">

class="hidden-xs" becomes class="d-none d-sm-block" (or d-none d-sm-inline-block) ...

<span class="d-none d-sm-inline">hidden-xs</span>

<span class="d-none d-sm-inline-block">hidden-xs</span>

An example of Bootstrap 4 responsive utilities:

<div class="d-none d-sm-block"> hidden-xs           
  <div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
    <div class="d-none d-lg-block"> visible-lg and up  (hidden-md and down)
      <div class="d-none d-xl-block"> visible-xl </div>

<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>

<div class="d-xl-none"> hidden-xl (visible-lg and down)         
  <div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
    <div class="d-md-none d-lg-none d-xl-none"> visible-sm and down  (or hidden-md and up)
      <div class="d-sm-none"> visible-xs </div>


How can I specify a [DllImport] path at runtime?

If you need a .dll file that is not on the path or on the application's location, then I don't think you can do just that, because DllImport is an attribute, and attributes are only metadata that is set on types, members and other language elements.

An alternative that can help you accomplish what I think you're trying, is to use the native LoadLibrary through P/Invoke, in order to load a .dll from the path you need, and then use GetProcAddress to get a reference to the function you need from that .dll. Then use these to create a delegate that you can invoke.

To make it easier to use, you can then set this delegate to a field in your class, so that using it looks like calling a member method.


Here is a code snippet that works, and shows what I meant.

class Program
    static void Main(string[] args)
        var a = new MyClass();
        var result = a.ShowMessage();

class FunctionLoader
    private static extern IntPtr LoadLibrary(string path);

    private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    public static Delegate LoadFunction<T>(string dllPath, string functionName)
        var hModule = LoadLibrary(dllPath);
        var functionAddress = GetProcAddress(hModule, functionName);
        return Marshal.GetDelegateForFunctionPointer(functionAddress, typeof (T));

public class MyClass
    static MyClass()
        // Load functions and set them up as delegates
        // This is just an example - you could load the .dll from any path,
        // and you could even determine the file location at runtime.
        MessageBox = (MessageBoxDelegate) 
                @"c:\windows\system32\user32.dll", "MessageBoxA");

    private delegate int MessageBoxDelegate(
        IntPtr hwnd, string title, string message, int buttons); 

    /// <summary>
    /// This is the dynamic P/Invoke alternative
    /// </summary>
    static private MessageBoxDelegate MessageBox;

    /// <summary>
    /// Example for a method that uses the "dynamic P/Invoke"
    /// </summary>
    public int ShowMessage()
        // 3 means "yes/no/cancel" buttons, just to show that it works...
        return MessageBox(IntPtr.Zero, "Hello world", "Loaded dynamically", 3);

Note: I did not bother to use FreeLibrary, so this code is not complete. In a real application, you should take care to release the loaded modules to avoid a memory leak.

I have filtered my Excel data and now I want to number the rows. How do I do that?

Add a column for example 'Selected' First. Then Filter your data. Go to the column 'Selected'. Provide any proxy text or number to all rows. like '1' or 'A' - now your hidden Rows are Blank Now, Clear Filter and Use Sorting - two levels Sort by - 'Selected' Ascending - this leaves blank cells at bottom Add Sort Level - 'Any column you Desire' your order

Now, Why dont you drag the autofill yourself.

Oops, I have no reputation here.

SQL multiple columns in IN clause

In general you can easily write the Where-Condition like this:

select * from tab1
where (col1, col2) in (select col1, col2 from tab2)

Oracle ignores rows where one or more of the selected columns is NULL. In these cases you probably want to make use of the NVL-Funktion to map NULL to a special value (that should not be in the values):

select * from tab1
where (col1, NVL(col2, '---') in (select col1, NVL(col2, '---') from tab2)

An array of List in c#

Since no context was given to this question and you are a relatively new user, I want to make sure that you are aware that you can have a list of lists. It's not the same as array of list and you asked specifically for that, but nevertheless:

List<List<int>> myList = new List<List<int>>();

you can initialize them through collection initializers like so:

List<List<int>> myList = new List<List<int>>(){{1,2,3},{4,5,6},{7,8,9}};

How to import JsonConvert in C# application?

JsonConvert is from the namespace Newtonsoft.Json, not System.ServiceModel.Web

Use NuGet to download the package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

How to go to each directory and execute a command?

While one liners are good for quick and dirty usage, I prefer below more verbose version for writing scripts. This is the template I use which takes care of many edge cases and allows you to write more complex code to execute on a folder. You can write your bash code in the function dir_command. Below, dir_coomand implements tagging each repository in git as an example. Rest of the script calls dir_command for each folder in directory. The example of iterating through only given set of folder is also include.


#Use set -x if you want to echo each command while getting executed
#set -x

#Save current directory so we can restore it later
#Save command line arguments so functions can access it

#Put your code in this function
#To access command line arguments use syntax ${args[1]} etc
function dir_command {
    #This example command implements doing git status for folder
    cd $1
    echo "$(tput setaf 2)$1$(tput sgr 0)"
    git tag -a ${args[0]} -m "${args[1]}"
    git push --tags
    cd ..

#This loop will go to each immediate child and execute dir_command
find . -maxdepth 1 -type d \( ! -name . \) | while read dir; do
   dir_command "$dir/"

#This example loop only loops through give set of folders    
declare -a dirs=("dir1" "dir2" "dir3")
for dir in "${dirs[@]}"; do
    dir_command "$dir/"

#Restore the folder
cd "$cur"

Visual Studio Code includePath

My c_cpp_properties.json config-

    "configurations": [
            "name": "Win32",
            "compilerPath": "C:/MinGW/bin/g++.exe",
            "includePath": [
            "defines": [
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "windows-gcc-x64"
    "version": 4

Installing Java on OS X 10.9 (Mavericks)

From the OP:

I finally reinstalled it from Java for OS X 2013-005. It solved this issue.

how to get current month and year

label1.Text = DateTime.Now.Month.ToString();


label2.Text = DateTime.Now.Year.ToString();

Add element to a list In Scala

Use import scala.collection.mutable.MutableList or similar if you really need mutation.

import scala.collection.mutable.MutableList
val x = MutableList(1, 2, 3, 4, 5)
x += 6 // MutableList(1, 2, 3, 4, 5, 6)
x ++= MutableList(7, 8, 9) // MutableList(1, 2, 3, 4, 5, 6, 7, 8, 9)

How to delete and recreate from scratch an existing EF Code First database

Single Liner to Drop, Create and Seed from Package Manager Console:

update-database -TargetMigration:0 | update-database -force


Highlight all occurrence of a selected word?

My favorite for doing this is the mark.vim plugin. It allows to highlight several words in different colors simultaneously.

Example Screenshot

What is the shortcut to Auto import all in Android Studio?

Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:

Select Insert imports on paste value to All

Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*

jquery - check length of input field?

That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if condition is always true.

The simplest way to make it work, it seems to me, is to account for this case:

    var value = $(this).val();
    if ( value.length > 0 && value != "Default text" ) ...

How can I get the status code from an http error in Axios?

As @Nick said, the results you see when you console.log a JavaScript Error object depend on the exact implementation of console.log, which varies and (imo) makes checking errors incredibly annoying.

If you'd like to see the full Error object and all the information it carries bypassing the toString() method, you could just use JSON.stringify:

  .catch(function (error) {

Oracle - Insert New Row with Auto Incremental ID

To get an auto increment number you need to use a sequence in Oracle. (See here and here).


SELECT my_seq.NEXTVAL FROM DUAL; -- to get the next value

-- use in a trigger for your table demo

  FROM   dual;

How can I select the row with the highest ID in MySQL?

SELECT * FROM `permlog` as one
RIGHT JOIN (SELECT MAX(id) as max_id FROM `permlog`) as two 
ON = two.max_id

Docker container will automatically stop after "docker run -d"

I have this code snippet run from the ENTRYPOINT in my docker file:

while true
    echo "Press [CTRL+C] to stop.."
    sleep 1

Run the built docker image as:

docker run -td <image name>

Log in to the container shell:

docker exec -it <container id> /bin/bash

What is "X-Content-Type-Options=nosniff"?

# prevent mime based attacks
Header set X-Content-Type-Options "nosniff"

This header prevents "mime" based attacks. This header prevents Internet Explorer from MIME-sniffing a response away from the declared content-type as the header instructs the browser not to override the response content type. With the nosniff option, if the server says the content is text/html, the browser will render it as text/html.