Programs & Examples On #Jquery

jQuery is a popular cross-browser JavaScript library that facilitates Document Object Model (DOM) traversal, event handling, animations, and AJAX interactions by minimizing the discrepancies across browsers. A question tagged jquery should be related to jquery, so jquery should be used by the code in question and at least a jquery usage-related elements need to be in the question.

How do I check if an element is hidden in jQuery?

Try

content.style.display != 'none'

_x000D_
_x000D_
function toggle() {_x000D_
  $(content).toggle();_x000D_
  let visible= content.style.display != 'none'_x000D_
  console.log('visible:', visible);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<button onclick="toggle()">Show/hide</button>_x000D_
<div id="content">ABC</div>
_x000D_
_x000D_
_x000D_

jQuery iframe load() event?

You may use the jquery's Contents method to get the content of the iframe.

How do you append rows to a table using jQuery?

I'm assuming you want to add this row to the <tbody> element, and simply using append() on the <table> will insert the <tr> outside the <tbody>, with perhaps undesirable results.

$('a').click(function() {
   $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
});

EDIT: Here is the complete source code, and it does indeed work: (Note the $(document).ready(function(){});, which was not present before.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('a').click(function() {
       $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
    });
});
</script>
<title></title>
</head>
<body>
<a href="javascript:void(0);">Link</a>
<table id="myTable">
  <tbody>
    <tr>
      <td>test</td>
    </tr>
  </tbody>
</table>
</body>
</html>

jQuery: how to get which button was clicked upon form submission?

If what you mean by not adding a .click event is that you don't want to have separate handlers for those events, you could handle all clicks (submits) in one function:

$(document).ready(function(){
  $('input[type="submit"]').click( function(event){ process_form_submission(event); } );
});

function process_form_submission( event ) {
  event.preventDefault();
  //var target = $(event.target);
  var input = $(event.currentTarget);
  var which_button = event.currentTarget.value;
  var data = input.parents("form")[0].data.value;
//  var which_button = '?';       // <-- this is what I want to know
  alert( 'data: ' + data + ', button: ' + which_button );
}

make html text input field grow as I type?

Here is an example with only CSS and Content Editable:

jsFiddle Example

CSS

span 
{
    border: solid 1px black;
}
div 
{
    max-width: 200px;   
}

HTML

<div>
    <span contenteditable="true">sdfsd</span>
</div>

Important note regarding contenteditable

Making an HTML element contenteditable lets users paste copied HTML elements inside of this element. This may not be ideal for your use case, so keep that in mind when choosing to use it.

How do I get the n-th level parent of an element in jQuery?

It's simple. Just use

$(selector).parents().eq(0); 

where 0 is the parent level (0 is parent, 1 is parent's parent etc)

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

I had the same problem when I was working on asp.net Mvc webApi because cors was not enabled. I solved this by enabling cors inside register method of webApiconfig

First install cors from here then

   public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);



        config.EnableCors();
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

Change values of select box of "show 10 entries" of jquery datatable

$(document).ready(function() {
    $('#example').dataTable( {
    "aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]],
    "pageLength": 25
    } );
} );

aLengthMenu : This parameter allows you to readily specify the entries in the length drop down menu that DataTables shows when pagination is enabled. It can be either a 1D array of options which will be used for both the displayed option and the value, or a 2D array which will use the array in the first position as the value, and the array in the second position as the displayed options (useful for language strings such as 'All').

Update

Since DataTables v1.10, the options you are looking for are pageLength and lengthMenu

How to get span tag inside a div in jQuery and assign a text?

Try this:

$("#message span").text("hello world!");

See it in your code!

function Errormessage(txt) {
    var m = $("#message");

    // set text before displaying message
    m.children("span").text(txt);

    // bind close listener
    m.children("a.close-notify").click(function(){
      m.fadeOut("slow");
    });

    // display message
    m.fadeIn("slow");
}

jquery - fastest way to remove all rows from a very large table

It's better to avoid any kind of loops, just remove all elements directly like this:

$("#mytable > tbody").html("");

jQuery adding 2 numbers from input fields

Ok so your code actually works but what you need to do is replace a and b in your click function with the jquery notation you used before the click. This will ensure you have the correct and most up to date values. so changing your click function to this should work:

$("submit").on("click", function(){
    var sum = $("#a").val().match(/\d+/) + $("#b").val().match(/\d+/);
    alert(sum);         
})

or inlined to:

$("submit").on("click", function(){
    alert($("#a").val().match(/\d+/) + $("#b").val().match(/\d+/));         
})

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.

What I finally end up doing was replacing the single quote ' with it code &#39; using a regex after the stringify() method call the following way:

var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "&#39;");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.

How to make a dropdown readonly using jquery?

This code will first store the original selection on each dropdown. Then if the user changes the selection it will reset the dropdown to its original selection.

http://jsfiddle.net/4aHcD/22/

//store the original selection
$("select :selected").each(function(){
    $(this).parent().data("default", this);
});

//change the selction back to the original
$("select").change(function(e) {
    $($(this).data("default")).prop("selected", true);
});

Add image in pdf using jspdf

I find it useful.

var imgData = 'data:image/jpeg;base64,verylongbase64;'

var doc = new jsPDF();

doc.setFontSize(40);
doc.text(35, 25, "Octonyan loves jsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);

http://mrrio.github.io/jsPDF/

Set the Value of a Hidden field using JQuery

The selector should not be #input. That means a field with id="input" which is not your case. You want:

$('#chag_sort').val(sort2);

Or if your hidden input didn't have an unique id but only a name="chag_sort":

$('input[name="chag_sort"]').val(sort2);

jQuery & CSS - Remove/Add display:none

For some reason, toggle didn't work for me, and I received the error uncaught type error toggle is not a function when inspecting the element in browser. So I used the following code and it started working for me.

$(".trigger").click(function () {
    $('.news').attr('style', 'display:none');
})

Used jquery script file jquery-2.1.3.min.js.

Browser back button handling

Warn/confirm User if Back button is Pressed is as below.

window.onbeforeunload = function() { return "Your work will be lost."; };

You can get more information using below mentioned links.

Disable Back Button in Browser using JavaScript

I hope this will help to you.

Loading cross-domain endpoint with AJAX

I'm posting this in case someone faces the same problem I am facing right now. I've got a Zebra thermal printer, equipped with the ZebraNet print server, which offers a HTML-based user interface for editing multiple settings, seeing the printer's current status, etc. I need to get the status of the printer, which is displayed in one of those html pages, offered by the ZebraNet server and, for example, alert() a message to the user in the browser. This means that I have to get that html page in Javascript first. Although the printer is within the LAN of the user's PC, that Same Origin Policy is still staying firmly in my way. I tried JSONP, but the server returns html and I haven't found a way to modify its functionality (if I could, I would have already set the magic header Access-control-allow-origin: *). So I decided to write a small console app in C#. It has to be run as Admin to work properly, otherwise it trolls :D an exception. Here is some code:

// Create a listener.
        HttpListener listener = new HttpListener();
        // Add the prefixes.
        //foreach (string s in prefixes)
        //{
        //    listener.Prefixes.Add(s);
        //}
        listener.Prefixes.Add("http://*:1234/"); // accept connections from everywhere,
        //because the printer is accessible only within the LAN (no portforwarding)
        listener.Start();
        Console.WriteLine("Listening...");
        // Note: The GetContext method blocks while waiting for a request. 
        HttpListenerContext context;
        string urlForRequest = "";

        HttpWebRequest requestForPage = null;
        HttpWebResponse responseForPage = null;
        string responseForPageAsString = "";

        while (true)
        {
            context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            urlForRequest = request.RawUrl.Substring(1, request.RawUrl.Length - 1); // remove the slash, which separates the portNumber from the arg sent
            Console.WriteLine(urlForRequest);

            //Request for the html page:
            requestForPage = (HttpWebRequest)WebRequest.Create(urlForRequest);
            responseForPage = (HttpWebResponse)requestForPage.GetResponse();
            responseForPageAsString = new StreamReader(responseForPage.GetResponseStream()).ReadToEnd();

            // Obtain a response object.
            HttpListenerResponse response = context.Response;
            // Send back the response.
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseForPageAsString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            response.AddHeader("Access-Control-Allow-Origin", "*"); // the magic header in action ;-D
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            // You must close the output stream.
            output.Close();
            //listener.Stop();

All the user needs to do is run that console app as Admin. I know it is way too ... frustrating and complicated, but it is sort of a workaround to the Domain Policy problem in case you cannot modify the server in any way.

edit: from js I make a simple ajax call:

$.ajax({
                type: 'POST',
                url: 'http://LAN_IP:1234/http://google.com',
                success: function (data) {
                    console.log("Success: " + data);
                },
                error: function (e) {
                    alert("Error: " + e);
                    console.log("Error: " + e);
                }
            });

The html of the requested page is returned and stored in the data variable.

Check if checkbox is checked with jQuery

All following methods are useful:

$('#checkbox').is(":checked")

$('#checkbox').prop('checked')

$('#checkbox')[0].checked

$('#checkbox').get(0).checked

It is recommended that DOMelement or inline "this.checked" should be avoided instead jQuery on method should be used event listener.

How to get child element by ID in JavaScript?

(Dwell in atom)

<div id="note">

   <textarea id="textid" class="textclass">Text</textarea>

</div>

<script type="text/javascript">

   var note = document.getElementById('textid').value;

   alert(note);

</script>

How to grab substring before a specified character jQuery or JavaScript

//split string into an array and grab the first item

var streetaddress = addy.split(',')[0];

Also, I'd recommend naming your variables with camel-case(streetAddress) for better readability.

how to set radio option checked onload with jQuery

Say you had radio buttons like these, for example:

<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>

And you wanted to check the one with a value of "Male" onload if no radio is checked:

$(function() {
    var $radios = $('input:radio[name=gender]');
    if($radios.is(':checked') === false) {
        $radios.filter('[value=Male]').prop('checked', true);
    }
});

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

this is my simple implementation for ASYNC requests with jQuery. I hope this help anyone.

var queueUrlsForRemove = [
    'http://dev-myurl.com/image/1', 
    'http://dev-myurl.com/image/2',
    'http://dev-myurl.com/image/3',
];

var queueImagesDelete = function(){

    deleteImage( queueUrlsForRemove.splice(0,1), function(){
        if (queueUrlsForRemove.length > 0) {
            queueImagesDelete();
        }
    });

}

var deleteImage = function(url, callback) {
    $.ajax({
        url: url,
        method: 'DELETE'
    }).done(function(response){
        typeof(callback) == 'function' ? callback(response) : null;
    });
}

queueImagesDelete();

Making Enter key on an HTML form submit instead of activating button

I just hit a problem with this. Mine was a fall off from changing the input to a button and I'd had a badly written /> tag terminator:

So I had:

<button name="submit_login" type="submit" class="login" />Login</button>

And have just amended it to:

<button name="submit_login" type="submit" class="login">Login</button>

Now works like a charm, always the annoying small things... HTH

jQuery animated number counter from zero to value

What the code does, is that the number 8000 is counting up from 0 to 8000. The problem is, that it is placed at the middle of quite long page, and once user scroll down and actually see the number, the animation is already dine. I would like to trigger the counter, once it appears in the viewport.

JS:

$('.count').each(function () {
                $(this).prop('Counter',0).animate({
                        Counter: $(this).text()
                }, {
                        duration: 4000,
                        easing: 'swing',
                        step: function (now) {
                                $(this).text(Math.ceil(now));
                        }
                });
            });

And HTML:

 <span class="count">8000</span>

Change hash without reload in jQuery

The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {

    // Prevent default anchor handling (which causes the page-jumping)
    event.preventDefault();

    if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if ( target.length ) {    
            // Smooth scrolling to anchor
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);

            // Update URL
            window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
        }
    }
});

Event handler not working on dynamic content

You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).

See http://api.jquery.com/on/#direct-and-delegated-events

Change your code to

$(document.body).on('click', '.update' ,function(){

The jQuery set receives the event then delegates it to elements matching the selector given as argument. This means that contrary to when using live, the jQuery set elements must exist when you execute the code.

As this answers receives a lot of attention, here are two supplementary advises :

1) When it's possible, try to bind the event listener to the most precise element, to avoid useless event handling.

That is, if you're adding an element of class b to an existing element of id a, then don't use

$(document.body).on('click', '#a .b', function(){

but use

$('#a').on('click', '.b', function(){

2) Be careful, when you add an element with an id, to ensure you're not adding it twice. Not only is it "illegal" in HTML to have two elements with the same id but it breaks a lot of things. For example a selector "#c" would retrieve only one element with this id.

Get values from label using jQuery

Firstly, I don't think spaces for an id is valid.

So i'd change the id to not include spaces.

<label year="2010" month="6" id="currentMonth"> June &nbsp;2010</label>

then the jquery code is simple (keep in mind, its better to fetch the jquery object once and use over and over agian)

var label = $('#currentMonth');
var month = label.attr('month');
var year = label.attr('year');
var text = label.text();

HTML-encoding lost when attribute read from input field

My pure-JS function:

/**
 * HTML entities encode
 *
 * @param {string} str Input text
 * @return {string} Filtered text
 */
function htmlencode (str){

  var div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
}

JavaScript HTML Entities Encode & Decode

regex with space and letters only?

Allowed only characters & spaces. Ex : Jayant Lonari

if (!/^[a-zA-Z\s]+$/.test(NAME)) {
    //Throw Error
}

Hide/Show Column in an HTML Table

<p><input type="checkbox" name="ch1" checked="checked" /> First Name</p>
.... 
<td class="ch1">...</td>

 <script>
       $(document).ready(function() {
            $('#demo').multiselect();
        });


        $("input:checkbox:not(:checked)").each(function() {
    var column = "table ." + $(this).attr("name");
    $(column).hide();
});

$("input:checkbox").click(function(){
    var column = "table ." + $(this).attr("name");
    $(column).toggle();
});
 </script>

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

You can try this

$('#startdate').val()

or

$('#startdate').data('date')

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.

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

It seems you don't import jquery. Those $ functions come with this non standard (but very useful) library.

Read the tutorial there : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery It starts with how to import the library.

How to show hidden divs on mouseover?

There is a really simple way to do this in a CSS only way.

Apply an opacity to 0, therefore making it invisible, but it will still react to JavaScript events and CSS selectors. In the hover selector, make it visible by changing the opacity value.

_x000D_
_x000D_
#mouse_over {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
#mouse_over:hover {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div style='border: 5px solid black; width: 120px; font-family: sans-serif'>_x000D_
<div style='height: 20px; width: 120px; background-color: cyan;' id='mouse_over'>Now you see me</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I check whether a option already exist in select by JQuery

This evaluates to true if it already exists:

$("#yourSelect option[value='yourValue']").length > 0;

jQuery Selector: Id Ends With?

Try

$("element[id$='txtTitle']");

edit: 4 seconds late :P

regular expression to validate datetime format (MM/DD/YYYY)

It's long, but great:

new RegExp(/(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/);

How to show a running progress bar while page is loading

It’s a chicken-and-egg problem. You won’t be able to do it because you need to load the assets to display the progress bar widget, by which time your page will be either fully or partially downloaded. Also, you need to know the total size of the page prior to the user requesting in order to calculate a percentage.

It’s more hassle than it’s worth.

Custom events in jQuery?

I had a similar question, but was actually looking for a different answer; I'm looking to create a custom event. For example instead of always saying this:

$('#myInput').keydown(function(ev) {
    if (ev.which == 13) {
        ev.preventDefault();
        // Do some stuff that handles the enter key
    }
});

I want to abbreviate it to this:

$('#myInput').enterKey(function() {
    // Do some stuff that handles the enter key
});

trigger and bind don't tell the whole story - this is a JQuery plugin. http://docs.jquery.com/Plugins/Authoring

The "enterKey" function gets attached as a property to jQuery.fn - this is the code required:

(function($){
    $('body').on('keydown', 'input', function(ev) {
        if (ev.which == 13) {
            var enterEv = $.extend({}, ev, { type: 'enterKey' });
            return $(ev.target).trigger(enterEv);
        }
    });

    $.fn.enterKey = function(selector, data, fn) {
        return this.on('enterKey', selector, data, fn);
    };
})(jQuery);

http://jsfiddle.net/b9chris/CkvuJ/4/

A nicety of the above is you can handle keyboard input gracefully on link listeners like:

$('a.button').on('click enterKey', function(ev) {
    ev.preventDefault();
    ...
});

Edits: Updated to properly pass the right this context to the handler, and to return any return value back from the handler to jQuery (for example in case you were looking to cancel the event and bubbling). Updated to pass a proper jQuery event object to handlers, including key code and ability to cancel event.

Old jsfiddle: http://jsfiddle.net/b9chris/VwEb9/24/

$(window).scrollTop() vs. $(document).scrollTop()

They are both going to have the same effect.

However, as pointed out in the comments: $(window).scrollTop() is supported by more web browsers than $('html').scrollTop().

how to bypass Access-Control-Allow-Origin?

Have you tried actually adding the Access-Control-Allow-Origin header to the response sent from your server? Like, Access-Control-Allow-Origin: *?

Problems with jQuery getJSON using local files in Chrome

An additional way to get around the problem is by leveraging Flash Player's Local Only security sandbox and ExternalInterface methods. One can have JavaScript request a Flash application published using the Local Only security sandbox to load the file from the hard drive, and Flash can pass the data back to JavaScript via Flash's ExternalInterface class. I've tested this in Chrome, FF and IE9, and it works well. I'd be happy to share the code if anyone is interested.

EDIT: I've started a google code (ironic?) project for the implementation: http://code.google.com/p/flash-loader/

How to detect pressing Enter on keyboard using jQuery?

I used $(document).on("keydown").

On some browsers keyCode is not supported. The same with which so if keyCode is not supported you need to use which and vice versa.

_x000D_
_x000D_
$(document).on("keydown", function(e) {_x000D_
  const ENTER_KEY_CODE = 13;_x000D_
  const ENTER_KEY = "Enter";_x000D_
  var code = e.keyCode || e.which_x000D_
  var key = e.key_x000D_
  if (code == ENTER_KEY_CODE || key == ENTER_KEY) {_x000D_
    console.log("Enter key pressed")_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

How to prevent user from typing in text field without disabling the field?

Markup

<asp:TextBox ID="txtDateOfBirth" runat="server" onkeydown="javascript:preventInput(event);" onpaste="return false;"
                                TabIndex="1">

Script

function preventInput(evnt) {
//Checked In IE9,Chrome,FireFox
if (evnt.which != 9) evnt.preventDefault();}

jQuery Array of all selected checkboxes (by class)

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

json Uncaught SyntaxError: Unexpected token :

I had the same problem and the solution was to encapsulate the json inside this function

jsonp(

.... your json ...

)

How to get an Array with jQuery, multiple <input> with the same name

To catch the names array, i use that:

$("input[name*='task']")

How can I scroll to a specific location on the page using jquery?

<script type="text/javascript">
    $(document).ready(function(){
        $(".scroll-element").click(function(){
            $('html,body').animate({
                scrollTop: $('.our_companies').offset().top
            }, 1000);

            return false;
        });
    })
</script>

Disable Copy or Paste action for text box?

Use

oncopy="return false" onpaste="return false"

Email: <input type="textbox" id="email" oncopy="return false" onpaste="return false" ><br/>
Confirm Email:    <input type="textbox" id="confirmEmail" oncopy="return false" onpaste="return false">

http://jsfiddle.net/S22ew/4/

Validation of radio button group using jQuery validation plugin

Puts the error message on top.

   <style> 

 .radio-group{ 
      position:relative; margin-top:40px; 
 } 

 #myoptions-error{ 
     position:absolute; 
     top: -25px; 
  } 

 </style> 

 <div class="radio-group"> 
 <input type="radio" name="myoptions" value="blue" class="required"> Blue<br /> 
 <input type="radio" name="myoptions" value="red"> Red<br /> 
 <input type="radio" name="myoptions" value="green"> Green </div>
 </div><!-- end radio-group -->

how to set select element as readonly ('disabled' doesnt pass select value on server)

To simplify things here's a jQuery plugin that can achieve this goal : https://github.com/haggen/readonly

  1. Include readonly.js in your project. (also needs jquery)
  2. Replace .attr('readonly', 'readonly') with .readonly() instead. That's it.

    For example, change from $(".someClass").attr('readonly', 'readonly'); to $(".someClass").readonly();.

jQuery: How to get the HTTP status code from within the $.ajax.error method?

An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.

function checkHttpStatus(url) {     
    $.ajax({
        type: "GET",
        data: {},
        url: url,
        error: function(response) {
            alert(url + " returns a " + response.status);
        }, success() {
            alert(url + " Good link");
        }
    });
}

How do I bind onchange event of a TextBox using JQuery?

You're looking for keydown/press/up

$("#inputID").keydown(function(event) {
    alert(event.keyCode);
});

or using bind $("#inputID").bind('onkeydown', ...

http://docs.jquery.com/Events

Get current rowIndex of table in jQuery

Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:

$('td').click(function(){
   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();
});

How to show Page Loading div until the page has finished loading?

This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading, then it will wait an optional extra few seconds.

  • Works with jQuery 3 (it has a new window load event)
  • No image needed but it's easy to add one
  • Change the delay for more branding or instructions
  • Only dependency is jQuery.

CSS loader code from https://projects.lukehaas.me/css-loaders

_x000D_
_x000D_
    _x000D_
$('body').append('<div style="" id="loadingDiv"><div class="loader">Loading...</div></div>');_x000D_
$(window).on('load', function(){_x000D_
  setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds._x000D_
});_x000D_
function removeLoader(){_x000D_
    $( "#loadingDiv" ).fadeOut(500, function() {_x000D_
      // fadeOut complete. Remove the loading div_x000D_
      $( "#loadingDiv" ).remove(); //makes page more lightweight _x000D_
  });  _x000D_
}
_x000D_
        .loader,_x000D_
        .loader:after {_x000D_
            border-radius: 50%;_x000D_
            width: 10em;_x000D_
            height: 10em;_x000D_
        }_x000D_
        .loader {            _x000D_
            margin: 60px auto;_x000D_
            font-size: 10px;_x000D_
            position: relative;_x000D_
            text-indent: -9999em;_x000D_
            border-top: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
            border-right: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
            border-bottom: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
            border-left: 1.1em solid #ffffff;_x000D_
            -webkit-transform: translateZ(0);_x000D_
            -ms-transform: translateZ(0);_x000D_
            transform: translateZ(0);_x000D_
            -webkit-animation: load8 1.1s infinite linear;_x000D_
            animation: load8 1.1s infinite linear;_x000D_
        }_x000D_
        @-webkit-keyframes load8 {_x000D_
            0% {_x000D_
                -webkit-transform: rotate(0deg);_x000D_
                transform: rotate(0deg);_x000D_
            }_x000D_
            100% {_x000D_
                -webkit-transform: rotate(360deg);_x000D_
                transform: rotate(360deg);_x000D_
            }_x000D_
        }_x000D_
        @keyframes load8 {_x000D_
            0% {_x000D_
                -webkit-transform: rotate(0deg);_x000D_
                transform: rotate(0deg);_x000D_
            }_x000D_
            100% {_x000D_
                -webkit-transform: rotate(360deg);_x000D_
                transform: rotate(360deg);_x000D_
            }_x000D_
        }_x000D_
        #loadingDiv {_x000D_
            position:absolute;;_x000D_
            top:0;_x000D_
            left:0;_x000D_
            width:100%;_x000D_
            height:100%;_x000D_
            background-color:#000;_x000D_
        }
_x000D_
This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading._x000D_
_x000D_
  <ul>_x000D_
    <li>Works with jQuery 3, which has a new window load event</li>_x000D_
    <li>No image needed but it's easy to add one</li>_x000D_
    <li>Change the delay for branding or instructions</li>_x000D_
    <li>Only dependency is jQuery.</li>_x000D_
  </ul>_x000D_
_x000D_
Place the script below at the bottom of the body._x000D_
_x000D_
CSS loader code from https://projects.lukehaas.me/css-loaders_x000D_
_x000D_
<!-- Place the script below at the bottom of the body -->_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

$(window).width() not the same as media query

What i do ;

<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
...

and call aWidth variable anywhere afterwards.

You need to put the getWidth() up in your document body to make sure that the scrollbar width is counted, else scrollbar width of the browser subtracted from getWidth().

Show Hide div if, if statement is true

Use show/hide method as below

$("div").show();//To Show

$("div").hide();//To Hide

JQuery .each() backwards

$($("li").get().reverse()).each(function() { /* ... */ });

new Image(), how to know if image 100% loaded or not?

Use the load event:

img = new Image();

img.onload = function(){
  // image  has been loaded
};

img.src = image_url;

Also have a look at:

How to convert a Title to a URL slug in jQuery?

private string ToSeoFriendly(string title, int maxLength) {
    var match = Regex.Match(title.ToLower(), "[\\w]+");
    StringBuilder result = new StringBuilder("");
    bool maxLengthHit = false;
    while (match.Success && !maxLengthHit) {
        if (result.Length + match.Value.Length <= maxLength) {
            result.Append(match.Value + "-");
        } else {
            maxLengthHit = true;
            // Handle a situation where there is only one word and it is greater than the max length.
            if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
        }
        match = match.NextMatch();
    }
    // Remove trailing '-'
    if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
    return result.ToString();
}

jQuery if Element has an ID?

Simple way:

Fox example this is your html,

<div class='classname' id='your_id_name'>
</div>

Jquery code:

if($('.classname').prop('id')=='your_id_name')
{
    //works your_id_name exist (true part)
}
else
{ 
    //works your_id_name not exist (false part)
}

:touch CSS pseudo-class or something similar?

Since mobile doesn't give hover feedback, I want, as a user, to see instant feedback when a link is tapped. I noticed that -webkit-tap-highlight-color is the fastest to respond (subjective).

Add the following to your body and your links will have a tap effect.

body {
    -webkit-tap-highlight-color: #ccc;
}

How to get screen width without (minus) scrollbar?

None of these solutions worked for me, however I was able to fix it by taking the width and subtracting the width of the scroll bar. I'm not sure how cross-browser compatible this is.

How to set top position using jquery

Just for reference, if you are using:

 $(el).offset().top 

To get the position, it can be affected by the position of the parent element. Thus you may want to be consistent and use the following to set it:

$(el).offset({top: pos});

As opposed to the CSS methods above.

How to check if input file is empty in jQuery

Here is the jQuery version of it:

if ($('#videoUploadFile').get(0).files.length === 0) {
    console.log("No files selected.");
}

jQuery Select first and second td

You can just pick the next td:

$(".location table tbody tr td:first-child").next("td").addClass("black");

Only on Firefox "Loading failed for the <script> with source"

As suggested above, this could possibly be an issue with your browser extensions. Disable all of your extensions including Adblock, and then try again as the code is loading fine in my browser right now (Google Chrome - latest) so it's probably an issue on your end. Also, have you tried a different browser like shudders IE if you have it? Adblock is known to conflict with domain names with track and market in them as a blanket rule. Try using private browsing mode or safe mode.

iFrame src change event detection?

Answer based on JQuery < 3

$('#iframeid').load(function(){
    alert('frame has (re)loaded');
});

As mentioned by subharb, as from JQuery 3.0 this needs to be changed to:

$('#iframe').on('load', function() {
    alert('frame has (re)loaded ');
});

https://jquery.com/upgrade-guide/3.0/#breaking-change-load-unload-and-error-removed

Getting the source of a specific image element with jQuery

If you do not specifically need the alt text of an image, then you can just target the class/id of the image.

$('img.propImg').each(function(){ 
     enter code here
}

I know it’s not quite answering the question, though I’d spent ages trying to figure this out and this question gave me the solution :). In my case I needed to hide any image tags with a specific src.

$('img.propImg').each(function(){ //for each loop that gets all the images. 
        if($(this).attr('src') == "img/{{images}}") { // if the src matches this
        $(this).css("display", "none") // hide the image.
    }
});

jQuery - how can I find the element with a certain id?

If you're trying to find an element by id, you don't need to search the table only - it should be unique on the page, and so you should be able to use:

var verificaHorario = $('#' + horaInicial);

If you need to search only in the table for whatever reason, you can use:

var verificaHorario = $("#tbIntervalos").find("td#" + horaInicial)

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Try the following way:

<input type="submit" value="Search" class="search-btn" />
<a href="javascript:;" onclick="$('.search-btn').click();">Go</a>

Convert UTC date time to local date time

Use this for UTC and Local time convert and vice versa.

//Covert datetime by GMT offset 
//If toUTC is true then return UTC time other wise return local time
function convertLocalDateToUTCDate(date, toUTC) {
    date = new Date(date);
    //Local time converted to UTC
    console.log("Time: " + date);
    var localOffset = date.getTimezoneOffset() * 60000;
    var localTime = date.getTime();
    if (toUTC) {
        date = localTime + localOffset;
    } else {
        date = localTime - localOffset;
    }
    date = new Date(date);
    console.log("Converted time: " + date);
    return date;
}

How to create a toggle button in Bootstrap

Initial answer from 2013

An excellent (unofficial) Bootstrap Switch is available.

Classic 2013 Switch

<input type="checkbox" name="my-checkbox" checked>
$("[name='my-checkbox']").bootstrapSwitch();

It uses radio types or checkboxes as switches. A type attribute has been added since V.1.8.

Source code is available on Github.

Note from 2018

I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.

Please consider having a look at modern Switches like this one from the React Component framework (not Bootstrap related, but can be integrated in Bootstrap grid and UI though).

Other implementations exist for Angular, View or jQuery.

Modern 2018 Switch

import '../assets/index.less'
import React from 'react'
import ReactDOM from 'react-dom'
import Switch from 'rc-switch'

class Switcher extends React.Component {
  state = {
    disabled: false,
  }

  toggle = () => {
    this.setState({
      disabled: !this.state.disabled,
    })
  }

  render() {
    return (
      <div style={{ margin: 20 }}>
        <Switch
          disabled={this.state.disabled}
          checkedChildren={'?'}
          unCheckedChildren={'?'}
        />
        </div>
      </div>
    )
  }
}

ReactDOM.render(<Switcher />, document.getElementById('__react-content'))

Native Bootstrap Switches

See ohkts11's answer below about the native Bootstrap switches.

How can I run a directive after the dom has finished rendering?

If you can't use $timeout due to external resources and cant use a directive due to a specific issue with timing, use broadcast.

Add $scope.$broadcast("variable_name_here"); after the desired external resource or long running controller/directive has completed.

Then add the below after your external resource has loaded.

$scope.$on("variable_name_here", function(){ 
   // DOM manipulation here
   jQuery('selector').height(); 
}

For example in the promise of a deferred HTTP request.

MyHttpService.then(function(data){
   $scope.MyHttpReturnedImage = data.image;
   $scope.$broadcast("imageLoaded");
});

$scope.$on("imageLoaded", function(){ 
   jQuery('img').height(80).width(80); 
}

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

Jquery: Find Text and replace

try this,

$('#id1').html($('#id1').html().replace('dogsss','dollsss'));

working sample

jQuery: Check if div with certain class name exists

if ($(".mydivclass").size()){
   // code here
}

The size() method just returns the number of elements that the jQuery selector selects - in this case the number of elements with the class mydivclass. If it returns 0, the expression is false, and therefore there are none, and if it returns any other number, the divs must exist.

Using jQuery to test if an input has focus

April 2015 Update

Since this question has been around a while, and some new conventions have come into play, I feel that I should mention the .live method has been depreciated.

In its place, the .on method has now been introduced.

Their documentation is quite useful in explaining how it works;

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live().

So, in order for you to target the 'input focused' event, you can use this in a script. Something like:

$('input').on("focus", function(){
   //do some stuff
});

This is quite robust and even allows you to use the TAB key as well.

Jquery : Refresh/Reload the page on clicking a button

simple way can be -

just href="javascript:location.reload(true);

your answer is

location.reload(true);

Thanks

Use basic authentication with jQuery and Ajax

Or, simply use the headers property introduced in 1.5:

headers: {"Authorization": "Basic xxxx"}

Reference: jQuery Ajax API

How to get to Model or Viewbag Variables in a Script Tag

try this method

<script type="text/javascript">

    function set(value) {
        return value;
    }

    alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
    alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));

</script>

Thanks

Get value of multiselect box using jQuery or pure JS

I think the answer may be easier to understand like this:

_x000D_
_x000D_
$('#empid').on('change',function() {_x000D_
  alert($(this).val());_x000D_
  console.log($(this).val());_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>_x000D_
<select id="empid" name="empname" multiple="multiple">_x000D_
  <option value="0">Potato</option>_x000D_
  <option value="1">Carrot</option>_x000D_
  <option value="2">Apple</option>_x000D_
  <option value="3">Raisins</option>_x000D_
  <option value="4">Peanut</option>_x000D_
</select>_x000D_
<br />_x000D_
Hold CTRL / CMD for selecting multiple fields
_x000D_
_x000D_
_x000D_

If you select "Carrot" and "Raisins" in the list, the output will be "1,3".

How to send JSON instead of a query string with $.ajax?

If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"

Original post here

Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

You could use prop as well. Check the following code below.

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").prop("readonly", false); 
     }
     else{ 
         $("#no_of_staff").prop("readonly", true); 
     }
   });
});

How can I get the current directory name in Javascript?

This one-liner works:

var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

jquery 3.0 url.indexOf error

Jquery 3.0 has some breaking changes that remove certain methods due to conflicts. Your error is most likely due to one of these changes such as the removal of the .load() event.

Read more in the jQuery Core 3.0 Upgrade Guide

To fix this you either need to rewrite the code to be compatible with Jquery 3.0 or else you can use the JQuery Migrate plugin which restores the deprecated and/or removed APIs and behaviours.

Parsing JSON objects for HTML table

Make a HTML Table from a JSON array of Objects by extending $ as shown below

$.makeTable = function (mydata) {
            var table = $('<table border=1>');
            var tblHeader = "<tr>";
            for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
            tblHeader += "</tr>";
            $(tblHeader).appendTo(table);
            $.each(mydata, function (index, value) {
                var TableRow = "<tr>";
                $.each(value, function (key, val) {
                    TableRow += "<td>" + val + "</td>";
                });
                TableRow += "</tr>";
                $(table).append(TableRow);
            });
            return ($(table));
        };

and use as follows:

var mydata = eval(jdata);
var table = $.makeTable(mydata);
$(table).appendTo("#TableCont");

where TableCont is some div

Datatables warning(table id = 'example'): cannot reinitialise data table

You have to destroy the datatable and empty the table body before binding DataTable by doing this below,

function Create() {
if ($.fn.DataTable.isDataTable('#dataTable')) {
    $('#dataTable').DataTable().destroy();
}
$('#dataTable tbody').empty();
//Here call the Datatable Bind function;} 

How to set value of input text using jQuery

this is for classes

$('.nameofdiv').val('we are developers');

for ids

$('#nameofdiv').val('we are developers');

now if u have an iput in a form u can use

$("#form li.name input.name_val").val('we are awsome developers');

Jquery: how to trigger click event on pressing enter key

Are you trying to mimic a click on a button when the enter key is pressed? If so you may need to use the trigger syntax.

Try changing

$('input[name = butAssignProd]').click();

to

$('input[name = butAssignProd]').trigger("click");

If this isn't the problem then try taking a second look at your key capture syntax by looking at the solutions in this post: jQuery Event Keypress: Which key was pressed?

jQuery AJAX submit form

You may use this on submit function like below.

HTML Form

<form class="form" action="" method="post">
    <input type="text" name="name" id="name" >
    <textarea name="text" id="message" placeholder="Write something to us"> </textarea>
    <input type="button" onclick="return formSubmit();" value="Send">
</form>

jQuery function:

<script>
    function formSubmit(){
        var name = document.getElementById("name").value;
        var message = document.getElementById("message").value;
        var dataString = 'name='+ name + '&message=' + message;
        jQuery.ajax({
            url: "submit.php",
            data: dataString,
            type: "POST",
            success: function(data){
                $("#myForm").html(data);
            },
            error: function (){}
        });
    return true;
    }
</script>

For more details and sample Visit: http://www.spiderscode.com/simple-ajax-contact-form/

How do I fire an event when a iframe has finished loading in jQuery?

Have you tried:

$("#iFrameId").on("load", function () {
    // do something once the iframe is loaded
});

How to define the css :hover state in a jQuery selector?

I know this has an accepted answer but if anyone comes upon this, my solution may help.

I found this question because I have a use-case where I wanted to turn off the :hover state for elements individually. Since there is no way to do this in the DOM, another good way to do it is to define a class in CSS that overrides the hover state.

For instance, the css:

.nohover:hover {
    color: black !important;
}

Then with jQuery:

$("#elm").addClass("nohover");

With this method, you can override as many DOM elements as you would like without binding tons of onHover events.

How to get hex color value rather than RGB value?

Here is a version that also checks for transparent, I needed this since my object was to insert the result into a style attribute, where the transparent version of a hex color is actually the word "transparent"..

function rgb2hex(rgb) {
     if (  rgb.search("rgb") == -1 ) {
          return rgb;
     }
     else if ( rgb == 'rgba(0, 0, 0, 0)' ) {
         return 'transparent';
     }
     else {
          rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
          function hex(x) {
               return ("0" + parseInt(x).toString(16)).slice(-2);
          }
          return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
     }
}

Permutations between two lists of unequal length

The simplest way is to use itertools.product:

a = ["foo", "melon"]
b = [True, False]
c = list(itertools.product(a, b))
>> [("foo", True), ("foo", False), ("melon", True), ("melon", False)]

No Main class found in NetBeans

I also experienced Netbeans complaining to me about "No main classes found". The issue was on a project I knew worked in the past, but failed when I tried it on another pc.

My specific failure reasons probably differ from the OP, but I'll still share what I learnt on the debugging journey, in-case these insights help anybody figure out their own unique issues relating to this topic.

What I learnt is that upon starting NetBeans, it should perform a step called "Scanning projects..." Scanning projects...

Prior to this phase, you should notice that any .java file you have with a main() method within it will show up in the 'Projects' pane with its icon looking like this (no arrow):

icon before scanning

After this scanning phase finishes, if a main() method was discovered within the file, that file's icon will change to this (with arrow):

icon after scanning

So on my system, it appeared this "Scanning projects..." step was failing, and instead would be stuck on an "Opening Projects" step.

I also noticed a little red icon in the bottom-right corner which hinted at the issue ailing me:

Unexpected exception

Unexpected Exception
java.lang.ExceptionInInitializerError

Clicking on that link showed me more details of the error:

java.security.NoSuchAlgorithmException: MD5 MessageDigest not available
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
    at java.security.Security.getImpl(Security.java:695)
    at java.security.MessageDigest.getInstance(MessageDigest.java:167)
    at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:113)
Caused: java.lang.RuntimeException
    at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:115)
Caused: java.lang.ExceptionInInitializerError
    at org.netbeans.modules.parsing.lucene.LuceneIndex$DirCache.createFSDirectory(LuceneIndex.java:839)

That mention of "java.security" reminded me that I had fiddled with this machine's "java.security" file (to be specific, I was performing Salvador Valencia's steps from this thread, but did it incorrectly and broke "java.security" in the process :))

Once I repaired the damage I caused to my "java.security" file, NetBeans' "Scanning projects..." step started to work again, the little green arrows appeared on my files once more and I no longer got that "No main classes found" issue.

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

Edit line thickness of CSS 'underline' attribute

The background-image can also be used to create an underline. This method handles line breaks.

It has to be shifted down via background-position and repeated horizontally. The line width can be adjusted to some degree using background-size (the background is limited to the content box of the element).

_x000D_
_x000D_
.underline
{
    --color: green;
    font-size: 40px;
    background-image: linear-gradient(var(--color) 0%, var(--color) 100%);
    background-repeat: repeat-x;
    background-position: 0 1.05em;
    background-size: 2px 5px;
}
_x000D_
<span class="underline">
     Underlined<br/>
     Text
</span>
_x000D_
_x000D_
_x000D_

Can I append an array to 'formdata' in javascript?

Simply you can do like this:

var formData = new FormData();
formData.append('array[key1]', this.array.key1);
formData.append('array[key2]', this.array.key2);

How to break lines in PowerShell?

I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)

Thanks!

Selecting element by data attribute with jQuery

I haven't seen a JavaScript answer without jQuery. Hopefully it helps someone.

_x000D_
_x000D_
var elements = document.querySelectorAll('[data-customerID="22"]');_x000D_
_x000D_
elements[0].innerHTML = 'it worked!';
_x000D_
<a data-customerID='22'>test</a>
_x000D_
_x000D_
_x000D_

Info:

Sorting Values of Set

Use a SortedSet (TreeSet is the default one):

SortedSet<String> set=new TreeSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=new ArrayList<String>(set);

No extra sorting code needed.

Oh, I see you want a different sort order. Supply a Comparator to the TreeSet:

new TreeSet<String>(Comparator.comparing(Integer::valueOf));

Now your TreeSet will sort Strings in numeric order (which implies that it will throw exceptions if you supply non-numeric strings)

Reference:

PHP: Show yes/no confirmation dialog

Try this:

<td>
    <a onclick="return confirm(\'Are you sure?\');" href="'.base_url('category/delete_category/'.$row->category_id).'" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i> Delete Coupon</a>
</td>

Font scaling based on width of container

My own solution, jQuery-based, works by gradually increasing the font size until the container gets a big increase in height (meaning it got a line break).

It's pretty simple, but works fairly well, and it is very easy to use. You don't have to know anything about the font being used, everything is taken care of by the browser.

You can play with it on http://jsfiddle.net/tubededentifrice/u5y15d0L/2/

The magic happens here:

var setMaxTextSize=function(jElement) {
    // Get and set the font size into data for reuse upon resize
    var fontSize=parseInt(jElement.data(quickFitFontSizeData)) || parseInt(jElement.css("font-size"));
    jElement.data(quickFitFontSizeData, fontSize);

    // Gradually increase font size until the element gets a big increase in height (i.e. line break)
    var i = 0;
    var previousHeight;
    do
    {
        previousHeight=jElement.height();
        jElement.css("font-size", "" + (++fontSize) + "px");
    }
    while(i++ < 300 && jElement.height()-previousHeight < fontSize/2)

    // Finally, go back before the increase in height and set the element as resized by adding quickFitSetClass
    fontSize -= 1;
    jElement.addClass(quickFitSetClass).css("font-size", "" + fontSize + "px");

    return fontSize;
};

How does the vim "write with sudo" trick work?

In :w !sudo tee %...

% means "the current file"

As eugene y pointed out, % does indeed mean "the current file name", which is passed to tee so that it knows which file to overwrite.

(In substitution commands, it's slightly different; as :help :% shows, it's equal to 1,$ (the entire file) (thanks to @Orafu for pointing out that this does not evaluate to the filename). For example, :%s/foo/bar means "in the current file, replace occurrences of foo with bar." If you highlight some text before typing :s, you'll see that the highlighted lines take the place of % as your substitution range.)

:w isn't updating your file

One confusing part of this trick is that you might think :w is modifying your file, but it isn't. If you opened and modified file1.txt, then ran :w file2.txt, it would be a "save as"; file1.txt wouldn't be modified, but the current buffer contents would be sent to file2.txt.

Instead of file2.txt, you can substitute a shell command to receive the buffer contents. For instance, :w !cat will just display the contents.

If Vim wasn't run with sudo access, its :w can't modify a protected file, but if it passes the buffer contents to the shell, a command in the shell can be run with sudo. In this case, we use tee.

Understanding tee

As for tee, picture the tee command as a T-shaped pipe in a normal bash piping situation: it directs output to specified file(s) and also sends it to standard output, which can be captured by the next piped command.

For example, in ps -ax | tee processes.txt | grep 'foo', the list of processes will be written to a text file and passed along to grep.

     +-----------+    tee     +------------+
     |           |  --------  |            |
     | ps -ax    |  --------  | grep 'foo' |
     |           |     ||     |            |
     +-----------+     ||     +------------+
                       ||   
               +---------------+
               |               |
               | processes.txt |
               |               |
               +---------------+

(Diagram created with Asciiflow.)

See the tee man page for more info.

Tee as a hack

In the situation your question describes, using tee is a hack because we're ignoring half of what it does. sudo tee writes to our file and also sends the buffer contents to standard output, but we ignore standard output. We don't need to pass anything to another piped command in this case; we're just using tee as an alternate way of writing a file and so that we can call it with sudo.

Making this trick easy

You can add this to your .vimrc to make this trick easy-to-use: just type :w!!.

" Allow saving of files as sudo when I forgot to start vim using sudo.
cmap w!! w !sudo tee > /dev/null %

The > /dev/null part explicitly throws away the standard output, since, as I said, we don't need to pass anything to another piped command.

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Sorting JSON by values

jQuery.fn.sort = function() {  
    return this.pushStack( [].sort.apply( this, arguments ), []);  
};  

 function sortLastName(a,b){  
     if (a.l_name == b.l_name){
       return 0;
     }
     return a.l_name> b.l_name ? 1 : -1;  
 };  
  function sortLastNameDesc(a,b){  
     return sortLastName(a,b) * -1;  
 };
var people= [
{
"f_name": "john",
"l_name": "doe",
"sequence": "0",
"title" : "president",
"url" : "google.com",
"color" : "333333",
},
{
"f_name": "michael",
"l_name": "goodyear",
"sequence": "0",
"title" : "general manager",
"url" : "google.com",
"color" : "333333",
}]

sorted=$(people).sort(sortLastNameDesc);  

How do I record audio on iPhone with AVAudioRecorder?

Although this is an answered question (and kind of old) i have decided to post my full working code for others that found it hard to find good working (out of the box) playing and recording example - including encoded, pcm, play via speaker, write to file here it is:

AudioPlayerViewController.h:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface AudioPlayerViewController : UIViewController {
AVAudioPlayer *audioPlayer;
AVAudioRecorder *audioRecorder;
int recordEncoding;
enum
{
    ENC_AAC = 1,
    ENC_ALAC = 2,
    ENC_IMA4 = 3,
    ENC_ILBC = 4,
    ENC_ULAW = 5,
    ENC_PCM = 6,
} encodingTypes;
}

-(IBAction) startRecording;
-(IBAction) stopRecording;
-(IBAction) playRecording;
-(IBAction) stopPlaying;

@end

AudioPlayerViewController.m:

#import "AudioPlayerViewController.h"

@implementation AudioPlayerViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    recordEncoding = ENC_AAC;
}

-(IBAction) startRecording
{
NSLog(@"startRecording");
[audioRecorder release];
audioRecorder = nil;

// Init audio with record capability
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];

NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10];
if(recordEncoding == ENC_PCM)
{
    [recordSettings setObject:[NSNumber numberWithInt: kAudioFormatLinearPCM] forKey: AVFormatIDKey];
    [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey];
    [recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
    [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];   
}
else
{
    NSNumber *formatObject;

    switch (recordEncoding) {
        case (ENC_AAC): 
            formatObject = [NSNumber numberWithInt: kAudioFormatMPEG4AAC];
            break;
        case (ENC_ALAC):
            formatObject = [NSNumber numberWithInt: kAudioFormatAppleLossless];
            break;
        case (ENC_IMA4):
            formatObject = [NSNumber numberWithInt: kAudioFormatAppleIMA4];
            break;
        case (ENC_ILBC):
            formatObject = [NSNumber numberWithInt: kAudioFormatiLBC];
            break;
        case (ENC_ULAW):
            formatObject = [NSNumber numberWithInt: kAudioFormatULaw];
            break;
        default:
            formatObject = [NSNumber numberWithInt: kAudioFormatAppleIMA4];
    }

    [recordSettings setObject:formatObject forKey: AVFormatIDKey];
    [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey];
    [recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
    [recordSettings setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];
    [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [recordSettings setObject:[NSNumber numberWithInt: AVAudioQualityHigh] forKey: AVEncoderAudioQualityKey];
}

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", [[NSBundle mainBundle] resourcePath]]];


NSError *error = nil;
audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];

if ([audioRecorder prepareToRecord] == YES){
    [audioRecorder record];
}else {
    int errorCode = CFSwapInt32HostToBig ([error code]); 
    NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode); 

}
NSLog(@"recording");
}

-(IBAction) stopRecording
{
NSLog(@"stopRecording");
[audioRecorder stop];
NSLog(@"stopped");
}

-(IBAction) playRecording
{
NSLog(@"playRecording");
// Init audio with playback capability
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
[audioPlayer play];
NSLog(@"playing");
}

-(IBAction) stopPlaying
{
NSLog(@"stopPlaying");
[audioPlayer stop];
NSLog(@"stopped");
}

- (void)dealloc
{
[audioPlayer release];
[audioRecorder release];
[super dealloc];
}

@end

Hope this will help some of you guys.

Simple jQuery, PHP and JSONP example?

When you use $.getJSON on an external domain it automatically actions a JSONP request, for example my tweet slider here

If you look at the source code you can see that I am calling the Twitter API using .getJSON.

So your example would be: THIS IS TESTED AND WORKS (You can go to http://smallcoders.com/javascriptdevenvironment.html to see it in action)

//JAVASCRIPT

$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?','firstname=Jeff',function(res){
    alert('Your name is '+res.fullname);
});

//SERVER SIDE
  <?php
 $fname = $_GET['firstname'];
      if($fname=='Jeff')
      {
          //header("Content-Type: application/json");
         echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

      }
?>

Note the ?callback=? and +res.fullname

Can you recommend a free light-weight MySQL GUI for Linux?

Why not try MySQL GUI Tools? It's light, and does its job well.

How do I remove the space between inline/inline-block elements?

There is a easy solution in CSS. For example:

HTML

<p class="parent">
    <span class="children"> Foo </span>
    <span class="children"> Bar </span>
</p>

CSS

.parent {
    letter-spacing: -.31em;
    *letter-spacing: normal;
    *word-spacing: -.43em;
}
.children {
    display: inline-block;
    *display: inline;
    zoom: 1;
    letter-spacing: normal;
    word-spacing: normal;
}

In my opinion writing font-size: 0 is not safe when you use it in a project like em, so I prefer purecss' solution.

You can check this framework in this link purecss. Enjoy :)

_x000D_
_x000D_
.row {_x000D_
    letter-spacing: -.31em;_x000D_
    *letter-spacing: normal;_x000D_
    *word-spacing: -.43em;_x000D_
_x000D_
    /* For better view */_x000D_
    background: #f9f9f9;_x000D_
    padding: 1em .5em;_x000D_
}_x000D_
_x000D_
.col {_x000D_
    display: inline-block;_x000D_
    *display: inline;_x000D_
    zoom: 1;_x000D_
    letter-spacing: normal;_x000D_
    word-spacing: normal;_x000D_
_x000D_
    /* For better view */_x000D_
    padding: 16px;_x000D_
    background: #dbdbdb;_x000D_
    border: 3px #bdbdbd solid;_x000D_
    box-sizing: border-box;_x000D_
    width: 25%;_x000D_
}
_x000D_
<div class="row">_x000D_
_x000D_
    <div class="col">1</div>_x000D_
    <div class="col">2</div>_x000D_
    <div class="col">3</div>_x000D_
    <div class="col">4</div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Explain the concept of a stack frame in a nutshell

Stack frame is the packed information related to a function call. This information generally includes arguments passed to th function, local variables and where to return upon terminating. Activation record is another name for a stack frame. The layout of the stack frame is determined in the ABI by the manufacturer and every compiler supporting the ISA must conform to this standard, however layout scheme can be compiler dependent. Generally stack frame size is not limited but there is a concept called "red/protected zone" to allow system calls...etc to execute without interfering with a stack frame.

There is always a SP but on some ABIs (ARM's and PowerPC's for example) FP is optional. Arguments that needed to be placed onto the stack can be offsetted using the SP only. Whether a stack frame is generated for a function call or not depends on the type and number of arguments, local variables and how local variables are accessed generally. On most ISAs, first, registers are used and if there are more arguments than registers dedicated to pass arguments these are placed onto the stack (For example x86 ABI has 6 registers to pass integer arguments). Hence, sometimes, some functions do not need a stack frame to be placed on the stack, just the return address is pushed onto the stack.

SQL update statement in C#

Please, never use this concat form:

String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
        + "WHERE supplier_id = " + textBox1.Text;

use:

command.Parameters.AddWithValue("@attribute", value);

Always work object oriented

Edit: This is because when you parameterize your updates it helps prevent SQL injection.

.Net: How do I find the .NET version?

Before going to a command prompt, please follow these steps...

Open My Computer ? double click "C:" drive ? double click "Windows" ? double click "Microsoft.NET" ? double click "Framework" ? Inside this folder, there will be folder(s) like "v1.0.3705" and/or "v2.0.50727" and/or "v3.5" and/or "v4.0.30319".

Your latest .NET version would be in the highest v number folder, so if v4.0.30319 is available that would hold your latest .NET framework. However, the v4.0.30319 does not mean that you have the .NET framework version 4.0. The v4.0.30319 is your Visual C# compiler version, therefore, in order to find the .NET framework version do the following.

Go to a command prompt and follow this path:

C:\Windows\Microsoft.NET\Framework\v4.0.30319 (or whatever the highest v number folder)

C:\Windows\Microsoft.NET\Framework\v4.0.30319 > csc.exe

Output:

Microsoft (R) Visual C# Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 Copyright (C) Microsoft Corporation. All rights reserved.

Example below:

Enter image description here

Oracle JDBC ojdbc6 Jar as a Maven Dependency

The correct answer was supplied by Raghuram in the comments section to my original question.

For whatever reason, pointing "mvn install" to a full path of the physical ojdbc6.jar file didn't work for me. (Or I consistently repeatedly flubbed it up when running the command, but no errors were issued.)

cd-ing into the directory where I keep ojdb6.jar and running the command from there worked the first time.

If Raghuram would like to answer this question, I'll accept his answer instead. Thanks everyone!

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

How do I get the list of keys in a Dictionary?

You should be able to just look at .Keys:

    Dictionary<string, int> data = new Dictionary<string, int>();
    data.Add("abc", 123);
    data.Add("def", 456);
    foreach (string key in data.Keys)
    {
        Console.WriteLine(key);
    }

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);

  private void SumOFEPFWages(GridView grd)
    {
        Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
        /*Sum of the total Amount of the day*/
        foreach (GridViewRow gvr in grd.Rows)
        {
            Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
            lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
        }

    }

How to capture a list of specific type with mockito

Based on @tenshi's and @pkalinow's comments (also kudos to @rogerdpack), the following is a simple solution for creating a list argument captor that also disables the "uses unchecked or unsafe operations" warning:

@SuppressWarnings("unchecked")
final ArgumentCaptor<List<SomeType>> someTypeListArgumentCaptor =
    ArgumentCaptor.forClass(List.class);

Full example here and corresponding passing CI build and test run here.

Our team has been using this for some time in our unit tests and this looks like the most straightforward solution for us.

SOAP request to WebService with java

When the WSDL is available, it is just two steps you need to follow to invoke that web service.

Step 1: Generate the client side source from a WSDL2Java tool

Step 2: Invoke the operation using:

YourService service = new YourServiceLocator();
Stub stub = service.getYourStub();
stub.operation();

If you look further, you will notice that the Stub class is used to invoke the service deployed at the remote location as a web service. When invoking that, your client actually generates the SOAP request and communicates. Similarly the web service sends the response as a SOAP. With the help of a tool like Wireshark, you can view the SOAP messages exchanged.

However since you have requested more explanation on the basics, I recommend you to refer here and write a web service with it's client to learn it further.

Fix footer to bottom of page

I've found the sticky footer solution a bit painful on responsive sites, given that the height of your nav and footer can differ depending on the device. If you only care about working on modern browsers, you can accomplish your goal using a bit of Javascript.

If this is your HTML:

<div class="nav">
</div>
<div class="wrapper">
</div>
<div class="footer">
</div>

Then use this JQuery on every page:

$(function(){

  /* Sets the minimum height of the wrapper div to ensure the footer reaches the bottom */
  function setWrapperMinHeight() {
    $('.wrapper').css('minHeight', window.innerHeight - $('.nav').height() - $('.footer').height());
  }
  /* Make sure the main div gets resized on ready */
  setWrapperMinHeight();

  /* Make sure the wrapper div gets resized whenever the screen gets resized */
  window.onresize = function() {
    setWrapperMinHeight();
  }
});

set the width of select2 input (through Angular-ui directive)

This is an old question but new info is still worth posting...

Starting with Select2 version 3.4.0 there is an attribute dropdownAutoWidth which solves the problem and handles all the odd cases. Note it is not on by default. It resizes dynamically as the user makes selections, it adds width for allowClear if that attribute is used, and it handles placeholder text properly too.

$("#some_select_id").select2({
    dropdownAutoWidth : true
});

VBA using ubound on a multidimensional array

ubound(arr, 1) 

and

ubound(arr, 2) 

How do I dynamically change the content in an iframe using jquery?

If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src attribute.

 $("#myiframe").attr("src", "newwebpage.html");

How to see the values of a table variable at debug time in T-SQL?

SQL Server Profiler 2014 lists the content of table value parameter. Might work in previous versions too. Enable SP:Starting or RPC:Completed event in Stored Procedures group and TextData column and when you click on entry in log you'll have the insert statements for table variable. You can then copy the text and run in Management Studio.

Sample output:

declare @p1 dbo.TableType
insert into @p1 values(N'A',N'B')
insert into @p1 values(N'C',N'D')

exec uspWhatever @PARAM=@p1

html select option SELECTED

foreach ($array as $value => $name) {
     echo '<option value="' . htmlentities($value) . '"' . (($_GET['sel'] === $value) ? ' selected="selected"') . '>' . htmlentities($name) . '</option>';
}

This is fairly neat, and, I think, self-explanatory.

How to prevent page scrolling when scrolling a DIV element?

Pure javascript version of Vidas's answer, el$ is the DOM node of the plane you are scrolling.

function onlyScrollElement(event, el$) {
    var delta = event.wheelDelta || -event.detail;
    el$.scrollTop += (delta < 0 ? 1 : -1) * 10;
    event.preventDefault();
}

Make sure you dont attach the even multiple times! Here is an example,

var ul$ = document.getElementById('yo-list');
// IE9, Chrome, Safari, Opera
ul$.removeEventListener('mousewheel', onlyScrollElement);
ul$.addEventListener('mousewheel', onlyScrollElement);
// Firefox
ul$.removeEventListener('DOMMouseScroll', onlyScrollElement);
ul$.addEventListener('DOMMouseScroll', onlyScrollElement);

Word of caution, the function there needs to be a constant, if you reinitialize the function each time before attaching it, ie. var func = function (...) the removeEventListener will not work.

Using Alert in Response.Write Function in ASP.NET

You can simply write

try
 {
    //Your Logic and code
 }
 catch (Exception ex)
 {
    //Error message in  alert box
    Response.Write("<script>alert('Error :" +ex.Message+"');</script>");
 }

it will work fine

Get Number of Rows returned by ResultSet in Java

If your query is something like this SELECT Count(*) FROM tranbook, then do this rs.next(); System.out.println(rs.getInt("Count(*)"));

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

This is a simple way from XML only

spanCount for number of columns

layoutManager for making it grid or linear(Vertical or Horizontal)

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/personListRecyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

various option are available such as:

 Double d= 123.12;
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64); // b = 123.1200000
b = b.setScale(2, BigDecimal.ROUND_HALF_UP);  // b = 123.12

BigDecimal b1 =new BigDecimal(collectionFileData.getAmount(), MathContext.DECIMAL64).setScale(2, BigDecimal.ROUND_HALF_UP)  // b1= 123.12

 d = (double) Math.round(d * 100) / 100;
BigDecimal b2 = new BigDecimal(d.toString());  // b2= 123.12



Use chrome as browser in C#?

OpenWebKitSharp gives you full control over WebKit Nightly, which is very close to webkit in terms of performance and compatibility. Chrome uses WebKit Chromium engine, while WebKit.NET uses Cairo and OpenWebKitSharp Nightly. Chromium should be the best of these builds, while at 2nd place should come Nightly and that's why I suggest OpenWebKitSharp.

http://gt-web-software.webs.com/libraries.htm at the OpenWebKitSharp section

How to set the Android progressbar's height?

android:scaleY="8" in your xml file

Form Submit Execute JavaScript Best Practice?

I know it's a little late for this. But I always thought that the best way to create event listeners is directly from JavaScript. Kind of like not applying inline CSS styles.

function validate(){
    //do stuff
}
function init(){
    document.getElementById('form').onsubmit = validate;
}
window.onload = init;

That way you don't have a bunch of event listeners throughout your HTML.

Push existing project into Github

Create a new repository

git clone <url>
cd "repositoryName"
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master

Existing folder

cd existing_folder
git init
git remote add origin <url>
git add .
git commit -m "Initial commit"
git push -u origin master

Existing Git repository

cd existing_repo
git remote rename origin old-origin
git remote add origin <url>
git push -u origin --all
git push -u origin --tags

What's the difference between UTF-8 and UTF-8 without BOM?

The Unicode Byte Order Mark (BOM) FAQ provides a concise answer:

Q: How I should deal with BOMs?

A: Here are some guidelines to follow:

  1. A particular protocol (e.g. Microsoft conventions for .txt files) may require use of the BOM on certain Unicode data streams, such as files. When you need to conform to such a protocol, use a BOM.

  2. Some protocols allow optional BOMs in the case of untagged text. In those cases,

    • Where a text data stream is known to be plain text, but of unknown encoding, BOM can be used as a signature. If there is no BOM, the encoding could be anything.

    • Where a text data stream is known to be plain Unicode text (but not which endian), then BOM can be used as a signature. If there is no BOM, the text should be interpreted as big-endian.

  3. Some byte oriented protocols expect ASCII characters at the beginning of a file. If UTF-8 is used with these protocols, use of the BOM as encoding form signature should be avoided.

  4. Where the precise type of the data stream is known (e.g. Unicode big-endian or Unicode little-endian), the BOM should not be used. In particular, whenever a data stream is declared to be UTF-16BE, UTF-16LE, UTF-32BE or UTF-32LE a BOM must not be used.

Create a List of primitive int?

When you use Java for Android development, it is recommended to use SparseIntArray to prevent autoboxing between int and Integer.

You can finde more information to SparseIntArray in the Android Developers documentation and a good explanation for autoboxing on Android enter link description here

What are the best use cases for Akka framework

I have used it so far in two real projects very successfully. both are in the near real-time traffic information field (traffic as in cars on highways), distributed over several nodes, integrating messages between several parties, reliable backend systems. I'm not at liberty to give specifics on clients yet, when I do get the OK maybe it can be added as a reference.

Akka has really pulled through on those projects, even though we started when it was on version 0.7. (we are using scala by the way)

One of the big advantages is the ease at which you can compose a system out of actors and messages with almost no boilerplating, it scales extremely well without all the complexities of hand-rolled threading and you get asynchronous message passing between objects almost for free.

It is very good in modeling any type of asynchronous message handling. I would prefer to write any type of (web) services system in this style than any other style. (Have you ever tried to write an asynchronous web service (server side) with JAX-WS? that's a lot of plumbing). So I would say any system that does not want to hang on one of its components because everything is implicitly called using synchronous methods, and that one component is locking on something. It is very stable and the let-it-crash + supervisor solution to failure really works well. Everything is easy to setup programmatically and not hard to unit test.

Then there are the excellent add-on modules. The Camel module really plugs in well into Akka and enables such easy development of asynchronous services with configurable endpoints.

I'm very happy with the framework and it is becoming a defacto standard for the connected systems that we build.

How do I remove an item from a stl vector with a certain value?

Use the global method std::remove with the begin and end iterator, and then use std::vector.erase to actually remove the elements.

Documentation links
std::remove http://www.cppreference.com/cppalgorithm/remove.html
std::vector.erase http://www.cppreference.com/cppvector/erase.html

std::vector<int> v;
v.push_back(1);
v.push_back(2);

//Vector should contain the elements 1, 2

//Find new end iterator
std::vector<int>::iterator newEnd = std::remove(v.begin(), v.end(), 1);

//Erase the "removed" elements.
v.erase(newEnd, v.end());

//Vector should now only contain 2

Thanks to Jim Buck for pointing out my error.

What is duck typing?

It is a term used in dynamic languages that do not have strong typing.

The idea is that you don't need a type in order to invoke an existing method on an object - if a method is defined on it, you can invoke it.

The name comes from the phrase "If it looks like a duck and quacks like a duck, it's a duck".

Wikipedia has much more information.

Get DataKey values in GridView RowCommand

I managed to get the value of the DataKeys using this code:

In the GridView I added:

DataKeyNames="ID" OnRowCommand="myRowCommand"

Then in my row command function:

protected void myRowCommand(object sender, GridViewCommandEventArgs e) 
{
    LinkButton lnkBtn = (LinkButton)e.CommandSource;    // the button
    GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent;  // the row
    GridView myGrid = (GridView)sender; // the gridview
    string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString(); // value of the datakey 

    switch (e.CommandName)
    {
      case "cmd1":
      // do something using the ID
      break;
      case "cmd2":
      // do something else using the ID
      break;
    }
 }

python dataframe pandas drop column using int

Since there can be multiple columns with same name , we should first rename the columns. Here is code for the solution.

df.columns=list(range(0,len(df.columns)))
df.drop(columns=[1,2])#drop second and third columns

Show/Hide Multiple Divs with Jquery

Assign each div a class. Then you can perform actions on all of them:

$(".divClass").hide();

So each button can do:

$(".divClass").hide()
$("#specificDiv").show();

You can make this more generic, and use the obvious convention - the button and the div with the same number in the id are related. So:

$(".button").click(function() {
  var divId = "#div" + $(this).attr("id").replace("showdiv", "");
  $(".divClass").hide(); 
  $(divId).show();
}

Twitter Bootstrap Datepicker within modal window

I had this error, because i scrolled bottom. Datepicker had wrong top position in fixed. I just use it now like:

$('#myModal').on('show.bs.modal', function (e) {
            $(document).scrollTop(0);
});

and its working fine now.

How to make the overflow CSS property work with hidden as value

This worked for me

<div style="display: flex; position: absolute; width: 100%;">
  <div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
  </div>
</div>

Adding position:absolute to the parent container made it work.

PS: This is for anyone looking for a solution to dynamically truncating text.

EDIT: This was meant to be an answer for this question but since they are related and it could help someone on this question I shall also leave it here instead of deleting it.

What is an ORM, how does it work, and how should I use one?

An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database.

Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders.

Here's a brief clip from Martin Fowler (Data Mapper):

Patterns of Enterprise Application Architecture Data Mappers

What is a tracking branch?

This was how I added a tracking branch so I can pull from it into my new branch:

git branch --set-upstream-to origin/Development new-branch

Print raw string from variable? (not getting the answers)

Get rid of the escape characters before storing or manipulating the raw string:

You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:

>>> mypath = os.getcwd().replace('\\','/')  
>>> os.path.exists(mypath)  
True  
>>>   

What is the difference between for and foreach?

The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false.

There is a need to specify the loop bounds (minimum or maximum). Following is a code example of a simple for loop that starts 0 till <= 5.

we look at foreach in detail. What looks like a simple loop on the outside is actually a complex data structure called an enumerator:

An enumerator is a data structure with a Current property, a MoveNext method, and a Reset method. The Current property holds the value of the current element, and every call to MoveNext advances the enumerator to the next item in the sequence.

Enumerators are great because they can handle any iterative data structure. In fact, they are so powerful that all of LINQ is built on top of enumerators.

But the disadvantage of enumerators is that they require calls to Current and MoveNext for every element in the sequence. All those method calls add up, especially in mission-critical code.

Conversely, the for-loop only has to call get_Item for every element in the list. That’s one method call less than the foreach-loop, and the difference really shows.

So when should you use a foreach-loop, and when should you use a for-loop?

Here’s what you need to do:

When you’re using LINQ, use foreach
When you’re working with very large computed sequences of values, use foreach
When performance isn’t an issue, use foreach
But if you want top performance, use a for-loop instead

jquery to change style attribute of a div class

Just try $('.handle').css('left', '300px');

Does reading an entire file leave the file handle open?

You can use pathlib.

For Python 3.5 and above:

from pathlib import Path
contents = Path(file_path).read_text()

For older versions of Python use pathlib2:

$ pip install pathlib2

Then:

from pathlib2 import Path
contents = Path(file_path).read_text()

This is the actual read_text implementation:

def read_text(self, encoding=None, errors=None):
    """
    Open the file in text mode, read it, and close the file.
    """
    with self.open(mode='r', encoding=encoding, errors=errors) as f:
        return f.read()

Why can I not create a wheel in python?

I also ran into the error message invalid command 'bdist_wheel'

It turns out the package setup.py used distutils rather than setuptools. Changing it as follows enabled me to build the wheel.

#from distutils.core import setup
from setuptools import setup

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

I got this error on Ubuntu, and the following worked for me:

Removed the dropbox binaries and download them again, by running:

sudo rm -rf /var/lib/dropbox/.dropbox-dist
dropbox start -i

Send JSON data with jQuery

I wrote a short convenience function for posting JSON.

$.postJSON = function(url, data, success, args) {
  args = $.extend({
    url: url,
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: true,
    success: success
  }, args);
  return $.ajax(args);
};

$.postJSON('test/url', data, function(result) {
  console.log('result', result);
});

TypeScript: Property does not exist on type '{}'

Access the field with array notation to avoid strict type checking on single field:

data['propertyName']; //will work even if data has not declared propertyName

Alternative way is (un)cast the variable for single access:

(<any>data).propertyName;//access propertyName like if data has no type

The first is shorter, the second is more explicit about type (un)casting


You can also totally disable type checking on all variable fields:

let untypedVariable:any= <any>{}; //disable type checking while declaring the variable
untypedVariable.propertyName = anyValue; //any field in untypedVariable is assignable and readable without type checking

Note: This would be more dangerous than avoid type checking just for a single field access, since all consecutive accesses on all fields are untyped

How to add dividers and spaces between items in RecyclerView?

The way how I'm handling the Divider view and also Divider Insets is by adding a RecyclerView extension.

1.

Add a new extension file by naming View or RecyclerView:

RecyclerViewExtension.kt

and add the setDivider extension method inside the RecyclerViewExtension.kt file.

/*
* RecyclerViewExtension.kt
* */
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView


fun RecyclerView.setDivider(@DrawableRes drawableRes: Int) {
    val divider = DividerItemDecoration(
        this.context,
        DividerItemDecoration.VERTICAL
    )
    val drawable = ContextCompat.getDrawable(
        this.context,
        drawableRes
    )
    drawable?.let {
        divider.setDrawable(it)
        addItemDecoration(divider)
    }
}

2.

Create a Drawable resource file inside of drawable package like recycler_view_divider.xml:

<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="10dp"
    android:insetRight="10dp">

    <shape>
        <size android:height="0.5dp" />
        <solid android:color="@android:color/darker_gray" />
    </shape>

</inset>

where you can specify the left and right margin on android:insetLeft and android:insetRight.

3.

On your Activity or Fragment where the RecyclerView is initialized, you can set the custom drawable by calling:

recyclerView.setDivider(R.drawable.recycler_view_divider)

4.

Cheers

RecyclerView row with divider.

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

My problem was the wrong port number for mongoDB server.

I had:

DATABASE_URL= "mongodb://localhost:3000/node-express-mongodb-server"

in my .env file (my environmental variables), but I had written it before running mongoDB server. So when I ran the mongoDB server, it wrote a different port number and I had to change it. I changed it to the right port number (which was written on my cmd window by mongoDB):

DATABASE_URL= "mongodb://localhost:27017/node-express-mongodb-server"

and now it works fine.

How to plot a function curve in R

plot has a plot.function method

plot(eq, 1, 1000)

Or

curve(eq, 1, 1000)

Where does linux store my syslog?

I'm running Ubuntu under WSL(Windows Subsystem for Linux) and systemctl start rsyslog didn't work for me.

So what I did is this:

$ service rsyslog start

Now syslog file will appear at /var/log/

How to set standard encoding in Visual Studio

Do you want the files to save as UTF-8 because you are using special characters that would be lost in ASCII encoding? If that's the case, then there is a VS2008 global setting in Tools > Options > Environment > Documents, named Save documents as Unicode when data cannot be saved in codepage. When this is enabled, VS2008 will save as Unicode if certain characters cannot be represented in the otherwise-default codepage.

Also, which files are not being saved as UTF-8? All of my .cs, .csproj, .sln, .config, .as*x, etc, all save as UTF-8 (with signature, the byte order marks), by default.

How many spaces will Java String.trim() remove?

See API for String class:

Returns a copy of the string, with leading and trailing whitespace omitted.

Whitespace on both sides is removed:

Note that trim() does not change the String instance, it will return a new object:

 String original = "  content  ";
 String withoutWhitespace = original.trim();

 // original still refers to "  content  "
 // and withoutWhitespace refers to "content"

Map and Reduce in .NET

The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

var wordOccurrences = words
                .GroupBy(w => w)
                .Select(intermediate => new
                {
                    Word = intermediate.Key,
                    Frequency = intermediate.Sum(w => 1)
                })
                .Where(w => w.Frequency > 10)
                .OrderBy(w => w.Frequency);

For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

How to append rows to an R data frame

My solution is almost the same as the original answer but it doesn't worked for me.

So, I gave names for the columns and it works:

painel <- rbind(painel, data.frame("col1" = xtweets$created_at,
                                   "col2" = xtweets$text))

How to convert a negative number to positive?

simply multiplying by -1 works in both ways ...

>>> -10 * -1
10
>>> 10 * -1
-10

How do I import a namespace in Razor View Page?

For namespace and Library

@using NameSpace_Name

For Model

@model Application_Name.Models.Model_Name 

For Iterate the list on Razor Page (You Have to use foreach loop for access the list items)

@model List<Application_Name.Models.Model_Name>

@foreach (var item in Model)
   {  
          <tr>
                <td>@item.srno</td>
                <td>@item.name</td>
         </tr>  
   }

Add a thousands separator to a total with Javascript or jQuery?

a recursive solution:

function thousands(amount) {
  if( /\d{3}\d+/.test(amount) ) {
    return thousands(amount.replace(/(\d{3}?)(,|$)/, ',$&'));
  }
  return amount;
}

another split solution:

function thousands (amount) {
  return amount
    // reverse string
    .split('')
    .reverse()
    .join('')
    // grouping starting by units
    .replace(/\d{3}/g, '$&,')
    // reverse string again
    .split('')
    .reverse()
    .join('');
}

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

How do I read a string entered by the user in C?

Using scanf removing any blank spaces before the string is typed and limiting the amount of characters to be read:

#define SIZE 100

....

char str[SIZE];

scanf(" %99[^\n]", str);

/* Or even you can do it like this */

scanf(" %99[a-zA-Z0-9 ]", str);

If you do not limit the amount of characters to be read with scanf it can be as dangerous as gets

jquery, find next element by class

You cannot use next() in this scenario, if you look at the documentation it says:
Next() Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling that matches the selector.

so if the second DIV was in the same TD then you could code:


// Won't work in your case
$(obj).next().filter('.class');

But since it's not, I don't see a point to use next(). You can instead code:

$(obj).parents('table').find('.class')

How do I read all classes from a Java package in the classpath?

Scannotation and Reflections use class path scanning approach:

Reflections reflections = new Reflections("my.package");
Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);

Another approach is to use Java Pluggable Annotation Processing API to write annotation processor which will collect all annotated classes at compile time and build the index file for runtime use. This mechanism is implemented in ClassIndex library:

Iterable<Class> classes = ClassIndex.getPackageClasses("my.package");

C# list.Orderby descending

list.OrderByDescending();

works for me.

How to add include and lib paths to configure/make cycle?

Set LDFLAGS and CFLAGS when you run make:

$ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make

If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib

Simple java program of pyramid

Try this one

 public static void main(String[] args) 
{
     int x=11;
     int y=x/2; // spaces
     int z=1; // *`s

     for(int i=0;i<5;i++)
    {
         for(int j=0;j<y;j++)
        {
             System.out.print(" ");
        }
        for(int k=0;k<z;k++)
        {
            System.out.print("*");
        }

        y=y-1;
        z=z+2;
        System.out.println();  
    }

}

Excel VBA function to print an array to the workbook

A more elegant way is to assign the whole array at once:

Sub PrintArray(Data, SheetName, StartRow, StartCol)

    Dim Rng As Range

    With Sheets(SheetName)
        Set Rng = .Range(.Cells(StartRow, StartCol), _
            .Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _
            UBound(Data, 2) - LBound(Data, 2) + StartCol))
    End With
    Rng.Value2 = Data

End Sub

But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.

Escaping Strings in JavaScript

You can also use this

_x000D_
_x000D_
let str = "hello single ' double \" and slash \\ yippie";

let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
_x000D_
_x000D_
_x000D_

Text Editor which shows \r\n?

EmEditor does this. You can also customize what symbols actually display to show them.

Closing JFrame with button click

You can use super.dispose() method which is more similar to close operation.

MySQL & Java - Get id of the last inserted value (JDBC)

Wouldn't you just change:

numero = stmt.executeUpdate(query);

to:

numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Take a look at the documentation for the JDBC Statement interface.

Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.

Removing the textarea border in HTML

This one is great:

<style type="text/css">
textarea.test
{  
width: 100%;
height: 100%;
border-color: Transparent;     
}
</style>
<textarea class="test"></textarea>

MySQL: How to set the Primary Key on phpMyAdmin?

MySQL can index the first x characters of a column,but a TEXT type is of variable length so mysql cant assure the uniqueness of the column.If you still want text column,use VARCHAR.

Failed to load resource under Chrome

I updated my Chrome browser to the latest version and the issue was fixed.

.NET Global exception handler in console application

What you are trying should work according to the MSDN doc's for .Net 2.0. You could also try a try/catch right in main around your entry point for the console app.

static void Main(string[] args)
{
    try
    {
        // Start Working
    }
    catch (Exception ex)
    {
        // Output/Log Exception
    }
    finally
    {
        // Clean Up If Needed
    }
}

And now your catch will handle anything not caught (in the main thread). It can be graceful and even restart where it was if you want, or you can just let the app die and log the exception. You woul add a finally if you wanted to do any clean up. Each thread will require its own high level exception handling similar to the main.

Edited to clarify the point about threads as pointed out by BlueMonkMN and shown in detail in his answer.

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

You can get this type of error if your class' .m file is not listed under the "Compile Sources" step of the "Build Phases" tab of your target. Normally Xcode does this for you, but sometimes it loses the plot and you need to add the .m file manually.

To do this:

TargetSettings -> Build Phases -> Compile Sources -> add your .m class ->Build and Run

PHP array printing using a loop

Foreach before foreach: :)

reset($array); 
while(list($key,$value) = each($array))
{
  // we used this back in php3 :)
}

Why is it OK to return a 'vector' from a function?

To well understand the behaviour, you can run this code:

#include <iostream>

class MyClass
{
  public:
    MyClass() { std::cout << "run constructor MyClass::MyClass()" << std::endl; }
    ~MyClass() { std::cout << "run destructor MyClass::~MyClass()" << std::endl; }
    MyClass(const MyClass& x) { std::cout << "run copy constructor MyClass::MyClass(const MyClass&)" << std::endl; }
    MyClass& operator = (const MyClass& x) { std::cout << "run assignation MyClass::operator=(const MyClass&)" << std::endl; }
};

MyClass my_function()
{
  std::cout << "run my_function()" << std::endl;
  MyClass a;
  std::cout << "my_function is going to return a..." << std::endl;
  return a;
}

int main(int argc, char** argv)
{
  MyClass b = my_function();

  MyClass c;
  c = my_function();

  return 0;
}

The output is the following:

run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run constructor MyClass::MyClass()
run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run assignation MyClass::operator=(const MyClass&)
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()

Note that this example was provided in C++03 context, it could be improved for C++ >= 11

Installed Java 7 on Mac OS X but Terminal is still using version 6

In my case, the issue was that Oracle was installing it to a different location than I was used to.

Download from Oracle: http://java.com/en/download/mac_download.jsp?locale=en

  1. Verify that it's installed properly by looking in System Prefs:

    • Command-Space to open Spotlight, type 'System Preferences', hit enter.
    • Click Java icon in bottom row. After the Java Control Panel opens, click 'Java' tab, 'View...', and verify that your install worked. You can see a 'Path' there also, which you can sub into the commands below in case they are different than mine.
  2. Verify that the version is as you expect (sub in your path as needed):

    /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java -version

  3. Create link from /usr/bin/java to your new install

    sudo ln -fs /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java

  4. Sanity check your version:

    java -version

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.

Event system in Python

If you need an eventbus that works across process or network boundaries you can try PyMQ. It currently supports pub/sub, message queues and synchronous RPC. The default version works on top of a Redis backend, so you need a running Redis server. There is also an in-memory backend for testing. You can also write your own backend.

import pymq

# common code
class MyEvent:
    pass

# subscribe code
@pymq.subscriber
def on_event(event: MyEvent):
    print('event received')

# publisher code
pymq.publish(MyEvent())

# you can also customize channels
pymq.subscribe(on_event, channel='my_channel')
pymq.publish(MyEvent(), channel='my_channel')

To initialize the system:

from pymq.provider.redis import RedisConfig

# starts a new thread with a Redis event loop
pymq.init(RedisConfig())

# main application control loop

pymq.shutdown()

Disclaimer: I am the author of this library

Get current AUTO_INCREMENT value for any table

mysqli executable sample code:

<?php
    $db = new mysqli("localhost", "user", "password", "YourDatabaseName");
    if ($db->connect_errno) die ($db->connect_error);

    $table=$db->prepare("SHOW TABLE STATUS FROM YourDatabaseName");
    $table->execute();
    $sonuc = $table->get_result();
    while ($satir=$sonuc->fetch_assoc()){
        if ($satir["Name"]== "YourTableName"){
            $ai[$satir["Name"]]=$satir["Auto_increment"];
        }
    }
    $LastAutoIncrement=$ai["YourTableName"];
    echo $LastAutoIncrement;
?>  

Calling a JSON API with Node.js

I think that for simple HTTP requests like this it's better to use the request module. You need to install it with npm (npm install request) and then your code can look like this:

const request = require('request')
     ,url = 'http://graph.facebook.com/517267866/?fields=picture'

request(url, (error, response, body)=> {
  if (!error && response.statusCode === 200) {
    const fbResponse = JSON.parse(body)
    console.log("Got a response: ", fbResponse.picture)
  } else {
    console.log("Got an error: ", error, ", status code: ", response.statusCode)
  }
})

How to check if a process is running via a batch script

Building on vtrz's answer and Samuel Renkert's answer on an other topic, I came up with the following script that only runs %EXEC_CMD% if it isn't already running:

@echo off
set EXEC_CMD="rsync.exe"
wmic process where (name=%EXEC_CMD%) get commandline | findstr /i %EXEC_CMD%> NUL
if errorlevel 1 (
    %EXEC_CMD% ...
) else (
    @echo not starting %EXEC_CMD%: already running.
)

As was said before, this requires administrative privileges.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

try import django then run django.setup() after the secret_key definition. like so:

SECRET_KEY = 'it5bs))q6toz-1gwf(+j+f9@rd8%_-0nx)p-2!egr*y1o51=45XXCV'
django.setup()

Fixed width buttons with Bootstrap

Just came upon the same need and was not satified with defining fixed width.

So did it with jquery:

_x000D_
_x000D_
    var max = Math.max ($("#share_cancel").width (), $("#share_commit").width ());_x000D_
    $("#share_cancel").width (max);_x000D_
    $("#share_commit").width (max); 
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
    <button type="button" class="btn btn-secondary" id="share_cancel">SHORT</button>_x000D_
    <button type="button" class="btn btn-success" id="share_commit">LOOOOOOOOONG</button>
_x000D_
_x000D_
_x000D_

Android Studio 3.0 Execution failed for task: unable to merge dex

Simply try doing a "Build -> Clean Project". That solved the problem for me.

PHP Email sending BCC

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: [email protected]\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";

Blurry text after using CSS transform: scale(); in Chrome

For me the problem was that my elements were using transformStyle: preserve-3d. I realized that this wasn't actually needed for the app and removing it fixed the blurriness.

How to write inline if statement for print?

You always need an else in an inline if:

a = 1 if b else 0

But an easier way to do it would be a = int(b).

Count with IF condition in MySQL query

This should work:

count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, NULL))

count() only check if the value exists or not. 0 is equivalent to an existent value, so it counts one more, while NULL is like a non-existent value, so is not counted.

How to scale a BufferedImage

Unfortunately the performance of getScaledInstance() is very poor if not problematic.

The alternative approach is to create a new BufferedImage and and draw a scaled version of the original on the new one.

BufferedImage resized = new BufferedImage(newWidth, newHeight, original.getType());
Graphics2D g = resized.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(original, 0, 0, newWidth, newHeight, 0, 0, original.getWidth(),
    original.getHeight(), null);
g.dispose();

newWidth,newHeight indicate the new BufferedImage size and have to be properly calculated. In case of factor scaling:

int newWidth = new Double(original.getWidth() * widthFactor).intValue();
int newHeight = new Double(original.getHeight() * heightFactor).intValue();

EDIT: Found the article illustrating the performance issue: The Perils of Image.getScaledInstance()

Assign null to a SqlParameter

In my opinion the better way is to do this with the Parameters property of the SqlCommand class:

public static void AddCommandParameter(SqlCommand myCommand)
{
    myCommand.Parameters.AddWithValue(
        "@AgeIndex",
        (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex);
}

PHP cURL GET request and request's body

CURLOPT_POSTFIELDS as the name suggests, is for the body (payload) of a POST request. For GET requests, the payload is part of the URL in the form of a query string.

In your case, you need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.

curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);

//$body = '{}';
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
//curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Two onClick actions one button

Additional attributes (in this case, the second onClick) will be ignored. So, instead of onclick calling both fbLikeDump(); and WriteCookie();, it will only call fbLikeDump();. To fix, simply define a single onclick attribute and call both functions within it:

<input type="button" value="Don't show this again! " onclick="fbLikeDump();WriteCookie();" />

Group a list of objects by an attribute

public class Test9 {

    static class Student {

        String stud_id;
        String stud_name;
        String stud_location;

        public Student(String stud_id, String stud_name, String stud_location) {
            super();
            this.stud_id = stud_id;
            this.stud_name = stud_name;
            this.stud_location = stud_location;
        }

        public String getStud_id() {
            return stud_id;
        }

        public void setStud_id(String stud_id) {
            this.stud_id = stud_id;
        }

        public String getStud_name() {
            return stud_name;
        }

        public void setStud_name(String stud_name) {
            this.stud_name = stud_name;
        }

        public String getStud_location() {
            return stud_location;
        }

        public void setStud_location(String stud_location) {
            this.stud_location = stud_location;
        }

        @Override
        public String toString() {
            return " [stud_id=" + stud_id + ", stud_name=" + stud_name + "]";
        }

    }

    public static void main(String[] args) {

        List<Student> list = new ArrayList<Student>();
        list.add(new Student("1726", "John Easton", "Lancaster"));
        list.add(new Student("4321", "Max Carrados", "London"));
        list.add(new Student("2234", "Andrew Lewis", "Lancaster"));
        list.add(new Student("5223", "Michael Benson", "Leeds"));
        list.add(new Student("5225", "Sanath Jayasuriya", "Leeds"));
        list.add(new Student("7765", "Samuael Vatican", "California"));
        list.add(new Student("3442", "Mark Farley", "Ladykirk"));
        list.add(new Student("3443", "Alex Stuart", "Ladykirk"));
        list.add(new Student("4321", "Michael Stuart", "California"));

        Map<String, List<Student>> map1  =

                list
                .stream()

            .sorted(Comparator.comparing(Student::getStud_id)
                    .thenComparing(Student::getStud_name)
                    .thenComparing(Student::getStud_location)
                    )

                .collect(Collectors.groupingBy(

                ch -> ch.stud_location

        ));

        System.out.println(map1);

/*
  Output :

{Ladykirk=[ [stud_id=3442, stud_name=Mark Farley], 
 [stud_id=3443, stud_name=Alex Stuart]], 

 Leeds=[ [stud_id=5223, stud_name=Michael Benson],  
 [stud_id=5225, stud_name=Sanath Jayasuriya]],


  London=[ [stud_id=4321, stud_name=Max Carrados]],


   Lancaster=[ [stud_id=1726, stud_name=John Easton],  

   [stud_id=2234, stud_name=Andrew Lewis]], 


   California=[ [stud_id=4321, stud_name=Michael Stuart],  
   [stud_id=7765, stud_name=Samuael Vatican]]}
*/


    }// main
}

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

I gave up trying to fix this issue.

My IIS web.config had the relevant "Access-Control-Allow-Methods" in it, I experimented adding config settings to my Angular code, but after burning a few hours trying to get Chrome to call a cross-domain JSON web service, I gave up miserably.

In the end, I added a dumb ASP.Net handler webpage, got that to call my JSON web service, and return the results. It was up and running in 2 minutes.

Here's the code I used:

public class LoadJSONData : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        string URL = "......";

        using (var client = new HttpClient())
        {
            // New code:
            client.BaseAddress = new Uri(URL);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Authorization", "Basic AUTHORIZATION_STRING");

            HttpResponseMessage response = client.GetAsync(URL).Result;
            if (response.IsSuccessStatusCode)
            {
                var content = response.Content.ReadAsStringAsync().Result;
                context.Response.Write("Success: " + content);
            }
            else
            {
                context.Response.Write(response.StatusCode + " : Message - " + response.ReasonPhrase);
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

And in my Angular controller...

$http.get("/Handlers/LoadJSONData.ashx")
   .success(function (data) {
      ....
   });

I'm sure there's a simpler/more generic way of doing this, but life's too short...

This worked for me, and I can get on with doing normal work now !!

Setting std=c99 flag in GCC

How about alias gcc99= gcc -std=c99?

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

What is the difference between VFAT and FAT32 file systems?

FAT32 along with FAT16 and FAT12 are File System Types, but vfat along with umsdos and msdos are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos driver don't have long filenames (they are 8.3 format). vfat is the most common driver for mounting FAT32 file systems nowadays.

Source: this wikipedia article

Output of commands like df and lsblk indeed show vfat as the File System Type. But sudo file -sL /dev/<partition> shows FAT (32 bit) if a File System is FAT32.

You can confirm vfat is a module and not a File System Type by running modinfo vfat.

What is the cause for "angular is not defined"

You have to put your script tag after the one that references Angular. Move it out of the head:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>

The way you've set it up now, your script runs before Angular is loaded on the page.

fatal error: Python.h: No such file or directory

I also encountered this error when I was installing coolprop in ubuntu.

For ubuntu 16.04 with python 3.6

sudo apt-get install python3.6-dev

If ever this doesn't work try installing/updating gcc lib.

sudo apt-get install gcc

Laravel Eloquent - distinct() and count() not working properly together

Based on Laravel docs for raw queries I was able to get count for a select field to work with this code in the product model.

public function scopeShowProductCount($query)
{
    $query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
          ->groupBy('pid')
          ->orderBy('count_pid', 'desc');
}

This facade worked to get the same result in the controller:

$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();

The resulting dump for both queries was as follows:

#attributes: array:2 [
  "pid" => "1271"
  "count_pid" => 19
],
#attributes: array:2 [
  "pid" => "1273"
  "count_pid" => 12
],
#attributes: array:2 [
  "pid" => "1275"
  "count_pid" => 7
]

How can I remove all objects but one from the workspace in R?

To keep all objects whose names match a pattern, you could use grep, like so:

to.remove <- ls()
to.remove <- c(to.remove[!grepl("^obj", to.remove)], "to.remove")
rm(list=to.remove)

What does "async: false" do in jQuery.ajax()?

  • async:false = Code paused. (Other code waiting for this to finish.)
  • async:true = Code continued. (Nothing gets paused. Other code is not waiting.)

As simple as this.

What's the best three-way merge tool?

Diffuse is an easy to use three-way merge tool. It supports all of the platforms and version control systems you mentioned, and it can compare more than three files at the same time.

enter image description here

Adding Permissions in AndroidManifest.xml in Android Studio?

Go to Android Manifest.xml and be sure to add the <uses-permission tag > inside the manifest tag but Outside of all other tags..

<manifest xlmns:android...>

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

This is an example of the permission of using Internet.

What is the 'open' keyword in Swift?

open come to play when dealing with multiple modules.

open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.

Can Selenium interact with an existing browser session?

All the solutions so far were lacking of certain functionality. Here is my solution:

public class AttachedWebDriver extends RemoteWebDriver {

    public AttachedWebDriver(URL url, String sessionId) {
        super();
        setSessionId(sessionId);
        setCommandExecutor(new HttpCommandExecutor(url) {
            @Override
            public Response execute(Command command) throws IOException {
                if (command.getName() != "newSession") {
                    return super.execute(command);
                }
                return super.execute(new Command(getSessionId(), "getCapabilities"));
            }
        });
        startSession(new DesiredCapabilities());
    }
}

Why would I use dirname(__FILE__) in an include or include_once statement?

I used this below if this is what you are thinking. It it worked well for me.

<?php
    include $_SERVER['DOCUMENT_ROOT']."/head_lib.php";
?>

What I was trying to do was pulla file called /head_lib.php from the root folder. It would not pull anything to build the webpage. The header, footer and other key features in sub directories would never show up. Until I did above it worked like a champ.

How to represent a DateTime in Excel

dd-mm-yyyy hh:mm:ss.000 Universal sortable date/time pattern

Execute Stored Procedure from a Function

EDIT: I haven't tried this, so I can't vouch for it! And you already know you shouldn't be doing this, so please don't do it. BUT...

Try looking here: http://sqlblog.com/blogs/denis_gobo/archive/2008/05/08/6703.aspx

The key bit is this bit which I have attempted to tweak for your purposes:

DECLARE @SQL varchar(500)

SELECT @SQL = 'osql -S' +@@servername +' -E -q "exec dbName..sprocName "'

EXEC master..xp_cmdshell @SQL

Create Carriage Return in PHP String?

I find the adding <br> does what is wanted.

Do AJAX requests retain PHP Session info?

What you're really getting at is: are cookies sent to with the AJAX request? Assuming the AJAX request is to the same domain (or within the domain constraints of the cookie), the answer is yes. So AJAX requests back to the same server do retain the same session info (assuming the called scripts issue a session_start() as per any other PHP script wanting access to session information).

Mapping object to dictionary and vice versa

I think you should use reflection. Something like this:

private T ConvertDictionaryTo<T>(IDictionary<string, object> dictionary) where T : new()
{
    Type type = typeof (T);
    T ret = new T();

    foreach (var keyValue in dictionary)
    {
        type.GetProperty(keyValue.Key).SetValue(ret, keyValue.Value, null);
    }

    return ret;
}

It takes your dictionary and loops through it and sets the values. You should make it better but it's a start. You should call it like this:

SomeClass someClass = ConvertDictionaryTo<SomeClass>(a);

jQuery returning "parsererror" for ajax request

If you get this problem using HTTP GET in IE I solved this issue by setting the cache: false. As I used the same url for both HTML and json requests it hit the cache instead of doing a json call.

$.ajax({
    url: '/Test/Something/',
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: { viewID: $("#view").val() },
    success: function (data) {
        alert(data);
    },
    error: function (data) {
        debugger;
        alert("Error");
    }
});

Named placeholders in string formatting

Apache Commons Lang's replaceEach method may come in handy dependeding on your specific needs. You can easily use it to replace placeholders by name with this single method call:

StringUtils.replaceEach("There's an incorrect value '%(value)' in column # %(column)",
            new String[] { "%(value)", "%(column)" }, new String[] { x, y });

Given some input text, this will replace all occurrences of the placeholders in the first string array with the corresponding values in the second one.

In PowerShell, how can I test if a variable holds a numeric value?

You can do something like :

$testvar -match '^[0-9]+$'

or

$testvar -match '^\d+$'

Returns True if $testvar is a number.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

How to use setArguments() and getArguments() methods in Fragments?

for those like me who are looking to send objects other than primitives, since you can't create a parameterized constructor in your fragment, just add a setter accessor in your fragment, this always works for me.

How to disable Google Chrome auto update?

If you are using Mac OS. Keep the version that you need and then following step help you stop updating chrome permanently.

To Disable auto update:-

Empty these directories:

~/Library/Google/GoogleSoftwareUpdate/

Then change the permissions on these folders named 'GoogleSoftwareUpdate' so that there's no owner and no read/write/execute permissions. In terminal:

cd /Library/Google/
sudo chown nobody:nogroup GoogleSoftwareUpdate
sudo chmod 000 GoogleSoftwareUpdate

cd ~/Library/Google/
sudo chown nobody:nogroup GoogleSoftwareUpdate
sudo chmod 000 GoogleSoftwareUpdate                                                                        

Then do the same for the folder Google one level up.

cd /Library/
sudo chown nobody:nogroup Google
sudo chmod 000 Google
cd ~/Library/                                                                                                                    
sudo chown nobody:nogroup Google
sudo chmod 000 Google

Hope this help!

How to top, left justify text in a <td> cell that spans multiple rows

td[rowspan] {
  vertical-align: top;
  text-align: left;
}

See: CSS attribute selectors.

Reading a JSP variable from JavaScript

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

    <title>JSP Page</title>
    <script>
       $(document).ready(function(){
          <% String name = "phuongmychi.github.io" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html

       });
    </script>
</head>
<body>
    <h1 id='id'>!</h1>
</body>

how to generate web service out of wsdl

step-1

open -> Visual Studio 2017 Developer Command Prompt

step-2

WSDL.exe  /OUT:myFile.cs WSDLURL  /Language:CS /serverInterface
  • /serverInterface (this to create interface from wsdl file)
  • WSDL.exe (this use to create class from wsdl. this comes with .net
  • /OUT: (output file name)

step-2

create new "Web service Project"

step-3

add -> web service

step-4

copy all code from myFile.cs (generated above) except "using classes" eg:

 /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
    [System.Web.Services.WebServiceBindingAttribute(Name="calculoterServiceSoap",Namespace="http://tempuri.org/")]

public interface ICalculoterServiceSoap {

    /// <remarks/>
    [System.Web.Services.WebMethodAttribute()]
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/addition", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    string addition(int firtNo, int secNo);
}

step-4

past it into your webService.asmx.cs (inside of namespace) created above in step-2

step-5

inherit the interface class with your web service class eg:

public class WebService2 : ICalculoterServiceSoap

Get most recent row for given ID

Use the aggregate MAX(signin) grouped by id. This will list the most recent signin for each id.

SELECT 
 id, 
 MAX(signin) AS most_recent_signin
FROM tbl
GROUP BY id

To get the whole single record, perform an INNER JOIN against a subquery which returns only the MAX(signin) per id.

SELECT 
  tbl.id,
  signin,
  signout
FROM tbl
  INNER JOIN (
    SELECT id, MAX(signin) AS maxsign FROM tbl GROUP BY id
  ) ms ON tbl.id = ms.id AND signin = maxsign
WHERE tbl.id=1

How to import an excel file in to a MySQL database

Fastest and simpliest way is to save XLS as ODS (open document spreasheet) and import it from PhpMyAdmin enter image description here

Python, print all floats to 2 decimal places in output

I have just discovered the round function - it is in Python 2.7, not sure about 2.6. It takes a float and the number of dps as arguments, so round(22.55555, 2) gives the result 22.56.

Tomcat: How to find out running tomcat version

On Windows just cmd

C:\Program Files (x86)\Extensis\Portfolio Server\applications\tomcat\bin>version

Call PHP function from jQuery?

This is exactly what ajax is for. See here:

http://api.jquery.com/load/

Basically, you ajax/test.php and put the returned HTML code to the element which has the result id.

$('#result').load('ajax/test.php');

Of course, you will need to put the functionality which takes time to a new php file (or call the old one with a GET parameter which will activate that functionality only).

row-level trigger vs statement-level trigger

statement level trigger is only once for dml statement row leval trigger is for each row for dml statements

Why is null an object and what's the difference between null and undefined?

null is an object. Its type is null. undefined is not an object; its type is undefined.

Save a list to a .txt file

If you have more then 1 dimension array

with open("file.txt", 'w') as output:
    for row in values:
        output.write(str(row) + '\n')

Code to write without '[' and ']'

with open("file.txt", 'w') as file:
        for row in values:
            s = " ".join(map(str, row))
            file.write(s+'\n')

Get the current date and time

use DateTime.Now

try this:

DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")

Style input type file?

Same solution via Jquery. Works if you have more than one file input in the page.

$j(".filebutton").click(function() {
    var input = $j(this).next().find('input');
    input.click();
});

$j(".fileinput").change(function(){

    var file = $j(this).val();
    var fileName = file.split("\\");
    var pai =$j(this).parent().parent().prev();
    pai.html(fileName[fileName.length-1]);
    event.preventDefault();
});

What is the difference between XAMPP or WAMP Server & IIS?

XAMPP and WAMP are both web server applications for PHP and MYSQL with the apache server. When we consider IIS, it also a web-server like apache runs on windows only.

XWAMPP/WAMP - Windows,Apache,Mysql,PHP

IIS - Apache,SQL Server, ASP.NET

If you like to read more about XWAMPP vs WAMP

Centering the image in Bootstrap

Update 2018

Bootstrap 2.x

You could create a new CSS class such as:

.img-center {margin:0 auto;}

And then, add this to each IMG:

 <img src="images/2.png" class="img-responsive img-center">

OR, just override the .img-responsive if you're going to center all images..

 .img-responsive {margin:0 auto;}

Demo: http://bootply.com/86123

Bootstrap 3.x

EDIT - With the release of Bootstrap 3.0.1, the center-block class can now be used without any additional CSS..

 <img src="images/2.png" class="img-responsive center-block">

Bootstrap 4

In Bootstrap 4, the mx-auto class (auto x-axis margins) can be used to center images that are display:block. However, img is display:inline by default so text-center can be used on the parent.

<div class="container">
    <div class="row">
        <div class="col-12">
            <img class="mx-auto d-block" src="//placehold.it/200">  
        </div>
    </div>
    <div class="row">
        <div class="col-12 text-center">
            <img src="//placehold.it/200">  
        </div>
    </div>
</div>

Bootsrap 4 - center image demo

MySQL search and replace some text in a field

The Replace string function will do that.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

For swift

var dateString:String = "2014-05-20";
var dateFmt = NSDateFormatter()
// the format you want
dateFmt.dateFormat = "yyyy-MM-dd"
var date1:NSDate = dateFmt.dateFromString(dateString)!;

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

For all those stuck with a similar problem, run the following:

LD_LIBRARY_PATH=/usr/local/lib64/:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH

When you compile and install GCC it does put the libraries here but that's it. As the FAQs say ( http://gcc.gnu.org/onlinedocs/libstdc++/faq.html#faq.how_to_set_paths ) you need to add it.

I assumed "How do I insure that the dynamically linked library will be found? " meant "how do I make sure it is always found" not "it wont be found, you need to do this"

For those who don't bother setting a prefix, it is /usr/local/lib64

You can find this mentioned briefly when you install gcc if you read the make output:

Libraries have been installed in:
   /usr/local/lib/../lib32
If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,-rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages. 

Grr that was simple! Also "if you ever happen to want to link against the installed libraries" - seriously?

Session 'app': Error Launching activity

I had same problem. I was using AVD with arm processor image and received this same message. The only way for me to make Android Studio 2.1.2 runs the app with instant run was change to an X86 processor image. The error was gone and ( until this moment) I think the emulator works faster than ARM emulated. My workstation configuration is Intel I5, 6Gb RAM. Maybe this helps until next fix.

Can't find @Nullable inside javax.annotation.*

I am using Guava which has annotation included:

(Gradle code )

compile 'com.google.guava:guava:23.4-jre'

What are the advantages of NumPy over regular Python lists?

Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.

Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?

Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).

from numpy import arange
from timeit import Timer

Nelements = 10000
Ntimeits = 10000

x = arange(Nelements)
y = range(Nelements)

t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list:  %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))

which on my systems (while I'm running a backup) gives:

numpy: 3.004e-05
list:  5.363e-04

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

How can I turn a JSONArray into a JSONObject?

I have JSONObject like this: {"status":[{"Response":"success"}]}.

If I want to convert the JSONObject value, which is a JSONArray into JSONObject automatically without using any static value, here is the code for that.

JSONArray array=new JSONArray();
JSONObject obj2=new JSONObject();
obj2.put("Response", "success");
array.put(obj2);
JSONObject obj=new JSONObject();
obj.put("status",array);

Converting the JSONArray to JSON Object:

Iterator<String> it=obj.keys();
        while(it.hasNext()){
String keys=it.next();
JSONObject innerJson=new JSONObject(obj.toString());
JSONArray innerArray=innerJson.getJSONArray(keys);
for(int i=0;i<innerArray.length();i++){
JSONObject innInnerObj=innerArray.getJSONObject(i);
Iterator<String> InnerIterator=innInnerObj.keys();
while(InnerIterator.hasNext()){
System.out.println("InnInnerObject value is :"+innInnerObj.get(InnerIterator.next()));


 }
}

pthread function from a class

My favorite way to handle a thread is to encapsulate it inside a C++ object. Here's an example:

class MyThreadClass
{
public:
   MyThreadClass() {/* empty */}
   virtual ~MyThreadClass() {/* empty */}

   /** Returns true if the thread was successfully started, false if there was an error starting the thread */
   bool StartInternalThread()
   {
      return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
   }

   /** Will not return until the internal thread has exited. */
   void WaitForInternalThreadToExit()
   {
      (void) pthread_join(_thread, NULL);
   }

protected:
   /** Implement this method in your subclass with the code you want your thread to run. */
   virtual void InternalThreadEntry() = 0;

private:
   static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}

   pthread_t _thread;
};

To use it, you would just create a subclass of MyThreadClass with the InternalThreadEntry() method implemented to contain your thread's event loop. You'd need to call WaitForInternalThreadToExit() on the thread object before deleting the thread object, of course (and have some mechanism to make sure the thread actually exits, otherwise WaitForInternalThreadToExit() would never return)

Regex: matching up to the first occurrence of a character

/^[^;]*/

The [^;] says match anything except a semicolon. The square brackets are a set matching operator, it's essentially, match any character in this set of characters, the ^ at the start makes it an inverse match, so match anything not in this set.

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Tracking CPU and Memory usage per process

Process Explorer can show total CPU time taken by a process, as well as a history graph per process.

What is two way binding?

Two-way binding just means that:

  1. When properties in the model get updated, so does the UI.
  2. When UI elements get updated, the changes get propagated back to the model.

Backbone doesn't have a "baked-in" implementation of #2 (although you can certainly do it using event listeners). Other frameworks like Knockout do wire up two-way binding automagically.


enter image description here


In Backbone, you can easily achieve #1 by binding a view's "render" method to its model's "change" event. To achieve #2, you need to also add a change listener to the input element, and call model.set in the handler.

Here's a Fiddle with two-way binding set up in Backbone.

Regex date validation for yyyy-mm-dd

You can use this regex to get the yyyy-MM-dd format:

((?:19|20)\\d\\d)-(0?[1-9]|1[012])-([12][0-9]|3[01]|0?[1-9])

You can find example for date validation: How to validate date with regular expression.

ArrayList: how does the size increase?

Up to JDK 6 the the capacity grow with formula newCapacity = (oldCapacity * 3/2) + 1.

In JDK 7 and above the formula changes to newCapacity = oldCapacity + (oldCapacity >> 1).

So if initial capacity is 10 then new capacity will be 16 in JDK6 and 15 in above JDK7

jQuery: Check if div with certain class name exists

To test for div elements explicitly:

if( $('div.mydivclass').length ){...}

How do I use namespaces with TypeScript external modules?

Try this namespaces module

namespaceModuleFile.ts

export namespace Bookname{
export class Snows{
    name:any;
    constructor(bookname){
        console.log(bookname);
    }
}
export class Adventure{
    name:any;
    constructor(bookname){
        console.log(bookname);
    }
}
}





export namespace TreeList{
export class MangoTree{
    name:any;
    constructor(treeName){
        console.log(treeName);
    }
}
export class GuvavaTree{
    name:any;
    constructor(treeName){
        console.log(treeName);
    }
}
}

bookTreeCombine.ts

---compilation part---

import {Bookname , TreeList} from './namespaceModule';
import b = require('./namespaceModule');
let BooknameLists = new Bookname.Adventure('Pirate treasure');
BooknameLists = new Bookname.Snows('ways to write a book'); 
const TreeLis = new TreeList.MangoTree('trees present in nature');
const TreeLists = new TreeList.GuvavaTree('trees are the celebraties');

How to provide shadow to Button

Try this if this works for you

enter image description here

android:background="@drawable/drop_shadow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="3dp"
        android:paddingTop="3dp"
        android:paddingRight="4dp"
        android:paddingBottom="5dp"

Error while inserting date - Incorrect date value:

I had a different cause for this error. I tried to insert a date without using quotes and received a strange error telling me I had tried to insert a date from 2003.

My error message:

Although I was already using the YYYY-MM-DD format, I forgot to add quotes around the date. Even though it is a date and not a string, quotes are still required.

NOW() function in PHP

Short answer

$now = date_create()->format('Y-m-d H:i:s');

Read below for the long answer.




The mimicry of the MySQL NOW() function in PHP

Here is a list of ways in PHP that mimic the MySQL NOW() function.

// relative date
$now = date_create('now')->format('Y-m-d H:i:s'); // works in php 5.2 and higher  
$now = date_create()->format('Y-m-d H:i:s'); // also works in php 5.2
$now = new DateTime('now')->format('Y-m-d H:i:s'); // syntax error!!!
$now = (new DateTime('now'))->format('Y-m-d H:i:s'); // works in php 5.4 and higher   
$now = date('Y-m-d H:i:s'); // Slightly higher performance, but less usable for date/time manipulations

// From Unix timestamp
// Using date_create() with a Unix timestamp will give you a FALSE,  
// and if you try to invoke format() on a FALSE then you'll get a: 
//     Fatal error: Call to a member function format() on boolean 
// So if you work with Unix timestamps then you could use: date_create_from_format().
$unixTimeStamp = 1420070400; // 01/01/2015 00:00:00
$y2015 = date_create_from_format('U', $unixTimeStamp, timezone_open('Europe/Amsterdam'))->format('Y-m-d H:i:s');
$y2015 = date('Y-m-d H:i:s', $unixTimeStamp);

I think that date_create()->format('Y-m-d H:i:s') is the best way because this approach allows you to handle time/time-zone manipulations easier than date('Y-m-d H:i:s') and it works since php 5.2.


MySQL NOW() function

The MySQL function NOW() gives the dateTime value in this format: 'YYYY-MM-DD HH:MM:SS'. See here: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_now.

An interesting fact is that it's possible to get the datetime format by running this query: SHOW VARIABLES LIKE 'd%e_format', the result could be something like this:

Variable_name     Value     
date_format       %Y-%m-%d
datetime_format   %Y-%m-%d %H:%i:%s

The variables up here are read-only variables. So you can't change it.

I guess the MySQL NOW() function gets it's format from the datetime_format variable.




The advantages of date_create()->format() instead date() summary

The favorable facts of date_create('now')->format('Y-m-d H:i:s') over date('Y-m-d H:i:s') are:

  • easier to handle time manipulations
  • easier to handle timezones
  • o.o.p.

The disadvantages of date_create()->format() instead date()

The function date() has a slightly better performance than date_create()->format(). See benchmark test below.

$start = time();
for ($i = 0; $i <= 5000000; $i++) {
    $a = date_create('now')->format('Y-m-d H:i:s');
}
$end = time();                  
$elapsedTimeA = $end - $start;

echo 'Case A, elapsed time in seconds: ' . $elapsedTimeA;
echo '<br>';

$start = time();
for ($i = 0; $i <= 5000000; $i++) {
    $b = date('Y-m-d H:i:s');
}
$end = time();                   
$elapsedTimeB = $end - $start;

echo 'Case B, elapsed time in seconds: ' . $elapsedTimeB;
echo '<br>';
// OUTPUT
Case A, elapsed time in seconds: 31
Case B, elapsed time in seconds: 14

The upper case shows that date() is faster. However, if we change the test scenario a bit, then outcome will be different. See below:

$start = time();
$dt = date_create('now');
for ($i = 0; $i <= 5000000; $i++) {
    $a = $dt->format('Y-m-d H:i:s');
}
$end = time();                  
$elapsedTimeA = $end - $start;

echo 'Case A, elapsed time in seconds: ' . $elapsedTimeA;
echo '<br>';

$start = time();
for ($i = 0; $i <= 5000000; $i++) {
    $b = date('Y-m-d H:i:s');
}
$end = time();                   
$elapsedTimeB = $end - $start;

echo 'Case B, elapsed time in seconds: ' . $elapsedTimeB;
echo '<br>';
// OUTPUT
Case A, elapsed time in seconds: 14
Case B, elapsed time in seconds: 15

The DateTime method: format() is faster here than date().




The advantages of date_create()->format() instead date() detailed

Read on for the detailed explanation.

easier to handle time manipulations

date_create() accepts a relative date/time format (like now, yesterday or +1 day) see this link, example:

$tomorrow = date_create('+1 day')->format('Y-m-d H:i:s'); 

date() accepts a relative date/time format as well, like this:

$tomorrow = date('Y-m-d H:i:s', strtotime('+1 day'));
$tomorrow = date('Y-m-d H:i:s', (time() + 86400)); // 86400 seconds = 1 day

easier to handle timezones

When timezones matter then the usage of date_create()->format() makes a lot more sense then date() because date() uses the default time zone which is configured in php.ini at the date.timezone directive. Link: http://php.net/manual/en/datetime.configuration.php#ini.date.timezone .

It is possible to change the timezone during run-time. Example:

date_default_timezone_set('Asia/Tokyo');.

The downside of that is that it will affect all date/time functions. This problem doesn't exists if you are using date_create()->format() in combination with timezone_open().

PHP supports major timezones. The funny thing is that it even supports the Arctic circle, and Antarctica. Have you ever heard about Longyearbyen? If not, then don't worry, neither did I until I read the official PHP documentation.

$nowLongyearbyen = date_create('now', timezone_open('Arctic/Longyearbyen'))->format('Y-m-d H:i:s');

See a list of all supported timezones: http://php.net/manual/en/timezones.php.

o.o.p.

O.O.P. uses state-full Objects. So I prefer to think in this way:

// Create a DateTime Object. 
// Use the DateTime that applies for tomorrow.
// Give me the datetime in format 'Y-m-d H:i:s'
$tomorrow = date_create('+1 day')->format('Y-m-d H:i:s'); 

Then to think in this way:

// Give me a date time string in format 'Y-m-d H:i:s', 
// use strtotime() to calculate the Unix timestamp that applies for tomorrow.
$tomorrow = date('Y-m-d H:i:s', strtotime('+1 day'));

Therefore I would say that the date_create()->format() approach is more readable to me then date().




date_create() VS new DateTime()

The favorable facts of date_create() over new DateTime() are:

  • Namespaces

Namespaces

If you work in a namespace and want to initialise a DateTime object with the new keyword, then you have to do it like this:

namespace my_namespace;

// The backslash must be used if you are in a namespace.
// Forgetting about the backslash results in a fatal error.
$dt = new \DateTime();

There is nothing wrong with this, but the downside of the above is that people forget sporadically about the backslash. By using the date_create() constructor function you don't have to worry about namespaces.

$dt = date_create(); // in or not in a namespace it works in both situations




Example of date_create()->format()

I use this approach for my projects if I have to fill an array. Like this:

$array = array(
    'name' => 'John',
    'date_time' => date_create('now')->format('Y-m-d H:i:s'), // uses the default timezone
    'date_time_japan' => date_create('now', timezone_open('Asia/Tokyo'))->format('Y-m-d H:i:s'),
);

How to import existing Android project into Eclipse?

I had the problem of getting errors when checking out an Android project from SVN. This is what I did and the whole thing settled down.
1. checkout the project from SVN as we normally do any other project
2. right click and get properties of the project
3. In the java build path->order and export tab select the android API and OK it

this removed all the project issues
so far so good but not sure if this is the 100% correct method

How to rotate a 3D object on axis three.js?

Here are the two functions I use. They are based on matrix rotations. and can rotate around arbitrary axes. To rotate using the world's axes you would want to use the second function rotateAroundWorldAxis().

// Rotate an object around an arbitrary axis in object space
var rotObjectMatrix;
function rotateAroundObjectAxis(object, axis, radians) {
    rotObjectMatrix = new THREE.Matrix4();
    rotObjectMatrix.makeRotationAxis(axis.normalize(), radians);

    // old code for Three.JS pre r54:
    // object.matrix.multiplySelf(rotObjectMatrix);      // post-multiply
    // new code for Three.JS r55+:
    object.matrix.multiply(rotObjectMatrix);

    // old code for Three.js pre r49:
    // object.rotation.getRotationFromMatrix(object.matrix, object.scale);
    // old code for Three.js r50-r58:
    // object.rotation.setEulerFromRotationMatrix(object.matrix);
    // new code for Three.js r59+:
    object.rotation.setFromRotationMatrix(object.matrix);
}

var rotWorldMatrix;
// Rotate an object around an arbitrary axis in world space       
function rotateAroundWorldAxis(object, axis, radians) {
    rotWorldMatrix = new THREE.Matrix4();
    rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);

    // old code for Three.JS pre r54:
    //  rotWorldMatrix.multiply(object.matrix);
    // new code for Three.JS r55+:
    rotWorldMatrix.multiply(object.matrix);                // pre-multiply

    object.matrix = rotWorldMatrix;

    // old code for Three.js pre r49:
    // object.rotation.getRotationFromMatrix(object.matrix, object.scale);
    // old code for Three.js pre r59:
    // object.rotation.setEulerFromRotationMatrix(object.matrix);
    // code for r59+:
    object.rotation.setFromRotationMatrix(object.matrix);
}

So you should call these functions within your anim function (requestAnimFrame callback), resulting in a rotation of 90 degrees on the x-axis:

var xAxis = new THREE.Vector3(1,0,0);
rotateAroundWorldAxis(mesh, xAxis, Math.PI / 180);

How do I iterate over a JSON structure?

Use for...of:

_x000D_
_x000D_
var mycars = [{name:'Susita'}, {name:'BMW'}];

for (var car of mycars) 
{
  document.write(car.name + "<br />");
}
_x000D_
_x000D_
_x000D_

Result:

Susita
BMW

Python datetime to string without microsecond component

I usually do:

import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0)  # To print now without microsecond.

# To print now:
print(now)

output:

2019-01-13 14:40:28

How to properly compare two Integers in Java?

We should always go for equals() method for comparison for two integers.Its the recommended practice.

If we compare two integers using == that would work for certain range of integer values (Integer from -128 to 127) due to JVM's internal optimisation.

Please see examples:

Case 1:

Integer a = 100; Integer b = 100;

if (a == b) {
    System.out.println("a and b are equal");
} else {
   System.out.println("a and b are not equal");
}

In above case JVM uses value of a and b from cached pool and return the same object instance(therefore memory address) of integer object and we get both are equal.Its an optimisation JVM does for certain range values.

Case 2: In this case, a and b are not equal because it does not come with the range from -128 to 127.

Integer a = 220; Integer b = 220;

if (a == b) {
    System.out.println("a and b are equal");
} else {
   System.out.println("a and b are not equal");
}

Proper way:

Integer a = 200;             
Integer b = 200;  
System.out.println("a == b? " + a.equals(b)); // true

I hope this helps.

Java 8: merge lists with stream API

In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)

When to use AtomicReference in Java?

I won't talk much. Already my respected fellow friends have given their valuable input. The full fledged running code at the last of this blog should remove any confusion. It's about a movie seat booking small program in multi-threaded scenario.

Some important elementary facts are as follows. 1> Different threads can only contend for instance and static member variables in the heap space. 2> Volatile read or write are completely atomic and serialized/happens before and only done from memory. By saying this I mean that any read will follow the previous write in memory. And any write will follow the previous read from memory. So any thread working with a volatile will always see the most up-to-date value. AtomicReference uses this property of volatile.

Following are some of the source code of AtomicReference. AtomicReference refers to an object reference. This reference is a volatile member variable in the AtomicReference instance as below.

private volatile V value;

get() simply returns the latest value of the variable (as volatiles do in a "happens before" manner).

public final V get()

Following is the most important method of AtomicReference.

public final boolean  compareAndSet(V expect, V update) {
        return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}

The compareAndSet(expect,update) method calls the compareAndSwapObject() method of the unsafe class of Java. This method call of unsafe invokes the native call, which invokes a single instruction to the processor. "expect" and "update" each reference an object.

If and only if the AtomicReference instance member variable "value" refers to the same object is referred to by "expect", "update" is assigned to this instance variable now, and "true" is returned. Or else, false is returned. The whole thing is done atomically. No other thread can intercept in between. As this is a single processor operation (magic of modern computer architecture), it's often faster than using a synchronized block. But remember that when multiple variables need to be updated atomically, AtomicReference won't help.

I would like to add a full fledged running code, which can be run in eclipse. It would clear many confusion. Here 22 users (MyTh threads) are trying to book 20 seats. Following is the code snippet followed by the full code.

Code snippet where 22 users are trying to book 20 seats.

for (int i = 0; i < 20; i++) {// 20 seats
            seats.add(new AtomicReference<Integer>());
        }
        Thread[] ths = new Thread[22];// 22 users
        for (int i = 0; i < ths.length; i++) {
            ths[i] = new MyTh(seats, i);
            ths[i].start();
        }

Following is the full running code.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class Solution {

    static List<AtomicReference<Integer>> seats;// Movie seats numbered as per
                                                // list index

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        seats = new ArrayList<>();
        for (int i = 0; i < 20; i++) {// 20 seats
            seats.add(new AtomicReference<Integer>());
        }
        Thread[] ths = new Thread[22];// 22 users
        for (int i = 0; i < ths.length; i++) {
            ths[i] = new MyTh(seats, i);
            ths[i].start();
        }
        for (Thread t : ths) {
            t.join();
        }
        for (AtomicReference<Integer> seat : seats) {
            System.out.print(" " + seat.get());
        }
    }

    /**
     * id is the id of the user
     * 
     * @author sankbane
     *
     */
    static class MyTh extends Thread {// each thread is a user
        static AtomicInteger full = new AtomicInteger(0);
        List<AtomicReference<Integer>> l;//seats
        int id;//id of the users
        int seats;

        public MyTh(List<AtomicReference<Integer>> list, int userId) {
            l = list;
            this.id = userId;
            seats = list.size();
        }

        @Override
        public void run() {
            boolean reserved = false;
            try {
                while (!reserved && full.get() < seats) {
                    Thread.sleep(50);
                    int r = ThreadLocalRandom.current().nextInt(0, seats);// excludes
                                                                            // seats
                                                                            //
                    AtomicReference<Integer> el = l.get(r);
                    reserved = el.compareAndSet(null, id);// null means no user
                                                            // has reserved this
                                                            // seat
                    if (reserved)
                        full.getAndIncrement();
                }
                if (!reserved && full.get() == seats)
                    System.out.println("user " + id + " did not get a seat");
            } catch (InterruptedException ie) {
                // log it
            }
        }
    }

}    

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

Fill remaining vertical space with CSS using display:flex

Use the flex-grow property to the main content div and give the dispaly: flex; to its parent;

_x000D_
_x000D_
body {_x000D_
    height: 100%;_x000D_
    position: absolute;_x000D_
    margin: 0;_x000D_
}_x000D_
section {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction : column;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  flex: 1; /* or flex-grow: 1  */;_x000D_
  overflow-x: auto;_x000D_
  background: gold;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
  min-height: 60px;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

How to see docker image contents

With Docker EE for Windows (17.06.2-ee-6 on Hyper-V Server 2016) all contents of Windows Containers can be examined at C:\ProgramData\docker\windowsfilter\ path of the host OS.

No special mounting needed.

Folder prefix can be found by container id from docker ps -a output.

How can I match on an attribute that contains a certain string?

To add onto bobince's answer... If whatever tool/library you using uses Xpath 2.0, you can also do this:

//*[count(index-of(tokenize(@class, '\s+' ), $classname)) = 1]

count() is apparently needed because index-of() returns a sequence of each index it has a match at in the string.

How to create a jar with external libraries included in Eclipse?

While exporting your source into a jar, make sure you select runnable jar option from the options. Then select if you want to package all the dependency jars or just include them directly in the jar file. It depends on the project that you are working on.

You then run the jar directly by java -jar example.jar.

How to describe "object" arguments in jsdoc?

By now there are 4 different ways to document objects as parameters/types. Each has its own uses. Only 3 of them can be used to document return values, though.

For objects with a known set of properties (Variant A)

/**
 * @param {{a: number, b: string, c}} myObj description
 */

This syntax is ideal for objects that are used only as parameters for this function and don't require further description of each property. It can be used for @returns as well.

For objects with a known set of properties (Variant B)

Very useful is the parameters with properties syntax:

/**
 * @param {Object} myObj description
 * @param {number} myObj.a description
 * @param {string} myObj.b description
 * @param {} myObj.c description
 */

This syntax is ideal for objects that are used only as parameters for this function and that require further description of each property. This can not be used for @returns.

For objects that will be used at more than one point in source

In this case a @typedef comes in very handy. You can define the type at one point in your source and use it as a type for @param or @returns or other JSDoc tags that can make use of a type.

/**
 * @typedef {Object} Person
 * @property {string} name how the person is called
 * @property {number} age how many years the person lived
 */

You can then use this in a @param tag:

/**
 * @param {Person} p - Description of p
 */

Or in a @returns:

/**
 * @returns {Person} Description
 */

For objects whose values are all the same type

/**
 * @param {Object.<string, number>} dict
 */

The first type (string) documents the type of the keys which in JavaScript is always a string or at least will always be coerced to a string. The second type (number) is the type of the value; this can be any type. This syntax can be used for @returns as well.

Resources

Useful information about documenting types can be found here:

https://jsdoc.app/tags-type.html

PS:

to document an optional value you can use []:

/**
 * @param {number} [opt_number] this number is optional
 */

or:

/**
 * @param {number|undefined} opt_number this number is optional
 */

Looping through array and removing items, without breaking for loop

for (i = 0, len = Auction.auctions.length; i < len; i++) {
    auction = Auction.auctions[i];
    Auction.auctions[i]['seconds'] --;
    if (auction.seconds < 0) {
        Auction.auctions.splice(i, 1);
        i--;
        len--;
    }
}

Network tools that simulate slow network connection

In case you need to simulate network connection quality when developing for Windows Phone, you might give a try to a Visual Studio built-in tool called Simulation Dashboard (more details here http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206952(v=vs.105).aspx):

You can use the Simulation Dashboard in Visual Studio to test your app for these connection problems, and to help prevent users from encountering scenarios like the following:

  • High-resolution music or videos stutter or freeze while streaming, or take a long time to download over a low-bandwidth connection.
  • Calls to a web service fail with a timeout.
  • The app crashes when no network is available.
  • Data transfer does not resume when the network connection is lost and then restored.
  • The user’s battery is drained by a streaming app that uses the network inefficiently.
  • Mapping the user’s route is interrupted in a navigation app.

...

In Visual Studio, on the Tools menu, open Simulation Dashboard. Find the network simulation section of the dashboard and check the Enable Network Simulation check box.

Get a list of all git commits, including the 'lost' ones

I've had luck recovering the commit by looking at the reflog, which was located at .git/logs/HEAD

I then had to scoll down to the end of the file, and I found the commit I just lost.

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Why does the Visual Studio editor show dots in blank spaces?

I had the same problem and resolved by pressing Ctrl + R , Ctrl + W.

Bootstrap dropdown sub menu missing

I bumped with this issue a few days ago. I tried many solutions and none really worked for me on the end i ended up creating an extenion/override of the dropdown code of bootstrap. It is a copy of the original code with changes to the closeMenus function.

I think it is a good solution since it doesn't affects the core classes of bootstrap js.

You can check it out on gihub: https://github.com/djokodonev/bootstrap-multilevel-dropdown

Django CSRF check failing with an Ajax POST request

One CSRF token is assigned to every session ( i.e. every time you log in). So before you wish to get some data entered by user and send that as ajax call to some function which is protected by csrf_protect decorator, try to find the functions that are being called before you are getting this data from user. E.g. some template must be being rendered on which your user is entering data. That template is being rendered by some function. In this function you can get csrf token as follows: csrf = request.COOKIES['csrftoken'] Now pass this csrf value in context dictionary against which template in question is being rendered. Now in that template write this line: Now in your javascript function, before making ajax request, write this: var csrf = $('#csrf').val() this will pick value of token passed to template and store it in variable csrf. Now while making ajax call, in your post data, pass this value as well : "csrfmiddlewaretoken": csrf

This will work even if you are not implementing django forms.

In fact, logic over here is : You need token which you can get from request. So you just need to figure out the function being called immediately after log in. Once you have this token, either make another ajax call to get it or pass it to some template which is accessible by your ajax.

css divide width 100% to 3 column

.selector{width:calc(100% / 3);}

svn list of files that are modified in local copy

If you only want the filenames and also want any files that have been added (A).

svn st | grep ^[AM] | cut -c9-

Note: The first 7 columns are each one character wide followed by a space then the filename.

How to crop a CvMat in OpenCV?

I know this question is already solved.. but there is a very easy way to crop. you can just do it in one line-

Mat cropedImage = fullImage(Rect(X,Y,Width,Height));

CSS Outside Border

I shared two solutions depending on your needs:

<style type="text/css" ref="stylesheet">
  .border-inside-box {
    border: 1px solid black;
  }
  .border-inside-box-v1 {
    outline: 1px solid black; /* 'border-radius' not available */
  }
  .border-outside-box-v2 {
    box-shadow: 0 0 0 1px black; /* 'border-style' not available (dashed, solid, etc) */
  }
</style>

example: https://codepen.io/danieldd/pen/gObEYKj

Python: create dictionary using dict() with integer keys?

Yes, but not with that version of the constructor. You can do this:

>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}

There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."

Select 50 items from list at random to write to file

If the list is in random order, you can just take the first 50.

Otherwise, use

import random
random.sample(the_list, 50)

random.sample help text:

sample(self, population, k) method of random.Random instance
    Chooses k unique random elements from a population sequence.

    Returns a new list containing elements from the population while
    leaving the original population unchanged.  The resulting list is
    in selection order so that all sub-slices will also be valid random
    samples.  This allows raffle winners (the sample) to be partitioned
    into grand prize and second place winners (the subslices).

    Members of the population need not be hashable or unique.  If the
    population contains repeats, then each occurrence is a possible
    selection in the sample.

    To choose a sample in a range of integers, use xrange as an argument.
    This is especially fast and space efficient for sampling from a
    large population:   sample(xrange(10000000), 60)

Windows Forms - Enter keypress activates submit button?

You can designate a button as the "AcceptButton" in the Form's properties and that will catch any "Enter" keypresses on the form and route them to that control.

See How to: Designate a Windows Forms Button as the Accept Button Using the Designer and note the few exceptions it outlines (multi-line text-boxes, etc.)