Programs & Examples On #Jquery selectors

Selectors can be used in jQuery to match a set of elements in a document. Most CSS selectors are implemented, as well as a set of custom ones.

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

                <div id="tabs" style="width: 290px">
                    <ul >
                        <li><a id="myTab1" href="#tabs-1" style="color: Green">Báo cáo chu?n</a></li>
                        <li><a id="myTab2" href="#tabs-2" style="color: Green">Báo cáo m? r?ng</a></li>
                    </ul>
                    <div id="tabs-1" style="overflow-x: auto">
                        <ul class="nav">

                            <li><a href="@Url.Content("~/Report/ReportDate")"><span class=""></span>Báo cáo theo ngày</a></li>

                        </ul>
                    </div>
                    <div id="tabs-2" style="overflow-x: auto; height: 290px">
                        <ul class="nav">

                            <li><a href="@Url.Content("~/Report/PetrolReport#tabs-2")"><span class=""></span>Báo cáo nhiên li?u</a></li>
                        </ul>
                    </div>
                </div>


        var index = $("#tabs div").index($("#tabs-1" ));
        $("#tabs").tabs("select", index);
       $("#tabs-1")[0].classList.remove("ui-tabs-hide");

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

I made use of variables defined in :root inside CSS to modify the :after (the same applies to :before) pseudo-element, in particular to change the background-color value for a styled anchor defined by .sliding-middle-out:hover:after and the content value for another anchor (#reference) in the following demo that generates random colors by using JavaScript/jQuery:

HTML

<a href="#" id="changeColor" class="sliding-middle-out" title="Generate a random color">Change link color</a>
<span id="log"></span>
<h6>
  <a href="https://stackoverflow.com/a/52360188/2149425" id="reference" class="sliding-middle-out" target="_blank" title="Stack Overflow topic">Reference</a>
</h6>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/davidmerfield/randomColor/master/randomColor.js"></script>

CSS

:root {
    --anchorsFg: #0DAFA4;
}
a, a:visited, a:focus, a:active {
    text-decoration: none;
    color: var(--anchorsFg);
    outline: 0;
    font-style: italic;

    -webkit-transition: color 250ms ease-in-out;
    -moz-transition: color 250ms ease-in-out;
    -ms-transition: color 250ms ease-in-out;
    -o-transition: color 250ms ease-in-out;
    transition: color 250ms ease-in-out;
}
.sliding-middle-out {
    display: inline-block;
    position: relative;
    padding-bottom: 1px;
}
.sliding-middle-out:after {
    content: '';
    display: block;
    margin: auto;
    height: 1px;
    width: 0px;
    background-color: transparent;

    -webkit-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -moz-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -ms-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -o-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
}
.sliding-middle-out:hover:after {
    width: 100%;
    background-color: var(--anchorsFg);
    outline: 0;
}
#reference {
  margin-top: 20px;
}
.sliding-middle-out:before {
  content: attr(data-content);
  display: attr(data-display);
}

JS/jQuery

var anchorsFg = randomColor();
$( ".sliding-middle-out" ).hover(function(){
    $( ":root" ).css({"--anchorsFg" : anchorsFg});
});

$( "#reference" ).hover(
 function(){
    $(this).attr("data-content", "Hello World!").attr("data-display", "block").html("");
 },
 function(){
    $(this).attr("data-content", "Reference").attr("data-display", "inline").html("");
 }
);

Toggle Checkboxes on/off

if you want to toggle each box individually (or just one box works just as well):

I recommend using .each() , as it is easy to modify if you want different things to happen, and still relatively short and easy to read.

e.g. :

// toggle all checkboxes, not all at once but toggle each one for its own checked state:
$('input[type="checkbox"]').each(function(){ this.checked = ! this.checked });

// check al even boxes, uncheck all odd boxes:
$('input[type="checkbox"]').each(function(i,cb){ cb.checked = (i%2 == 0); });

// set all to checked = x and only trigger change if it actually changed:
x = true;
$('input[type="checkbox"]').each(function(){
    if(this.checked != x){ this.checked = x; $(this).change();}  
});

on a side note... not sure why everyone uses .attr() or .prop() to (un)check things.

as far as I know, element.checked has always worked the same in all browsers?

JQuery: How to get selected radio button value?

This work for me hope this will help: to get radio selected value you have to use ratio name as selector like this

selectedVal = $('input[name="radio_name"]:checked').val();

selectedVal will have the required value, change the radio_name according to yours, in your case it would b "myradiobutton"

selectedVal = $('input[name="myradiobutton"]:checked').val();

jQuery - determine if input element is textbox or select list

You could do this:

if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
    // it was an input
}

or this, which is slower, but shorter and cleaner:

if( ctrl.is('input') ) {
    // it was an input
}

If you want to be more specific, you can test the type:

if( ctrl.is('input:text') ) {
    // it was an input
}

jQuery: How to get to a particular child of a parent?

If I understood your problem correctly, $(this).parents('.box').children('.something1') Is this what you are looking for?

Get a list of checked checkboxes in a div using jQuery

If you need to get quantity of selected checkboxes:

var selected = []; // initialize array
    $('div#checkboxes input[type=checkbox]').each(function() {
       if ($(this).is(":checked")) {
           selected.push($(this));
       }
    });
var selectedQuantity = selected.length;

Get value of multiselect box using jQuery or pure JS

According to the widget's page, it should be:

var myDropDownListValues = $("#myDropDownList").multiselect("getChecked").map(function()
{
    return this.value;    
}).get();

It works for me :)

How to get child element by index in Jquery?

If you know the child element you're interested in is the first:

 $('.second').children().first();

Or to find by index:

 var index = 0
 $('.second').children().eq(index);

Get selected text from a drop-down list (select box) using jQuery

 $("#selectID option:selected").text();

Instead of #selectID you can use any jQuery selector, like .selectClass using class.

As mentioned in the documentation here.

The :selected selector works for <option> elements. It does not work for checkboxes or radio inputs; use :checked for them.

.text() As per the documentation here.

Get the combined text contents of each element in the set of matched elements, including their descendants.

So you can take text from any HTML element using the .text() method.

Refer the documentation for a deeper explanation.

JQuery - how to select dropdown item based on value

I have a different situation, where the drop down list values are already hard coded. There are only 12 districts so the jQuery Autocomplete UI control isn't populated by code.

The solution is much easier. Because I had to wade through other posts where it was assumed the control was being dynamically loaded, wasn't finding what I needed and then finally figured it out.

So where you have HTML as below, setting the selected index is set like this, note the -input part, which is in addition to the drop down id:

$('#project-locationSearch-dist-input').val('1');

                <label id="lblDistDDL" for="project-locationSearch-input-dist" title="Select a district to populate SPNs and PIDs or enter a known SPN or PID." class="control-label">District</label>
                <select id="project-locationSearch-dist" data-tabindex="1">
                    <option id="optDistrictOne" value="01">1</option>
                    <option id="optDistrictTwo" value="02">2</option>
                    <option id="optDistrictThree" value="03">3</option>
                    <option id="optDistrictFour" value="04">4</option>
                    <option id="optDistrictFive" value="05">5</option>
                    <option id="optDistrictSix" value="06">6</option>
                    <option id="optDistrictSeven" value="07">7</option>
                    <option id="optDistrictEight" value="08">8</option>
                    <option id="optDistrictNine" value="09">9</option>
                    <option id="optDistrictTen" value="10">10</option>
                    <option id="optDistrictEleven" value="11">11</option>
                    <option id="optDistrictTwelve" value="12">12</option>
                </select>

Something else figured out about the Autocomplete control is how to properly disable/empty it. We have 3 controls working together, 2 of them mutually exclusive:

//SPN
spnDDL.combobox({
    select: function (event, ui) {
        var spnVal = spnDDL.val();
        //fire search event
        $('#project-locationSearch-pid-input').val('');
        $('#project-locationSearch-pid-input').prop('disabled', true);
        pidDDL.empty(); //empty the pid list
    }
});
//get the labels so we have their tool tips to hand.
//this way we don't set id values on each label
spnDDL.siblings('label').tooltip();

//PID
pidDDL.combobox({
    select: function (event, ui) {
        var pidVal = pidDDL.val();
        //fire search event
        $('#project-locationSearch-spn-input').val('');
        $('#project-locationSearch-spn-input').prop('disabled', true);
        spnDDL.empty(); //empty the spn list
    }
});

Some of this is beyond the scope of the post and I don't know where to put it exactly. Since this is very helpful and took some time to figure out, it's being shared.

Und Also ... to enable a control like this, it's (disabled, false) and NOT (enabled, true) -- that also took a bit of time to figure out. :)

The only other thing to note, much in addition to the post, is:

    /*
Note, when working with the jQuery Autocomplete UI control,
the xxx-input control is a text input created at the time a selection
from the drop down is picked.  Thus, it's created at that point in time
and its value must be picked fresh.  Can't be put into a var and re-used
like the drop down list part of the UI control.  So you get spnDDL.empty()
where spnDDL is a var created like var spnDDL = $('#spnDDL);  But you can't
do this with the input part of the control.  Winded explanation, yes.  That's how
I have to do my notes or 6 months from now I won't know what a short hand note means
at all. :) 
*/
    //district
    $('#project-locationSearch-dist').combobox({
        select: function (event, ui) {
            //enable spn and pid drop downs
            $('#project-locationSearch-pid-input').prop('disabled', false);
            $('#project-locationSearch-spn-input').prop('disabled', false);
            //clear them of old values
            pidDDL.empty();
            spnDDL.empty();
            //get new values
            GetSPNsByDistrict(districtDDL.val());
            GetPIDsByDistrict(districtDDL.val());
        }
    });

All shared because it took too long to learn these things on the fly. Hope this is helpful.

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

document.getElementById vs jQuery $()

All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it

<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>

Online Demo! - https://codepen.io/frank-dspeed/pen/mdywbre

Get the selected value in a dropdown using jQuery.

Try:

jQuery("#availability option:selected").val();

Or to get the text of the option, use text():

jQuery("#availability option:selected").text();

More Info:

Wildcards in jQuery selectors

Try the jQuery starts-with

selector, '^=', eg

[id^="jander"]

I have to ask though, why don't you want to do this using classes?

Count immediate child div elements using jQuery

$("#foo > div") 

selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:

$("#foo > div").size()

or you can use

$("#foo > div").length

Both will return you the same result

Getting the source of a specific image element with jQuery

$('img.conversation_img[alt="example"]')
    .each(function(){
         alert($(this).attr('src'))
    });

This will display src attributes of all images of class 'conversation_img' with alt='example'

How can I exclude $(this) from a jQuery selector?

You can use the not function rather than the :not selector:

$(".content a").not(this).hide("slow")

JQuery create new select option

A really simple way to do this...

// create the option
var opt = $("<option>").val("myvalue").text("my text");

//append option to the select element
$(#my-select).append(opt);

This could be done in lots of ways, even in a single line if really you want to.

jQuery - Getting the text value of a table cell in the same row as a clicked element

You want .children() instead (documentation here):

$(this).closest('tr').children('td.two').text();

jQuery get specific option tag text

I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find... earlier):

<script type="text/javascript">
    $(document).ready(function(){
        $("select[showChoices]").each(function(){
            $(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'>&nbsp;</span>");
            doShowSelected($(this).attr('id'));//shows initial selections
        }).change(function(){
            doShowSelected($(this).attr('id'));//as user makes new selections
        });
    });
    function doShowSelected(inId){
        var aryVals=$("#"+inId).val();
        var selText="";
        for(var i=0; i<aryVals.length; i++){
            var o="#"+inId+" option[value='"+aryVals[i]+"']";
            selText+=$(o).text()+"<br>";
        }
        $("#spn"+inId).html(selText);
    }
</script>
<select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
    <option selected="selected" value=1>opt 1</option>
    <option selected="selected" value=2>opt 2</option>
    <option value=3>opt 3</option>
    <option value=4>opt 4</option>
</select>

jQuery select by attribute using AND and OR operators

JQuery uses CSS selectors to select elements, so you just need to use more than one rule by separating them with commas, as so:

a=$('[myc="blue"], [myid="1"], [myid="3"]');

Edit:

Sorry, you wanted blue and 1 or 3. How about:

a=$('[myc="blue"][myid="1"],  [myid="3"]');

Putting the two attribute selectors together gives you AND, using a comma gives you OR.

How can I change CSS display none or block property using jQuery?

(function($){
    $.fn.displayChange = function(fn){
        $this = $(this);
        var state = {};
        state.old = $this.css('display');
        var intervalID = setInterval(function(){
            if( $this.css('display') != state.old ){
                state.change = $this.css('display');
                fn(state);
                state.old = $this.css('display');
            }
        }, 100);        
    }

    $(function(){
        var tag = $('#content');
        tag.displayChange(function(obj){
            console.log(obj);
        });  
    })   
})(jQuery);

What is Join() in jQuery?

That's not a jQuery function - it's the regular Array.join function.

It converts an array to a string, putting the argument between each element.

jQuery selector to get form by name

$('form[name="frmSave"]') is correct. You mentioned you thought this would get all children with the name frmsave inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');

$('form[name="frmSave"]') literally means find all forms with the name frmSave, because there is no combinator involved.

jQuery find and replace string

var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);

How to select specific form element in jQuery?

I prefer an id descendant selector of your #form2, like this:

$("#form2 #name").val("Hello World!");

http://api.jquery.com/descendant-selector/

JQuery .on() method with multiple event handlers to one selector

I learned something really useful and fundamental from here.

chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.

It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter

function showPhotos() {
    $(this).find("span").slideToggle();
}

$(".photos")
    .on("mouseenter", "li", showPhotos)
    .on("mouseleave", "li", showPhotos);

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Get index of clicked element in collection with jQuery

$('selector').click(function (event) {
    alert($(this).index());
});

jsfiddle

Using jquery to get all checked checkboxes with a certain class name

Obligatory .map example:

var checkedVals = $('.theClass:checkbox:checked').map(function() {
    return this.value;
}).get();
alert(checkedVals.join(","));

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

I faced this issue because my selector was depend on id meanwhile I did not set id for my element

my selector was

$("#EmployeeName")

but my HTML element

<input type="text" name="EmployeeName">

so just make sure that your selector criteria are valid

How to detect if a browser is Chrome using jQuery?

if(navigator.vendor.indexOf('Goog') > -1){
  //Your code here
}

jQuery OR Selector?

Using a comma may not be sufficient if you have multiple jQuery objects that need to be joined.

The .add() method adds the selected elements to the result set:

// classA OR classB
jQuery('.classA').add('.classB');

It's more verbose than '.classA, .classB', but lets you build more complex selectors like the following:

// (classA which has <p> descendant) OR (<div> ancestors of classB)
jQuery('.classA').has('p').add(jQuery('.classB').parents('div'));

jQuery: select an element's class and id at the same time?

How about this code?

$("a.save#country")

Set selected option of select box

This would be another option:

$('.id_100 option[value=val2]').prop('selected', true);

jQuery select all except first

Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first) is slowed down by that evaluation.

An equally fast and easy to read solution is using the function version .not(":first"):

e.g.

$("li").not(":first").hide();

JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

This is only few percentage points slower than slice(1), but is very readable as "I want all except the first one".

jquery: animate scrollLeft

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate

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

    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function()
{
    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

Get second child using jQuery

How's this:

$(t).first().next()

MAJOR UPDATE:

Apart from how beautiful the answer looks, you must also give a thought to the performance of the code. Therefore, it is also relavant to know what exactly is in the $(t) variable. Is it an array of <TD> or is it a <TR> node with several <TD>s inside it? To further illustrate the point, see the jsPerf scores on a <ul> list with 50 <li> children:

http://jsperf.com/second-child-selector

The $(t).first().next() method is the fastest here, by far.

But, on the other hand, if you take the <tr> node and find the <td> children and and run the same test, the results won't be the same.

Hope it helps. :)

Multiple selector chaining in jQuery?

like:

$('#Create .myClass, #Edit .myClass').plugin({ 
    options: here
});

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. An alternative to this combinator is the .add() method.

jQuery first child of "this"

element.children().first();

Find all children and get first of them.

jquery $('.class').each() how many items?

Use the .length property. It is not a function.

alert($('.class').length); // alerts a nonnegative number 

What is fastest children() or find() in jQuery?

None of the other answers dealt with the case of using .children() or .find(">") to only search for immediate children of a parent element. So, I created a jsPerf test to find out, using three different ways to distinguish children.

As it happens, even when using the extra ">" selector, .find() is still a lot faster than .children(); on my system, 10x so.

So, from my perspective, there does not appear to be much reason to use the filtering mechanism of .children() at all.

jQuery selector first td of each row

try

var children = null;
$('tr').each(function(){
    var td = $(this).children('td:first');
    if(children == null)
        children = td;
    else
        children.add(td);
});

// children should now hold all the first td elements

jQuery Selector: Id Ends With?

Since this is ASP.NET, you can simply use the ASP <%= %> tag to print the generated ClientID of txtTitle:

$('<%= txtTitle.ClientID %>')

This will result in...

$('ctl00$ContentBody$txtTitle')

... when the page is rendered.

Note: In Visual Studio, Intellisense will yell at you for putting ASP tags in JavaScript. You can ignore this as the result is valid JavaScript.

jQuery - Click event on <tr> elements with in a table and getting <td> element values

<script>
jQuery(document).ready(function() {
    jQuery("tr").click(function(){
       alert("Click! "+ jQuery(this).find('td').html());
    });
});
</script>

Combining a class selector and an attribute selector with jQuery

I think you just need to remove the space. i.e.

$(".myclass[reference=12345]").css('border', '#000 solid 1px');

There is a fiddle here http://jsfiddle.net/xXEHY/

jQuery delete all table rows except first

If it were me, I'd probably boil it down to a single selector:

$('someTableSelector tr:not(:first)').remove();

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

addID in jQuery?

do you mean a method?

$('div.foo').attr('id', 'foo123');

Just be careful that you don't set multiple elements to the same ID.

jQuery selectors on custom data attributes using HTML5

$("ul[data-group='Companies'] li[data-company='Microsoft']") //Get all elements with data-company="Microsoft" below "Companies"

$("ul[data-group='Companies'] li:not([data-company='Microsoft'])") //get all elements with data-company!="Microsoft" below "Companies"

Look in to jQuery Selectors :contains is a selector

here is info on the :contains selector

How to get the children of the $(this) selector?

The jQuery constructor accepts a 2nd parameter called context which can be used to override the context of the selection.

jQuery("img", this);

Which is the same as using .find() like this:

jQuery(this).find("img");

If the imgs you desire are only direct descendants of the clicked element, you can also use .children():

jQuery(this).children("img");

Changing the child element's CSS when the parent is hovered

If you're using Twitter Bootstrap styling and base JS for a drop down menu:

.child{ display:none; }
.parent:hover .child{ display:block; }

This is the missing piece to create sticky-dropdowns (that aren't annoying)

  • The behavior is to:
    1. Stay open when clicked, close when clicking again anywhere else on the page
    2. Close automatically when the mouse scrolls out of the menu's elements.

How to generate UL Li list from string array using jquery?

Even better approach using array's join method

var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var list = '<ul class="myList"><li class="ui-menu-item" role="menuitem"><a class="ui-all" tabindex="-1">' + countries.join('</a></li><li>') + '</li></ul>';

Select element by exact match of its content

Try add a extend pseudo function:

$.expr[':'].textEquals = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().match("^" + arg + "$");
    };
});

Then you can do:

$('p:textEquals("Hello World")');

Check if any ancestor has a class using jQuery

if ($elem.parents('.left').length) {

}

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

You could try jQuery UI's .position method.

$("#mydiv").position({
  of: $('#mydiv').parent(),
  my: 'left+200 top+200',
  at: 'left top'
});

Check the working demo.

jQuery selector regular expressions

These can be helpful.

If you're finding by Contains then it'll be like this

    $("input[id*='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Starts With then it'll be like this

    $("input[id^='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Ends With then it'll be like this

     $("input[id$='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is not a given string

    $("input[id!='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which name contains a given word, delimited by spaces

     $("input[name~='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen

     $("input[id|='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

jQuery - passing value from one input to another

It's simpler if you modify your HTML a little bit:

<label for="first_name">First Name</label>
<input type="text" id="name" name="name" />

<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" />

<label for="firstname">Firstname</label>
<input type="text" id="firstname" name="firstname" disabled="disabled" />

then it's relatively simple

$(document).ready(function() { 
    $('#name').change(function() {
      $('#firstname').val($('#name').val());
    });
});

jQuery scrollTop not working in Chrome but working in Firefox

I had a same problem with scrolling in chrome. So i removed this lines of codes from my style file.

html{height:100%;}
body{height:100%;}

Now i can play with scroll and it works:

var pos = 500;
$("html,body").animate({ scrollTop: pos }, "slow");

Selecting multiple classes with jQuery

Have you tried this?

$('.myClass, .myOtherClass').removeClass('theclass');

How can I get the ID of an element using jQuery?

Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.

var generatedIdCounter = 0;

$.fn.id = function() {
    var identifier = this.attr('id');

    if(!identifier) {
        generatedIdCounter++;
        identifier = 'isGenerated_' + generatedIdCounter;

        this.attr('id', identifier);
    }

    return identifier;
}

How to use:

$('.classname').id();

$('#elementId').id();

jQuery how to find an element based on a data-attribute value?

You have to inject the value of current into an Attribute Equals selector:

$("ul").find(`[data-slide='${current}']`)

For older JavaScript environments (ES5 and earlier):

$("ul").find("[data-slide='" + current + "']"); 

jquery find class and get the value

var myVar = $("#start").find('myClass').val();

needs to be

var myVar = $("#start").find('.myClass').val();

Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>.

JQuery show/hide when hover

('.cat').hover(
  function () {
    $(this).show();
  }, 
  function () {
    $(this).hide();
  }
);

It's the same for the others.

For the smooth fade in you can use fadeIn and fadeOut

Not class selector in jQuery

You need the :not() selector:

$('div[class^="first-"]:not(.first-bar)')

or, alternatively, the .not() method:

$('div[class^="first-"]').not('.first-bar');

How can I select item with class within a DIV?

Try this

$("#mydiv div.myclass")

How can I get selector from jQuery object

How about:

var selector = "*"
$(selector).click(function() {
    alert(selector);
});

I don't believe jQuery store the selector text that was used. After all, how would that work if you did something like this:

$("div").find("a").click(function() {
    // what would expect the 'selector' to be here?
});

How can I select an element with multiple classes in jQuery?

The problem you're having, is that you are using a Group Selector, whereas you should be using a Multiples selector! To be more specific, you're using $('.a, .b') whereas you should be using $('.a.b').

For more information, see the overview of the different ways to combine selectors herebelow!


Group Selector : ","

Select all <h1> elements AND all <p> elements AND all <a> elements :

$('h1, p, a')

Multiples selector : "" (no character)

Select all <input> elements of type text, with classes code and red :

$('input[type="text"].code.red')

Descendant Selector : " " (space)

Select all <i> elements inside <p> elements:

$('p i')

Child Selector : ">"

Select all <ul> elements that are immediate children of a <li> element:

$('li > ul')

Adjacent Sibling Selector : "+"

Select all <a> elements that are placed immediately after <h2> elements:

$('h2 + a')

General Sibling Selector : "~"

Select all <span> elements that are siblings of <div> elements:

$('div ~ span')

jQuery vs document.querySelectorAll

If you are optimizing your page for IE8 or newer, you should really consider whether you need jquery or not. Modern browsers have many assets natively which jquery provides.

If you care for performance, you can have incredible performance benefits (2-10 faster) using native javascript: http://jsperf.com/jquery-vs-native-selector-and-element-style/2

I transformed a div-tagcloud from jquery to native javascript (IE8+ compatible), the results are impressive. 4 times faster with just a little overhead.

                    Number of lines       Execution Time                       
Jquery version :        340                    155ms
Native version :        370                    27ms

You Might Not Need Jquery provides a really nice overview, which native methods replace for which browser version.

http://youmightnotneedjquery.com/


Appendix: Further speed comparisons how native methods compete to jquery

jQuery’s .bind() vs. .on()

The direct methods and .delegate are superior APIs to .on and there is no intention of deprecating them.

The direct methods are preferable because your code will be less stringly typed. You will get immediate error when you mistype an event name rather than a silent bug. In my opinion, it's also easier to write and read click than on("click"

The .delegate is superior to .on because of the argument's order:

$(elem).delegate( ".selector", {
    click: function() {
    },
    mousemove: function() {
    },
    mouseup: function() {
    },
    mousedown: function() {
    }
});

You know right away it's delegated because, well, it says delegate. You also instantly see the selector.

With .on it's not immediately clear if it's even delegated and you have to look at the end for the selector:

$(elem).on({
    click: function() {
    },
    mousemove: function() {
    },
    mouseup: function() {
    },
    mousedown: function() {
    }
}, "selector" );

Now, the naming of .bind is really terrible and is at face value worse than .on. But .delegate cannot do non-delegated events and there are events that don't have a direct method, so in a rare case like this it could be used but only because you want to make a clean separation between delegated and non-delegated events.

jQuery - selecting elements from inside a element

....but $('span', $('#foo')); doesn't work?

This method is called as providing selector context.

In this you provide a second argument to the jQuery selector. It can be any css object string just like you would pass for direct selecting or a jQuery element.

eg.

$("span",".cont1").css("background", '#F00');

The above line will select all spans within the container having the class named cont1.

DEMO

jQuery hasClass() - check for more than one class

How about this?

if (element.hasClass("class1 class2")

jQuery selector for the label of a checkbox

This should do it:

$("label[for=comedyclubs]")

If you have non alphanumeric characters in your id then you must surround the attr value with quotes:

$("label[for='comedy-clubs']")

hide/show a image in jquery

With image class name:

$('.img_class').hide(); // to hide image
$('.img_class').show(); // to show image

With image Id :

$('#img_id').hide(); // to hide image
$('#img_id').show(); // to show image

Check if value is in select list with JQuery

I know this is kind of an old question by this one works better.

if(!$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"] option[value="'+data['item'][i]['id']+'"]')[0]){
  //Doesn't exist, so it isn't a repeat value being added. Go ahead and append.
  $('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"]').append(option);
}

As you can see in this example, I am searching by unique tags data-dropdown name and the value of the selected option. Of course you don't need these for these to work but I included them so that others could see you can search multi values, etc.

How can I select an element by name with jQuery?

If you have something like:

<input type="checkbox" name="mycheckbox" value="11" checked="">
<input type="checkbox" name="mycheckbox" value="12">

You can read all like this:

jQuery("input[name='mycheckbox']").each(function() {
    console.log( this.value + ":" + this.checked );
});

The snippet:

_x000D_
_x000D_
jQuery("input[name='mycheckbox']").each(function() {_x000D_
  console.log( this.value + ":" + this.checked );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="mycheckbox" value="11" checked="">_x000D_
<input type="checkbox" name="mycheckbox" value="12">
_x000D_
_x000D_
_x000D_

jQuery : select all element with custom attribute

Use the "has attribute" selector:

$('p[MyTag]')

Or to select one where that attribute has a specific value:

$('p[MyTag="Sara"]')

There are other selectors for "attribute value starts with", "attribute value contains", etc.

How to use placeholder as default value in select2 framework

This worked for me:

$('#SelectListId').prepend('<option selected></option>').select2({
    placeholder: "Select Month",
    allowClear: true
});

Hope this help :)

How can I get the corresponding table header (th) from a table cell (td)?

var $th = $td.closest('tbody').prev('thead').find('> tr > th:eq(' + $td.index() + ')');

Or a little bit simplified

var $th = $td.closest('table').find('th').eq($td.index());

How to get all child inputs of a div element (jQuery)

here is my approach:

You can use it in other event.

_x000D_
_x000D_
var id;_x000D_
$("#panel :input").each(function(e){ _x000D_
  id = this.id;_x000D_
  // show id _x000D_
  console.log("#"+id);_x000D_
  // show input value _x000D_
  console.log(this.value);_x000D_
  // disable input if you want_x000D_
  //$("#"+id).prop('disabled', true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="panel">_x000D_
  <table>_x000D_
    <tr>_x000D_
       <td><input id="Search_NazovProjektu" type="text" value="Naz Val" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
       <td><input id="Search_Popis" type="text" value="Po Val" /></td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery or CSS selector to select all IDs that start with some string

Normally you would select IDs using the ID selector #, but for more complex matches you can use the attribute-starts-with selector (as a jQuery selector, or as a CSS3 selector):

div[id^="player_"]

If you are able to modify that HTML, however, you should add a class to your player divs then target that class. You'll lose the additional specificity offered by ID selectors anyway, as attribute selectors share the same specificity as class selectors. Plus, just using a class makes things much simpler.

Trigger an event on `click` and `enter`

$('#form').keydown(function(e){
    if (e.keyCode === 13) { // If Enter key pressed
        $(this).trigger('submit');
    }
});

How to get all options of a select using jQuery?

You can take all your "selected values" by the name of the checkboxes and present them in a sting separated by ",".

A nice way to do this is to use jQuery's $.map():

var selected_val = $.map($("input[name='d_name']:checked"), function(a)
    {
        return a.value;
    }).join(',');

alert(selected_val);

jQuery to loop through elements with the same class

More precise:

$.each($('.testimonal'), function(index, value) { 
    console.log(index + ':' + value); 
});

How can I know which radio button is selected via jQuery?

This should work:

$("input[name='radioName']:checked").val()

Note the "" usaged around the input:checked and not '' like the Peter J's solution

jQuery: Get selected element tag name

nodeName will give you the tag name in uppercase, while localName will give you the lower case.

$("yourelement")[0].localName 

will give you : yourelement instead of YOURELEMENT

Get the value in an input text box

To get the textbox value, you can use the jQuery val() function.

For example,

$('input:textbox').val() – Get textbox value.

$('input:textbox').val("new text message") – Set the textbox value.

use jQuery's find() on JSON object

Another option I wanted to mention, you could convert your data into XML and then use jQuery.find(":id='A'") the way you wanted.

There are jQuery plugins to that effect, like json2xml.

Probably not worth the conversion overhead, but that's a one time cost for static data, so it might be useful.

How can I detect if a selector returns null?

My preference, and I have no idea why this isn't already in jQuery:

$.fn.orElse = function(elseFunction) {
  if (!this.length) {
    elseFunction();
  }
};

Used like this:

$('#notAnElement').each(function () {
  alert("Wrong, it is an element")
}).orElse(function() {
  alert("Yup, it's not an element")
});

Or, as it looks in CoffeeScript:

$('#notAnElement').each ->
  alert "Wrong, it is an element"; return
.orElse ->
  alert "Yup, it's not an element"

Access the css ":after" selector with jQuery

If you use jQuery built-in after() with empty value it will create a dynamic object that will match your :after CSS selector.

$('.active').after().click(function () {
    alert('clickable!');
});

See the jQuery documentation.

jQuery select element in parent window

You can also use,

parent.jQuery("#testdiv").attr("style", content from form);

jQuery: Check if div with certain class name exists

In Jquery you can use like this.

if ($(".className")[0]){

   // Do something if class exists

} else {

// Do something if class does not exist

}

With JavaScript

if (document.getElementsByClassName("className").length > 0) {

// Do something if class exists

}else{

    // Do something if class does not exist......

}

Jquery bind double click and single click separately

If you don't want to create separate variables to manage the state, you can check this answer https://stackoverflow.com/a/65620562/4437468

Get text of the selected option with jQuery

Change your selector to

val = j$("#select_2 option:selected").text();

You're selecting the <select> instead of the <option>

Testing if a checkbox is checked with jQuery

I've came through a case recently where I've needed check value of checkbox when user clicked on button. The only proper way to do so is to use prop() attribute.

var ansValue = $("#ans").prop('checked') ? $("#ans").val() : 0;

this worked in my case maybe someone will need it.

When I've tried .attr(':checked') it returned checked but I wanted boolean value and .val() returned value of attribute value.

jQuery selector for inputs with square brackets in the name attribute

If the selector is contained within a variable, the code below may be helpful:

selector_name = $this.attr('name');
//selector_name = users[0][first:name]

escaped_selector_name = selector_name.replace(/(:|\.|\[|\])/g,'\\$1');
//escaped_selector_name = users\\[0\\]\\[first\\:name\\]

In this case we prefix all special characters with double backslash.

jQuery Set Select Index

$('#selectBox option').get(3).attr('selected', 'selected')

When using the above I kept getting errors in webkit (Chrome) saying:

"Uncaught TypeError: Object # has no method 'attr'"

This syntax stops those errors.

$($('#selectBox  option').get(3)).attr('selected', 'selected');

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

If/else else if in Jquery for a condition

Iam confused a lot from morning whether it should be less than or greater than`

this can accept value less than "99999"

I think you answered it yourself... But it's valid when it's less than. Thus the following is incorrect:

}elseif($("#seats").val() < 99999){
  alert("Not a valid Number");
}else{

You are saying if it's less than 99999, then it's not valid. You want to do the opposite:

}elseif($("#seats").val() >= 99999){
  alert("Not a valid Number");
}else{

Also, since you have $("#seats") twice, jQuery has to search the DOM twice. You should really be storing the value, or at least the DOM element in a variable. And some more of your code doesn't make much sense, so I'm going to make some assumptions and put it all together:

var seats = $("#seats").val();

var error = null;

if (seats == "") {
    error = "Number is required";
} else {
    var seatsNum = parseInt(seats);
    
    if (isNaN(seatsNum)) {
        error = "Not a valid number";
    } else if (seatsNum >= 99999) {
        error = "Number must be less than 99999";
    }
}

if (error != null) {
    alert(error);
} else {
    alert("Valid number");
}

// If you really need setflag:
var setflag = error != null;

Here's a working sample: http://jsfiddle.net/LUY8q/

print highest value in dict with key

The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max key (as opposed to the dict key) you can easily extract the highest value and its associated key.

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)

Android getText from EditText field

Try this -

EditText myEditText =  (EditText) findViewById(R.id.vnosEmaila);

String text = myEditText.getText().toString();

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

It is more flexible to use curl instead of fopen and file_get_content for opening a webpage.

How to create JSON string in C#

You could use the JavaScriptSerializer class, check this article to build an useful extension method.

Code from article:

namespace ExtensionMethods
{
    public static class JSONHelper
    {
        public static string ToJSON(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static string ToJSON(this object obj, int recursionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(obj);
        }
    }
}

Usage:

using ExtensionMethods;

...

List<Person> people = new List<Person>{
                   new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
                   new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
                   };


string jsonString = people.ToJSON();

How to do a non-greedy match in grep?

I know that its a bit of a dead post but I just noticed that this works. It removed both clean-up and cleanup from my output.

> grep -v -e 'clean\-\?up'
> grep --version grep (GNU grep) 2.20

How to check if IsNumeric

There's the TryParse method, which returns a bool indicating if the conversion was successful.

How do you validate a URL with a regular expression in Python?

modified django url validation regex:

import re

ul = '\u00a1-\uffff'  # unicode letters range (must not be a raw string)

# IP patterns 
ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}' 
ipv6_re = r'\[[0-9a-f:\.]+\]'

# Host patterns 
hostname_re = r'[a-z' + ul + r'0-9](?:[a-z' + ul + r'0-9-]{0,61}[a-z' + ul + r'0-9])?'
domain_re = r'(?:\.(?!-)[a-z' + ul + r'0-9-]{1,63}(?<!-))*' # domain names have max length of 63 characters
tld_re = ( 
    r'\.'                                # dot 
    r'(?!-)'                             # can't start with a dash 
    r'(?:[a-z' + ul + '-]{2,63}'         # domain label 
    r'|xn--[a-z0-9]{1,59})'              # or punycode label 
    r'(?<!-)'                            # can't end with a dash 
    r'\.?'                               # may have a trailing dot 
) 
host_re = '(' + hostname_re + domain_re + tld_re + '|localhost)'

regex = re.compile( 
    r'^(?:http|ftp)s?://' # http(s):// or ftp(s)://
    r'(?:\S+(?::\S*)?@)?'  # user:pass authentication 
    r'(?:' + ipv4_re + '|' + ipv6_re + '|' + host_re + ')' # localhost or ip
    r'(?::\d{2,5})?'  # optional port
    r'(?:[/?#][^\s]*)?'  # resource path
    r'\Z', re.IGNORECASE)

source: https://github.com/django/django/blob/master/django/core/validators.py#L74

Client on Node.js: Uncaught ReferenceError: require is not defined

In my case I used another solution.

As the project doesn't require CommonJS and it must have ES3 compatibility (modules not supported) all you need is just remove all export and import statements from your code, because your tsconfig doesn't contain

"module": "commonjs"

But use import and export statements in your referenced files

import { Utils } from "./utils"
export interface Actions {}

Final generated code will always have(at least for TypeScript 3.0) such lines

"use strict";
exports.__esModule = true;
var utils_1 = require("./utils");
....
utils_1.Utils.doSomething();

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I got same error. This is how it worked for me:

  • cleaned the project under currently installed gcc
  • recompiled it

Worked perfectly!

How to set 24-hours format for date on java?

Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);

HH will return 0-23 for hours.

kk will return 1-24 for hours.

See more here: Customizing Formats

use method setIs24HourView(Boolean is24HourView) to set time picker to set 24 hour view.

Pythonic way to create a long multi-line string

I usually use something like this:

text = '''
    This string was typed to be a demo
    on how could we write a multi-line
    text in Python.
'''

If you want to remove annoying blank spaces in each line, you could do as follows:

text = '\n'.join(line.lstrip() for line in text.splitlines())

Best way of invoking getter by reflection

The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.

SVN repository backup strategies

svnadmin hotcopy

svnadmin hotcopy REPOS_PATH NEW_REPOS_PATH

This subcommand makes a full “hot” backup of your repository, including all hooks, configuration files, and, of course, database files.

How can I get a value from a map?

The answer by Steve Jessop explains well, why you can't use std::map::operator[] on a const std::map. Gabe Rainbow's answer suggests a nice alternative. I'd just like to provide some example code on how to use map::at(). So, here is an enhanced example of your function():

void function(const MAP &map, const std::string &findMe) {
    try {
        const std::string& value = map.at(findMe);
        std::cout << "Value of key \"" << findMe.c_str() << "\": " << value.c_str() << std::endl;
        // TODO: Handle the element found.
    }
    catch (const std::out_of_range&) {
        std::cout << "Key \"" << findMe.c_str() << "\" not found" << std::endl;
        // TODO: Deal with the missing element.
    }
}

And here is an example main() function:

int main() {
    MAP valueMap;
    valueMap["string"] = "abc";
    function(valueMap, "string");
    function(valueMap, "strong");
    return 0;
}

Output:

Value of key "string": abc
Key "strong" not found

Code on Ideone

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

Fade Effect on Link Hover?

Nowadays people are just using CSS3 transitions because it's a lot easier than messing with JS, browser support is reasonably good and it's merely cosmetic so it doesn't matter if it doesn't work.

Something like this gets the job done:

a {
  color:blue;
  /* First we need to help some browsers along for this to work.
     Just because a vendor prefix is there, doesn't mean it will
     work in a browser made by that vendor either, it's just for
     future-proofing purposes I guess. */
  -o-transition:.5s;
  -ms-transition:.5s;
  -moz-transition:.5s;
  -webkit-transition:.5s;
  /* ...and now for the proper property */
  transition:.5s;
}
a:hover { color:red; }

You can also transition specific CSS properties with different timings and easing functions by separating each declaration with a comma, like so:

a {
  color:blue; background:white;
  -o-transition:color .2s ease-out, background 1s ease-in;
  -ms-transition:color .2s ease-out, background 1s ease-in;
  -moz-transition:color .2s ease-out, background 1s ease-in;
  -webkit-transition:color .2s ease-out, background 1s ease-in;
  /* ...and now override with proper CSS property */
  transition:color .2s ease-out, background 1s ease-in;
}
a:hover { color:red; background:yellow; }

Demo here

Remove local git tags that are no longer on the remote repository

Just added a git sync-local-tags command to pivotal_git_scripts Gem fork on GitHub:

https://github.com/kigster/git_scripts

Install the gem, then run "git sync-local-tags" in your repository to delete the local tags that do not exist on the remote.

Alternatively you can just install this script below and call it "git-sync-local-tags":


#!/usr/bin/env ruby

# Delete tags from the local Git repository, which are not found on 
# a remote origin
#
# Usage: git sync-local-tags [-n]
#        if -n is passed, just print the tag to be deleted, but do not 
#        actually delete it.
#
# Author: Konstantin Gredeskoul (http://tektastic.com)
#
#######################################################################

class TagSynchronizer
  def self.local_tags
    `git show-ref --tags | awk '{print $2}'`.split(/\n/)
  end

  def self.remote_tags
    `git ls-remote --tags origin | awk '{print $2}'`.split(/\n/)
  end

  def self.orphaned_tags
    self.local_tags - self.remote_tags
  end

  def self.remove_unused_tags(print_only = false)
    self.orphaned_tags.each do |ref|
      tag = ref.gsub /refs\/tags\//, ''
      puts "deleting local tag #{tag}"
      `git tag -d #{tag}` unless print_only
    end
  end
end

unless File.exists?(".git")
  puts "This doesn't look like a git repository."
  exit 1
end

print_only = ARGV.include?("-n")
TagSynchronizer.remove_unused_tags(print_only)

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

If you are using Xcode 8.0 to 8.3.3 and swift 2.2 to 3.0

In my case need to change in URL http:// to https:// (if not working then try)

Add an App Transport Security Setting: Dictionary.
Add a NSAppTransportSecurity: Dictionary.
Add a NSExceptionDomains: Dictionary.
Add a yourdomain.com: Dictionary.  (Ex: stackoverflow.com)

Add Subkey named " NSIncludesSubdomains" as Boolean: YES
Add Subkey named " NSExceptionAllowsInsecureHTTPLoads" as Boolean: YES

enter image description here

Setting HttpContext.Current.Session in a unit test

If you're using the MVC framework, this should work. I used Milox's FakeHttpContext and added a few additional lines of code. The idea came from this post:

http://codepaste.net/p269t8

This seems to work in MVC 5. I haven't tried this in earlier versions of MVC.

HttpContext.Current = MockHttpContext.FakeHttpContext();

var wrapper = new HttpContextWrapper(HttpContext.Current);

MyController controller = new MyController();
controller.ControllerContext = new ControllerContext(wrapper, new RouteData(), controller);

string result = controller.MyMethod();

How to click a href link using Selenium

How to click on link without using click method in selenum?

This is a tricky question. Follow the below steps:

driver.get("https://www.google.com");
String gmaillink= driver.findElement(By.xpath("//a[@href='https://mail.google.com/mail/?tab=wm&ogbl']")).getAttribute("href");
System.out.println(gmaillink);
driver.get(gmaillink);

String to HashMap JAVA

Assuming no key contains either ',' or ':':

Map<String, Integer> map = new HashMap<String, Integer>();
for(final String entry : s.split(",")) {
    final String[] parts = entry.split(":");
    assert(parts.length == 2) : "Invalid entry: " + entry;
    map.put(parts[0], new Integer(parts[1]));
}

How to switch back to 'master' with git?

I'm trying to sort of get my head around what's going on over there. Is there anything IN your "example" folder? Git doesn't track empty folders.

If you branched and switched to your new branch then made a new folder and left it empty, and then did "git commit -a", you wouldn't get that new folder in the commit.

Which means it's untracked, which means checking out a different branch wouldn't remove it.

Determine version of Entity Framework I am using?

To answer the first part of your question: Microsoft published their Entity Framework version history here.

What's is the difference between include and extend in use case diagram?

Extends is used when you understand that your use case is too much complex. So you extract the complex steps into their own "extension" use cases.

Includes is used when you see common behavior in two use cases. So you abstract out the common behavior into a separate "abstract" use case.

(ref: Jeffrey L. Whitten, Lonnie D. Bentley, Systems analysis & design methods, McGraw-Hill/Irwin, 2007)

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

This is not just a Chrome/Safari issue, I experienced a quite similar behavior with Firefox 18.0.1. The funny part is that this does not happen on MSIE! The problem here is the first mouseup event that forces to unselect the input content, so just ignore the first occurence.

$(':text').focus(function(){
    $(this).one('mouseup', function(event){
        event.preventDefault();
    }).select();
});

The timeOut approach causes a strange behavior, and blocking every mouseup event you can not remove the selection clicking again on the input element.

How to validate domain credentials?

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices.AccountManagement;

class WindowsCred
{
    private const string SPLIT_1 = "\\";

    public static bool ValidateW(string UserName, string Password)
    {
        bool valid = false;
        string Domain = "";

        if (UserName.IndexOf("\\") != -1)
        {
            string[] arrT = UserName.Split(SPLIT_1[0]);
            Domain = arrT[0];
            UserName = arrT[1];
        }

        if (Domain.Length == 0)
        {
            Domain = System.Environment.MachineName;
        }

        using (PrincipalContext context = new PrincipalContext(ContextType.Domain, Domain)) 
        {
            valid = context.ValidateCredentials(UserName, Password);
        }

        return valid;
    }
}

Kashif Mushtaq Ottawa, Canada

How do I close an Android alertdialog

Replying to an old post but hopefully somebody might find this useful. Do this instead

final AlertDialog builder = new AlertDialog.Builder(getActivity()).create();

You can then go ahead and do,

builder.dismiss();

Getting content/message from HttpResponseMessage

I think the easiest approach is just to change the last line to

txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!

This way you don't need to introduce any stream readers and you don't need any extension methods.

Most efficient way to remove special characters from string

HashSet is O(1)
Not sure if it is faster than the existing comparison

private static HashSet<char> ValidChars = new HashSet<char>() { 'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3', '_' };
public static string RemoveSpecialCharacters(string str)
{
    StringBuilder sb = new StringBuilder(str.Length / 2);
    foreach (char c in str)
    {
        if (ValidChars.Contains(c)) sb.Append(c);
    }
    return sb.ToString();
}

I tested and this in not faster than the accepted answer.
I will leave it up as if you needed a configurable set of characters this would be a good solution.

How to set the text/value/content of an `Entry` widget using a button in tkinter

You can choose between the following two methods to set the text of an Entry widget. For the examples, assume imported library import tkinter as tk and root window root = tk.Tk().


  • Method A: Use delete and insert

    Widget Entry provides methods delete and insert which can be used to set its text to a new value. First, you'll have to remove any former, old text from Entry with delete which needs the positions where to start and end the deletion. Since we want to remove the full old text, we start at 0 and end at wherever the end currently is. We can access that value via END. Afterwards the Entry is empty and we can insert new_text at position 0.

    entry = tk.Entry(root)
    new_text = "Example text"
    entry.delete(0, tk.END)
    entry.insert(0, new_text)
    

  • Method B: Use StringVar

    You have to create a new StringVar object called entry_text in the example. Also, your Entry widget has to be created with keyword argument textvariable. Afterwards, every time you change entry_text with set, the text will automatically show up in the Entry widget.

    entry_text = tk.StringVar()
    entry = tk.Entry(root, textvariable=entry_text)
    new_text = "Example text"
    entry_text.set(new_text)
    

  • Complete working example which contains both methods to set the text via Button:

    This window

    screenshot

    is generated by the following complete working example:

    import tkinter as tk
    
    def button_1_click():
        # define new text (you can modify this to your needs!)
        new_text = "Button 1 clicked!"
        # delete content from position 0 to end
        entry.delete(0, tk.END)
        # insert new_text at position 0
        entry.insert(0, new_text)
    
    def button_2_click():
        # define new text (you can modify this to your needs!)
        new_text = "Button 2 clicked!"
        # set connected text variable to new_text
        entry_text.set(new_text)
    
    root = tk.Tk()
    
    entry_text = tk.StringVar()
    entry = tk.Entry(root, textvariable=entry_text)
    
    button_1 = tk.Button(root, text="Button 1", command=button_1_click)
    button_2 = tk.Button(root, text="Button 2", command=button_2_click)
    
    entry.pack(side=tk.TOP)
    button_1.pack(side=tk.LEFT)
    button_2.pack(side=tk.LEFT)
    
    root.mainloop()
    

Given URL is not allowed by the Application configuration Facebook application error

I found Valid OAuth Redirect URIs under PRODUCTS then Facebook Login > Settings not as everyone is stating above. I am supposing this is a version issue.

It still didn't work for me. I guess I really have to add Android Platform rather than just the Website. This is annoying because my app is still in development mode :(

UPDATE: I'm using Expo to develop my react-native app and used info provided here: https://developers.facebook.com/apps/131491964294190/settings/basic/ to set up the Android and iOS platforms. This resolved the issue for me.

Navigation Drawer (Google+ vs. YouTube)

Just recently I forked a current Github project called "RibbonMenu" and edited it to fit my needs:

https://github.com/jaredsburrows/RibbonMenu

What's the Purpose

  • Ease of Access: Allow easy access to a menu that slides in and out
  • Ease of Implementation: Update the same screen using minimal amount of code
  • Independency: Does not require support libraries such as ActionBarSherlock
  • Customization: Easy to change colors and menus

What's New

  • Changed the sliding animation to match Facebook and Google+ apps
  • Added standard ActionBar (you can chose to use ActionBarSherlock)
  • Used menuitem to open the Menu
  • Added ability to update ListView on main Activity
  • Added 2 ListViews to the Menu, similiar to Facebook and Google+ apps
  • Added a AutoCompleteTextView and a Button as well to show examples of implemenation
  • Added method to allow users to hit the 'back button' to hide the menu when it is open
  • Allows users to interact with background(main ListView) and the menu at the same time unlike the Facebook and Google+ apps!

ActionBar with Menu out

ActionBar with Menu out

ActionBar with Menu out and search selected

ActionBar with Menu out and search selected

Setting user agent of a java URLConnection

HTTP Servers tend to reject old browsers and systems.

The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection or the system property "http.agent".

How to deal with floating point number precision in JavaScript?

You can use parseFloat() and toFixed() if you want to bypass this issue for a small operation:

a = 0.1;
b = 0.2;

a + b = 0.30000000000000004;

c = parseFloat((a+b).toFixed(2));

c = 0.3;

a = 0.3;
b = 0.2;

a - b = 0.09999999999999998;

c = parseFloat((a-b).toFixed(2));

c = 0.1;

Getting list of tables, and fields in each, in a database

I found an easy way to fetch the details of Tables and columns of a particular DB using SQL developer.

Select *FROM USER_TAB_COLUMNS

Change the color of a bullet in a html list?

You could use CSS to attain this. By specifying the list in the color and style of your choice, you can then also specify the text as a different color.

Follow the example at http://www.echoecho.com/csslists.htm.

How to change the JDK for a Jenkins job?

Using latest Jenkins version 2.7.4 which is also having a bug for existing jobs.

  1. Add new JDKs through Manage Jenkins -> Global Tool Configuration -> JDK ** If you edit current job then JDK dropdown is not showing (bug)

  2. Hit http://your_jenkin_server:8080/restart and restart the server

  3. Re-configure job

Now, you should see JDK dropdown in "job name" -> Configure in Jenkins web ui. It will list all JDKs available in Jenkins configuration.

Java ArrayList Index

Using an Array:

String[] fruits = new String[3]; // make a 3 element array
fruits[0]="apple";
fruits[1]="banana";
fruits[2]="orange";
System.out.println(fruits[1]); // output the second element

Using a List

ArrayList<String> fruits = new ArrayList<String>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
System.out.println(fruits.get(1));

Best way to get hostname with php

I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:

php_uname('n');

gethostname();

Simple proof that GUID is not unique

The odds of a bug in the GUID generating code are much higher than the odds of the algorithm generating a collision. The odds of a bug in your code to test the GUIDs is even greater. Give up.

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

Javascript sleep/delay/wait function

You could use the following code, it does a recursive call into the function in order to properly wait for the desired time.

function exportar(page,miliseconds,totalpages)
{
    if (page <= totalpages)
    {
        nextpage = page + 1;
        console.log('fnExcelReport('+ page +'); nextpage = '+ nextpage + '; miliseconds = '+ miliseconds + '; totalpages = '+ totalpages );
        fnExcelReport(page);
        setTimeout(function(){
            exportar(nextpage,miliseconds,totalpages);
        },miliseconds);
    };
}

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

The most correct way is to use HttpContext.Current.Server.MapPath("~/App_Data");. This means you can only retrieve the path from a method where the HttpContext is available. It makes sense: the App_Data directory is a web project folder structure [1].

If you need the path to ~/App_Data from a class where you don't have access to the HttpContext you can always inject a provider interface using your IoC container:

public interface IAppDataPathProvider
{
    string GetAppDataPath();
}

Implement it using your HttpApplication:

public class AppDataPathProvider : IAppDataPathProvider
{
    public string GetAppDataPath()
    {
        return MyHttpApplication.GetAppDataPath();
    }
}

Where MyHttpApplication.GetAppDataPath looks like:

public class MyHttpApplication : HttpApplication
{
    // of course you can fetch&store the value at Application_Start
    public static string GetAppDataPath()
    {
        return HttpContext.Current.Server.MapPath("~/App_Data");
    }
}

[1] http://msdn.microsoft.com/en-us/library/ex526337%28v=vs.100%29.aspx

How I can get web page's content and save it into the string variable

I've run into issues with Webclient.Downloadstring before. If you do, you can try this:

WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
    html = sr.ReadToEnd();
}

If statements for Checkboxes

I suggest

if (checkbox.IsChecked == true)
{
    //do something
}

Hope it's helpful ^^

JavaScript file upload size validation

If you set the Ie 'Document Mode' to 'Standards' you can use the simple javascript 'size' method to get the uploaded file's size.

Set the Ie 'Document Mode' to 'Standards':

<meta http-equiv="X-UA-Compatible" content="IE=Edge">

Than, use the 'size' javascript method to get the uploaded file's size:

<script type="text/javascript">
    var uploadedFile = document.getElementById('imageUpload');
    var fileSize = uploadedFile.files[0].size;
    alert(fileSize); 
</script>

It works for me.

How to store decimal values in SQL Server?

The settings for Decimal are its precision and scale or in normal language, how many digits can a number have and how many digits do you want to have to the right of the decimal point.

So if you put PI into a Decimal(18,0) it will be recorded as 3?

If you put PI into a Decimal(18,2) it will be recorded as 3.14?

If you put PI into Decimal(18,10) be recorded as 3.1415926535.

How to implement HorizontalScrollView like Gallery?

Try this code:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="100dip"
tools:context=".MainActivity" >
<HorizontalScrollView
    android:id="@+id/hsv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:fillViewport="true"
    android:measureAllChildren="false"
    android:scrollbars="none" >
    <LinearLayout
        android:id="@+id/innerLay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >
        <LinearLayout
            android:id="@+id/asthma_action_plan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/action_plan" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/controlled_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/controlled" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/as_needed_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/as_needed" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/rescue_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/rescue" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/your_symptoms"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/symptoms" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/your_triggers"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/triggers" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/wheeze_rate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/wheeze_rate" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/peak_flow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/peak_flow" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>
</HorizontalScrollView>
<TextView
    android:layout_width="fill_parent"
    android:layout_height="0.2dp"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/hsv"
    android:background="@drawable/ln" />
<LinearLayout
    android:id="@+id/prev"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:paddingLeft="5dip"
    android:paddingRight="5dip"
    android:descendantFocusability="blocksDescendants" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/prev_arrow" />
</LinearLayout>
<LinearLayout
    android:id="@+id/next"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:paddingLeft="5dip"
    android:paddingRight="5dip"
    android:descendantFocusability="blocksDescendants" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/next_arrow" />
</LinearLayout>
</RelativeLayout>

grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:src="@drawable/ic_launcher" />
</LinearLayout>

MainActivity.java

import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {

LinearLayout asthmaActionPlan, controlledMedication, asNeededMedication,
        rescueMedication, yourSymtoms, yourTriggers, wheezeRate, peakFlow;
LayoutParams params;
LinearLayout next, prev;
int viewWidth;
GestureDetector gestureDetector = null;
HorizontalScrollView horizontalScrollView;
ArrayList<LinearLayout> layouts;
int parentLeft, parentRight;
int mWidth;
int currPosition, prevPosition;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    prev = (LinearLayout) findViewById(R.id.prev);
    next = (LinearLayout) findViewById(R.id.next);
    horizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv);
    gestureDetector = new GestureDetector(new MyGestureDetector());
    asthmaActionPlan = (LinearLayout) findViewById(R.id.asthma_action_plan);
    controlledMedication = (LinearLayout) findViewById(R.id.controlled_medication);
    asNeededMedication = (LinearLayout) findViewById(R.id.as_needed_medication);
    rescueMedication = (LinearLayout) findViewById(R.id.rescue_medication);
    yourSymtoms = (LinearLayout) findViewById(R.id.your_symptoms);
    yourTriggers = (LinearLayout) findViewById(R.id.your_triggers);
    wheezeRate = (LinearLayout) findViewById(R.id.wheeze_rate);
    peakFlow = (LinearLayout) findViewById(R.id.peak_flow);

    Display display = getWindowManager().getDefaultDisplay();
    mWidth = display.getWidth(); // deprecated
    viewWidth = mWidth / 3;
    layouts = new ArrayList<LinearLayout>();
    params = new LayoutParams(viewWidth, LayoutParams.WRAP_CONTENT);

    asthmaActionPlan.setLayoutParams(params);
    controlledMedication.setLayoutParams(params);
    asNeededMedication.setLayoutParams(params);
    rescueMedication.setLayoutParams(params);
    yourSymtoms.setLayoutParams(params);
    yourTriggers.setLayoutParams(params);
    wheezeRate.setLayoutParams(params);
    peakFlow.setLayoutParams(params);

    layouts.add(asthmaActionPlan);
    layouts.add(controlledMedication);
    layouts.add(asNeededMedication);
    layouts.add(rescueMedication);
    layouts.add(yourSymtoms);
    layouts.add(yourTriggers);
    layouts.add(wheezeRate);
    layouts.add(peakFlow);

    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    horizontalScrollView.smoothScrollTo(
                            (int) horizontalScrollView.getScrollX()
                                    + viewWidth,
                            (int) horizontalScrollView.getScrollY());
                }
            }, 100L);
        }
    });

    prev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    horizontalScrollView.smoothScrollTo(
                            (int) horizontalScrollView.getScrollX()
                                    - viewWidth,
                            (int) horizontalScrollView.getScrollY());
                }
            }, 100L);
        }
    });

    horizontalScrollView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            }
            return false;
        }
    });
}

class MyGestureDetector extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        if (e1.getX() < e2.getX()) {
            currPosition = getVisibleViews("left");
        } else {
            currPosition = getVisibleViews("right");
        }

        horizontalScrollView.smoothScrollTo(layouts.get(currPosition)
                .getLeft(), 0);
        return true;
    }
}

public int getVisibleViews(String direction) {
    Rect hitRect = new Rect();
    int position = 0;
    int rightCounter = 0;
    for (int i = 0; i < layouts.size(); i++) {
        if (layouts.get(i).getLocalVisibleRect(hitRect)) {
            if (direction.equals("left")) {
                position = i;
                break;
            } else if (direction.equals("right")) {
                rightCounter++;
                position = i;
                if (rightCounter == 2)
                    break;
            }
        }
    }
    return position;
}
}

Let me know if any issue enjoy...

Compare two folders which has many files inside contents

To get summary of new/missing files, and which files differ:

diff -arq folder1 folder2

a treats all files as text, r recursively searched subdirectories, q reports 'briefly', only when files differ

Loop through files in a folder in matlab

At first, you must specify your path, the path that your *.csv files are in there

path = 'f:\project\dataset'

You can change it based on your system.

then,

use dir function :

files = dir (strcat(path,'\*.csv'))

L = length (files);

for i=1:L
   image{i}=csvread(strcat(path,'\',file(i).name));   
   % process the image in here
end

pwd also can be used.

ImportError: No module named google.protobuf

This solved my problem with google.protobuf import in Tensorflow and Python 3.7.5 that i had yesterday.

Check where is protobuf

pip show protobuf

If it is installed you will get something like this

Name: protobuf
Version: 3.6.1
Summary: Protocol Buffers
Home-page: https://developers.google.com/protocol-buffers/
Author: None
Author-email: None
License: 3-Clause BSD License
Location: /usr/lib/python3/dist-packages
Requires: 
Required-by: tensorflow, tensorboard

(If not, run pip install protobuf )

Now move into the location folder.

cd /usr/lib/python3/dist-packages

Now run

touch google/__init__.py

How is Java platform-independent when it needs a JVM to run?

No, it's the other way around. It's because you use the virtual machine that the Java program gets independend.

The virtual machine is not independent, you have to install one that is specifically made for your type of system. The virtual machine creates an independent platform on top of the operating system.

kill a process in bash

Old post, but I just ran into a very similar problem. After some experimenting, I found that you can do this with a single command:

kill $(ps aux | grep <process_name> | grep -v "grep" | cut -d " " -f2)

In OP's case, <process_name> would be "gedit file.txt".

Java, Calculate the number of days between two dates

My best solution (so far) for calculating the number of days difference:

//  This assumes that you already have two Date objects: startDate, endDate
//  Also, that you want to ignore any time portions

Calendar startCale=new GregorianCalendar();
Calendar endCal=new GregorianCalendar();

startCal.setTime(startDate);
endCal.setTime(endDate);

endCal.add(Calendar.YEAR,-startCal.get(Calendar.YEAR));
endCal.add(Calendar.MONTH,-startCal.get(Calendar.MONTH));
endCal.add(Calendar.DATE,-startCal.get(Calendar.DATE));

int daysDifference=endCal.get(Calendar.DAY_OF_YEAR);

Note, however, that this assumes less than a year's difference!

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

This post helped me with zip(). I know I'm a few years late, but I still want to contribute. This is in Python 3.

Note: in python 2.x, zip() returns a list of tuples; in Python 3.x, zip() returns an iterator. itertools.izip() in python 2.x == zip() in python 3.x

Since it looks like you're building a list of tuples, the following code is the most pythonic way of trying to accomplish what you are doing.

>>> lat = [1, 2, 3]
>>> long = [4, 5, 6]
>>> tuple_list = list(zip(lat, long))
>>> tuple_list
[(1, 4), (2, 5), (3, 6)]

Or, alternatively, you can use list comprehensions (or list comps) should you need more complicated operations. List comprehensions also run about as fast as map(), give or take a few nanoseconds, and are becoming the new norm for what is considered Pythonic versus map().

>>> lat = [1, 2, 3]
>>> long = [4, 5, 6]
>>> tuple_list = [(x,y) for x,y in zip(lat, long)]
>>> tuple_list
[(1, 4), (2, 5), (3, 6)]
>>> added_tuples = [x+y for x,y in zip(lat, long)]
>>> added_tuples
[5, 7, 9]

SQL Query - how do filter by null or not null

Just like you said

select * from tbl where statusid is null

or

select * from tbl where statusid is not null

If your statusid is not null, then it will be selected just fine when you have an actual value, no need for any "if" logic if that is what you were thinking

select * from tbl where statusid = 123 -- the record(s) returned will not have null statusid

if you want to select where it is null or a value, try

select * from tbl where statusid = 123 or statusid is null

How to update a single library with Composer?

If you just want to update a few packages and not all, you can list them as such:

php composer.phar update vendor/package:2.* vendor/package2:dev-master

You can also use wildcards to update a bunch of packages at once:

php composer.phar update vendor/*
  • --prefer-source: Install packages from source when available.
  • --prefer-dist: Install packages from dist when available.
  • --ignore-platform-reqs: ignore php, hhvm, lib-* and ext-* requirements and force the installation even if the local machine does not fulfill these. See also the platform config option.
  • --dry-run: Simulate the command without actually doing anything.
  • --dev: Install packages listed in require-dev (this is the default behavior).
  • --no-dev: Skip installing packages listed in require-dev. The autoloader generation skips the autoload-dev rules.
  • --no-autoloader: Skips autoloader generation.
  • --no-scripts: Skips execution of scripts defined in composer.json.
  • --no-plugins: Disables plugins.
  • --no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters.
  • --optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default.
  • --lock: Only updates the lock file hash to suppress warning about the lock file being out of date.
  • --with-dependencies: Add also all dependencies of whitelisted packages to the whitelist.
  • --prefer-stable: Prefer stable versions of dependencies.
  • --prefer-lowest: Prefer lowest versions of dependencies. Useful for testing minimal versions of requirements, generally used with --prefer-stable.

How to use the read command in Bash?

Typical usage might look like:

i=0
echo -e "hello1\nhello2\nhello3" | while read str ; do
    echo "$((++i)): $str"
done

and output

1: hello1
2: hello2
3: hello3

Having trouble setting working directory

Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!

How to enable/disable bluetooth programmatically in android

To Enable the Bluetooth you could use either of the following functions:

 public void enableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()){
        Intent intentBtEnabled = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
        // The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally defined integer (which must be greater than 0), that the system passes back to you in your onActivityResult() 
        // implementation as the requestCode parameter. 
        int REQUEST_ENABLE_BT = 1;
        startActivityForResult(intentBtEnabled, REQUEST_ENABLE_BT);
        }
  }

The second function is:

public void enableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()){
        mBluetoothAdapter.enable();
    }
}

The difference is that the first function makes the app ask the user a permission to turn on the Bluetooth or to deny. The second function makes the app turn on the Bluetooth directly.

To Disable the Bluetooth use the following function:

public void disableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter.isEnabled()){
        mBluetoothAdapter.disable();
    }
}

NOTE/ The first function needs only the following permission to be defined in the AndroidManifest.xml file:

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

While, the second and third functions need the following permissions:

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

TypeScript getting error TS2304: cannot find name ' require'

Quick and Dirty

If you just have one file using require, or you're doing this for demo purposes you can define require at the top of your TypeScript file.

declare var require: any

TypeScript 2.x

If you are using TypeScript 2.x you no longer need to have Typings or Definitely Typed installed. Simply install the following package.

npm install @types/node --save-dev

The Future of Declaration Files (6/15/2016)

Tools like Typings and tsd will continue to work, and we’ll be working alongside those communities to ensure a smooth transition.

Verify or Edit your src/tsconfig.app.json so that it contains the following:

...
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ]
...

Make sure is the file in the src folder and no the one on the root app folder.

By default, any package under @types is already included in your build unless you've specified either of these options. Read more

TypeScript 1.x

Using typings (DefinitelyTyped's replacement) you can specify a definition directly from a GitHub repository.

Install typings

npm install typings -g --save-dev

Install the requireJS type definition from DefinitelyType's repo

typings install dt~node --save --global

Webpack

If you are using Webpack as your build tool you can include the Webpack types.

npm install --save-dev @types/webpack-env

Update your tsconfig.json with the following under compilerOptions:

"types": [
      "webpack-env"
    ]

This allows you to do require.ensure and other Webpack specific functions.

Angular CLI

With CLI you can follow the Webpack step above and add the "types" block to your tsconfig.app.json.

Alternatively, you could use the preinstalled node types. Keep in mind this will include additional types to your client-side code that are not really available.

"compilerOptions": {
    // other options
    "types": [
      "node"
    ]
  }

Change default date time format on a single database in SQL Server

If this really is a QA issue and you can't change the code. Setup a new server instance on the machine and setup the language as "British English"

How to work with string fields in a C struct?

This does not work:

string s = (string)malloc(sizeof string); 

string refers to a pointer, you need the size of the structure itself:

string s = malloc(sizeof (*string)); 

Note the lack of cast as well (conversion from void* (malloc's return type) is implicitly performed).

Also, in your main, you have a globally delcared patient, but that is uninitialized. Try:

 patient.number = 3;     
 patient.name = "John";     
 patient.address = "Baker street";     
 patient.birthdate = "4/15/2012";     
 patient.gender = 'M';     

before you read-access any of its members

Also, strcpy is inherently unsafe as it does not have boundary checking (will copy until the first '\0' is encountered, writing past allocated memory if the source is too long). Use strncpy instead, where you can at least specify the maximum number of characters copied -- read the documentation to ensure you pass the correct value, it is easy to make an off-by-one error.

Assignment inside lambda expression in Python

UPDATE:

[o for d in [{}] for o in lst if o.name != "" or d.setdefault("", o) == o]

or using filter and lambda:

flag = {}
filter(lambda o: bool(o.name) or flag.setdefault("", o) == o, lst)

Previous Answer

OK, are you stuck on using filter and lambda?

It seems like this would be better served with a dictionary comprehension,

{o.name : o for o in input}.values()

I think the reason that Python doesn't allow assignment in a lambda is similar to why it doesn't allow assignment in a comprehension and that's got something to do with the fact that these things are evaluated on the C side and thus can give us an increase in speed. At least that's my impression after reading one of Guido's essays.

My guess is this would also go against the philosophy of having one right way of doing any one thing in Python.

How to change the default browser to debug with in Visual Studio 2008?

If you use MVC, you don't have this menu (no "Browse With..." menu)

Create first a normal ASP.NET web site.

Java Replacing multiple different substring in a string at once (or in the most efficient way)

This worked for me:

String result = input.replaceAll("string1|string2|string3","replacementString");

Example:

String input = "applemangobananaarefruits";
String result = input.replaceAll("mango|are|ts","-");
System.out.println(result);

Output: apple-banana-frui-

HTML select dropdown list

This is how I do this with JQuery...

using the jquery-watermark plugin (http://code.google.com/p/jquery-watermark/)

$('#inputId').watermark('Please select a name');

works like a charm!!

There is some good documentation at that google code site.

Hope this helps!

How to get detailed list of connections to database in sql server 2005?

As @Hutch pointed out, one of the major limitations of sp_who2 is that it does not take any parameters so you cannot sort or filter it by default. You can save the results into a temp table, but then the you have to declare all the types ahead of time (and remember to DROP TABLE).

Instead, you can just go directly to the source on master.dbo.sysprocesses

I've constructed this to output almost exactly the same thing that sp_who2 generates, except that you can easily add ORDER BY and WHERE clauses to get meaningful output.

SELECT  spid,
        sp.[status],
        loginame [Login],
        hostname, 
        blocked BlkBy,
        sd.name DBName, 
        cmd Command,
        cpu CPUTime,
        physical_io DiskIO,
        last_batch LastBatch,
        [program_name] ProgramName   
FROM master.dbo.sysprocesses sp 
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid 

An Authentication object was not found in the SecurityContext - Spring 3.2.2

As pointed already by @Arun P Johny the root cause of the problem is that at the moment when AuthenticationSuccessEvent is processed SecurityContextHolder is not populated by Authentication object. So any declarative authorization checks (that must get user rights from SecurityContextHolder) will not work. I give you another idea how to solve this problem. There are two ways how you can run your custom code immidiately after successful authentication:

  1. Listen to AuthenticationSuccessEvent
  2. Provide your custom AuthenticationSuccessHandler implementation.

AuthenticationSuccessHandler has one important advantage over first way: SecurityContextHolder will be already populated. So just move your stateService.rowCount() call into loginsuccesshandler.LoginSuccessHandler#onAuthenticationSuccess(...) method and the problem will go away.

How to make a link open multiple pages when clicked

I did it in a simple way:

    <a href="http://virtual-doctor.net" onclick="window.open('http://runningrss.com');
return true;">multiopen</a>

It'll open runningrss in a new window and virtual-doctor in same window.

How to take last four characters from a varchar?

Right should do:

select RIGHT('abcdeffff',4)

Regular cast vs. static_cast vs. dynamic_cast

static_cast

static_cast is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. static_cast performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:

void func(void *data) {
  // Conversion from MyClass* -> void* is implicit
  MyClass *c = static_cast<MyClass*>(data);
  ...
}

int main() {
  MyClass c;
  start_thread(&func, &c)  // func(&c) will be called
      .join();
}

In this example, you know that you passed a MyClass object, and thus there isn't any need for a runtime check to ensure this.

dynamic_cast

dynamic_cast is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a bad_cast exception is thrown in that case).

if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
  ...
} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
  ...
}

You cannot use dynamic_cast if you downcast (cast to a derived class) and the argument type is not polymorphic. For example, the following code is not valid, because Base doesn't contain any virtual function:

struct Base { };
struct Derived : Base { };
int main() {
  Derived d; Base *b = &d;
  dynamic_cast<Derived*>(b); // Invalid
}

An "up-cast" (cast to the base class) is always valid with both static_cast and dynamic_cast, and also without any cast, as an "up-cast" is an implicit conversion.

Regular Cast

These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast. Needless to say, this is much more powerful as it combines all of const_cast, static_cast and reinterpret_cast, but it's also unsafe, because it does not use dynamic_cast.

In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" static_cast sequence would give you a compile-time error for that.

Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.

How to format date string in java?

package newpckg;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StrangeDate {

    public static void main(String[] args) {

        // string containing date in one format
        // String strDate = "2012-05-20T09:00:00.000Z";
        String strDate = "2012-05-20T09:00:00.000Z";

        try {
            // create SimpleDateFormat object with source string date format
            SimpleDateFormat sdfSource = new SimpleDateFormat(
                    "yyyy-MM-dd'T'hh:mm:ss'.000Z'");

            // parse the string into Date object
            Date date = sdfSource.parse(strDate);

            // create SimpleDateFormat object with desired date format
            SimpleDateFormat sdfDestination = new SimpleDateFormat(
                    "dd/MM/yyyy, ha");

            // parse the date into another format
            strDate = sdfDestination.format(date);

            System.out
                    .println("Date is converted from yyyy-MM-dd'T'hh:mm:ss'.000Z' format to dd/MM/yyyy, ha");
            System.out.println("Converted date is : " + strDate.toLowerCase());

        } catch (ParseException pe) {
            System.out.println("Parse Exception : " + pe);
        }
    }
}

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

index.php not loading by default

This might be helpful to somebody. here is the snippet from httpd.conf (Apache version 2.2 windows)

# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html
    DirectoryIndex index.php
</IfModule>

now this will look for index.html file if not found it will look for index.php.

What is the best way to tell if a character is a letter or number in Java without using regexes?

 import java.util.Scanner;
 public class v{
 public static void main(String args[]){
 Scanner in=new Scanner(System.in);
    String str;
    int l;
    int flag=0;
    System.out.println("Enter the String:");
    str=in.nextLine();
    str=str.toLowerCase();
    str=str.replaceAll("\\s","");
    char[] ch=str.toCharArray();
    l=str.length();
    for(int i=0;i<l;i++){
        if ((ch[i] >= 'a' && ch[i]<= 'z') || (ch[i] >= 'A' && ch[i] <= 'Z')){
        flag=0;
        }
        else

        flag++;
        break;
        } 
if(flag==0)
    System.out.println("Onlt char");


}
}

Simple way to transpose columns and rows in SQL?

Based on this solution from bluefeet here is a stored procedure that uses dynamic sql to generate the transposed table. It requires that all the fields are numeric except for the transposed column (the column that will be the header in the resulting table):

/****** Object:  StoredProcedure [dbo].[SQLTranspose]    Script Date: 11/10/2015 7:08:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Paco Zarate
-- Create date: 2015-11-10
-- Description: SQLTranspose dynamically changes a table to show rows as headers. It needs that all the values are numeric except for the field using for     transposing.
-- Parameters: @TableName - Table to transpose
--             @FieldNameTranspose - Column that will be the new headers
-- Usage: exec SQLTranspose <table>, <FieldToTranspose>
-- =============================================
ALTER PROCEDURE [dbo].[SQLTranspose] 
  -- Add the parameters for the stored procedure here
  @TableName NVarchar(MAX) = '', 
  @FieldNameTranspose NVarchar(MAX) = ''
AS
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  DECLARE @colsUnpivot AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX),
  @queryPivot  AS NVARCHAR(MAX),
  @colsPivot as  NVARCHAR(MAX),
  @columnToPivot as NVARCHAR(MAX),
  @tableToPivot as NVARCHAR(MAX), 
  @colsResult as xml

  select @tableToPivot = @TableName;
  select @columnToPivot = @FieldNameTranspose


  select @colsUnpivot = stuff((select ','+quotename(C.name)
       from sys.columns as C
       where C.object_id = object_id(@tableToPivot) and
             C.name <> @columnToPivot 
       for xml path('')), 1, 1, '')

  set @queryPivot = 'SELECT @colsResult = (SELECT  '','' 
                    + quotename('+@columnToPivot+')
                  from '+@tableToPivot+' t
                  where '+@columnToPivot+' <> ''''
          FOR XML PATH(''''), TYPE)'

  exec sp_executesql @queryPivot, N'@colsResult xml out', @colsResult out

  select @colsPivot = STUFF(@colsResult.value('.', 'NVARCHAR(MAX)'),1,1,'')

  set @query 
    = 'select name, rowid, '+@colsPivot+'
        from
        (
          select '+@columnToPivot+' , name, value, ROW_NUMBER() over (partition by '+@columnToPivot+' order by '+@columnToPivot+') as rowid
          from '+@tableToPivot+'
          unpivot
          (
            value for name in ('+@colsUnpivot+')
          ) unpiv
        ) src
        pivot
        (
          sum(value)
          for '+@columnToPivot+' in ('+@colsPivot+')
        ) piv
        order by rowid'
  exec(@query)
END

You can test it with the table provided with this command:

exec SQLTranspose 'yourTable', 'color'

how to set font size based on container size?

You may be able to do this with CSS3 using calculations, however it would most likely be safer to use JavaScript.

Here is an example: http://jsfiddle.net/8TrTU/

Using JS you can change the height of the text, then simply bind this same calculation to a resize event, during resize so it scales while the user is making adjustments, or however you are allowing resizing of your elements.

How to get the fields in an Object via reflection?

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

In short:

Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
    field.setAccessible(true); // You might want to set modifier to public first.
    Object value = field.get(someObject); 
    if (value != null) {
        System.out.println(field.getName() + "=" + value);
    }
}

To learn more about reflection, check the Sun tutorial on the subject.


That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

for (Method method : someObject.getClass().getDeclaredMethods()) {
    if (Modifier.isPublic(method.getModifiers())
        && method.getParameterTypes().length == 0
        && method.getReturnType() != void.class
        && (method.getName().startsWith("get") || method.getName().startsWith("is"))
    ) {
        Object value = method.invoke(someObject);
        if (value != null) {
            System.out.println(method.getName() + "=" + value);
        }
    }
}

That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.

Using sed to mass rename files

The parentheses capture particular strings for use by the backslashed numbers.

How to sort findAll Doctrine's method?

This works for me:

$entities = $em->getRepository('MyBundle:MyTable')->findBy(array(),array('name' => 'ASC'));

Keeping the first array empty fetches back all data, it worked in my case.

Could you explain STA and MTA?

Each EXE which hosts COM or OLE controls defines it's apartment state. The apartment state is by default STA (and for most programs should be STA).

STA - All OLE controls by necessity must live in a STA. STA means that your COM-object must be always manipulated on the UI thread and cannot be passed to other threads (much like any UI element in MFC). However, your program can still have many threads.

MTA - You can manipulate the COM object on any thread in your program.

Unix epoch time to Java Date object

To convert seconds time stamp to millisecond time stamp. You could use the TimeUnit API and neat like this.

long milliSecondTimeStamp = MILLISECONDS.convert(secondsTimeStamp, SECONDS)

Adding a new value to an existing ENUM Type

Complementing @Dariusz 1

For Rails 4.2.1, there's this doc section:

== Transactional Migrations

If the database adapter supports DDL transactions, all migrations will automatically be wrapped in a transaction. There are queries that you can't execute inside a transaction though, and for these situations you can turn the automatic transactions off.

class ChangeEnum < ActiveRecord::Migration
  disable_ddl_transaction!

  def up
    execute "ALTER TYPE model_size ADD VALUE 'new_value'"
  end
end

What file uses .md extension and how should I edit them?

Github's Atom text editor has a live-preview mode for markdown files.

The keyboard shortcut is CTRL+SHIFT+M.

It can be activated from the editor using the CTRL+SHIFT+M key-binding and is currently enabled for .markdown, .md, .mkd, .mkdown, and .ron files.

enter image description here

Double decimal formatting in Java

First import NumberFormat. Then add this:

NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();

This will give you two decimal places and put a dollar sign if it's dealing with currency.

import java.text.NumberFormat;
public class Payroll 
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
    int hoursWorked = 80;
    double hourlyPay = 15.52;

    double grossPay = hoursWorked * hourlyPay;
    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();

    System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));
    }

}

How to use WinForms progress bar?

Hey there's a useful tutorial on Dot Net pearls: http://www.dotnetperls.com/progressbar

In agreement with Peter, you need to use some amount of threading or the program will just hang, somewhat defeating the purpose.

Example that uses ProgressBar and BackgroundWorker: C#

using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            // Start the BackgroundWorker.
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 1; i <= 100; i++)
            {
                // Wait 100 milliseconds.
                Thread.Sleep(100);
                // Report progress.
                backgroundWorker1.ReportProgress(i);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // Change the value of the ProgressBar to the BackgroundWorker progress.
            progressBar1.Value = e.ProgressPercentage;
            // Set the text.
            this.Text = e.ProgressPercentage.ToString();
        }
    }
} //closing here

How to start a Process as administrator mode in C#

This is a clear answer to your question: How do I force my .NET application to run as administrator?

Summary:

Right Click on project -> Add new item -> Application Manifest File

Then in that file change a line like this:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Compile and run!

Call another rest api from my server in Spring-Boot

Does Retrofit have any method to achieve this? If not, how I can do that?

YES

Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.

For more information refer the following link

https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

Just comment out the whole "User for advanced features" and "Advanced phpMyAdmin features" code blocks in config.inc.php.

When to use an interface instead of an abstract class and vice versa?

An abstract class can have shared state or functionality. An interface is only a promise to provide the state or functionality. A good abstract class will reduce the amount of code that has to be rewritten because it's functionality or state can be shared. The interface has no defined information to be shared

How to download a file over HTTP?

I wanted do download all the files from a webpage. I tried wget but it was failing so I decided for the Python route and I found this thread.

After reading it, I have made a little command line application, soupget, expanding on the excellent answers of PabloG and Stan and adding some useful options.

It uses BeatifulSoup to collect all the URLs of the page and then download the ones with the desired extension(s). Finally it can download multiple files in parallel.

Here it is:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function, unicode_literals)
import sys, os, argparse
from bs4 import BeautifulSoup

# --- insert Stan's script here ---
# if sys.version_info >= (3,): 
#...
#...
# def download_file(url, dest=None): 
#...
#...

# --- new stuff ---
def collect_all_url(page_url, extensions):
    """
    Recovers all links in page_url checking for all the desired extensions
    """
    conn = urllib2.urlopen(page_url)
    html = conn.read()
    soup = BeautifulSoup(html, 'lxml')
    links = soup.find_all('a')

    results = []    
    for tag in links:
        link = tag.get('href', None)
        if link is not None: 
            for e in extensions:
                if e in link:
                    # Fallback for badly defined links
                    # checks for missing scheme or netloc
                    if bool(urlparse.urlparse(link).scheme) and bool(urlparse.urlparse(link).netloc):
                        results.append(link)
                    else:
                        new_url=urlparse.urljoin(page_url,link)                        
                        results.append(new_url)
    return results

if __name__ == "__main__":  # Only run if this file is called directly
    # Command line arguments
    parser = argparse.ArgumentParser(
        description='Download all files from a webpage.')
    parser.add_argument(
        '-u', '--url', 
        help='Page url to request')
    parser.add_argument(
        '-e', '--ext', 
        nargs='+',
        help='Extension(s) to find')    
    parser.add_argument(
        '-d', '--dest', 
        default=None,
        help='Destination where to save the files')
    parser.add_argument(
        '-p', '--par', 
        action='store_true', default=False, 
        help="Turns on parallel download")
    args = parser.parse_args()

    # Recover files to download
    all_links = collect_all_url(args.url, args.ext)

    # Download
    if not args.par:
        for l in all_links:
            try:
                filename = download_file(l, args.dest)
                print(l)
            except Exception as e:
                print("Error while downloading: {}".format(e))
    else:
        from multiprocessing.pool import ThreadPool
        results = ThreadPool(10).imap_unordered(
            lambda x: download_file(x, args.dest), all_links)
        for p in results:
            print(p)

An example of its usage is:

python3 soupget.py -p -e <list of extensions> -d <destination_folder> -u <target_webpage>

And an actual example if you want to see it in action:

python3 soupget.py -p -e .xlsx .pdf .csv -u https://healthdata.gov/dataset/chemicals-cosmetics

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

It is simple just write java -XshowSettings:properties on your command line in windows and then paste all the files in the path shown by the java.library.path.

How to auto-remove trailing whitespace in Eclipse?

As @Malvineous said, It's not professional but a work-around to use the Find/Replace method to remove trailing space (below including tab U+0009 and whitespace U+0020).
Just press Ctrl + F (or command + F)

  1. Find [\t ][\t ]*$
  2. Replace with blank string
  3. Use Regular expressions
  4. Replace All

extra:
For removing leading space, find ^[\t ][\t ]* instead of [\t ][\t ]*$
For removing blank lines, find ^\s*$\r?\n

How to debug SSL handshake using cURL?

curl probably does have some options for showing more information but for things like this I always use openssl s_client

With the -debug option this gives lots of useful information

Maybe I should add that this also works with non HTTP connections. So if you are doing "https", try the curl commands suggested below. If you aren't or want a second option openssl s_client might be good

Uninstall Node.JS using Linux command line?

I think Manoj Gupta had the best answer from what I'm seeing. However, the remove command doesn't get rid of any configuration folders or files that may be leftover. Use:

sudo apt-get purge --auto-remove nodejs

The purge command should remove the package and then clean up any configuration files. (see this question for more info on the difference between purge and remove). The auto-remove flag will do the same for packages that were installed by NodeJS.

See the accepted answer on this question for a better explanation.

Although don't forget to handle NPM! Josh's answer covers that.

Mocking a class: Mock() or patch()?

mock.patch is a very very different critter than mock.Mock. patch replaces the class with a mock object and lets you work with the mock instance. Take a look at this snippet:

>>> class MyClass(object):
...   def __init__(self):
...     print 'Created MyClass@{0}'.format(id(self))
... 
>>> def create_instance():
...   return MyClass()
... 
>>> x = create_instance()
Created MyClass@4299548304
>>> 
>>> @mock.patch('__main__.MyClass')
... def create_instance2(MyClass):
...   MyClass.return_value = 'foo'
...   return create_instance()
... 
>>> i = create_instance2()
>>> i
'foo'
>>> def create_instance():
...   print MyClass
...   return MyClass()
...
>>> create_instance2()
<mock.Mock object at 0x100505d90>
'foo'
>>> create_instance()
<class '__main__.MyClass'>
Created MyClass@4300234128
<__main__.MyClass object at 0x100505d90>

patch replaces MyClass in a way that allows you to control the usage of the class in functions that you call. Once you patch a class, references to the class are completely replaced by the mock instance.

mock.patch is usually used when you are testing something that creates a new instance of a class inside of the test. mock.Mock instances are clearer and are preferred. If your self.sut.something method created an instance of MyClass instead of receiving an instance as a parameter, then mock.patch would be appropriate here.

Does C# support multiple inheritance?

Multiple inheritance is not supported in C#.

But if you want to "inherit" behavior from two sources why not use the combination of:

  • Composition
  • Dependency Injection

There is a basic but important OOP principle that says: "Favor composition over inheritance".

You can create a class like this:

public class MySuperClass
{
    private IDependencyClass1 mDependency1;
    private IDependencyClass2 mDependency2;

    public MySuperClass(IDependencyClass1 dep1, IDependencyClass2 dep2)
    {
        mDependency1 = dep1;
        mDependency2 = dep2;
    }

    private void MySuperMethodThatDoesSomethingComplex()
    {
        string s = mDependency1.GetMessage();
        mDependency2.PrintMessage(s);
    }
}

As you can see the dependecies (actual implementations of the interfaces) are injected via the constructor. You class does not know how each class is implemented but it knows how to use them. Hence, a loose coupling between the classes involved here but the same power of usage.

Today's trends show that inheritance is kind of "out of fashion".

MySQL duplicate entry error even though there is no duplicate entry

I know this wasn't the problem in this case, but I had a similar issue of "Duplicate Entry" when creating a composite primary key:

ALTER TABLE table ADD PRIMARY KEY(fieldA,fieldB); 

The error was something like:

#1062 Duplicate entry 'valueA-valueB' for key 'PRIMARY'

So I searched:

select * from table where fieldA='valueA' and fieldB='valueB'

And the output showed just 1 row, no duplicate!

After some time I found out that if you have NULL values in these field you receive these errors. In the end the error message was kind of misleading me.

How to clear all data in a listBox?

If your listbox is connected to a LIST as the data source, listbox.Items.Clear() will not work.

I typically create a file named "DataAccess.cs" containing a separate class for code that uses or changes data pertaining to my form. The following is a code snippet from the DataAccess class that clears or removes all items in the list "exampleItems"

public List<ExampleItem> ClearExampleItems()
       {
           List<ExampleItem> exampleItems = new List<ExampleItem>();
           exampleItems.Clear();
           return examplelistItems;
        }

ExampleItem is also in a separate class named "ExampleItem.cs"

using System;

namespace        // The namespace is automatically added by Visual Studio
{
    public class ExampleItem
    {
        public int ItemId { get; set; }
        public string ItemType { get; set; }
        public int ItemNumber { get; set; }
        public string ItemDescription { get; set; }

        public string FullExampleItem 
        {
            get
            {
                return $"{ItemId} {ItemType} {ItemNumber} {ItemDescription}";
            }
        }
    }
}

In the code for your Window Form, the following code fragments reference your listbox:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Windows.Forms;

namespace        // The namespace is automatically added by Visual Studio
{
    
    public partial class YourFormName : Form
    {
        
        List<ExampleItem> exampleItems = new List<ExampleItem>();

        public YourFormName()
        {
            InitializeComponent();

            // Connect listbox to LIST
            UpdateExampleItemsBinding();
        }

        private void UpdateUpdateItemsBinding()
        {
            ExampleItemsListBox.DataSource = exampleItems;
            ExampleItemsListBox.DisplayMember = "FullExampleItem";
        }

        private void buttonClearListBox_Click(object sender, EventArgs e)
        {
            DataAccess db = new DataAccess();
            exampleItems = db.ClearExampleItems();
            
            UpdateExampleItemsBinding();
        }
    }
}

This solution specifically addresses a Windows Form listbox with the datasource connected to a list.

Git - Ignore files during merge

You could use .gitignore to keep the config.xml out of the repository, and then use a post commit hook to upload the appropriate config.xml file to the server.

Proxy setting for R

Tried all of these and also the solutions using netsh, winhttp etc. Geek On Acid's answer helped me download packages from the server but none of these solutions worked for using the package I wanted to run (twitteR package).

The best solution is to use a software that let's you configure system-wide proxy.

FreeCap (free) and Proxifier (trial) worked perfectly for me at my company.

Please note that you need to remove proxy settings from your browser and any other apps that you have configured to use proxy as these tools provide system-wide proxy for all network traffic from your computer.

Set selected radio from radio group with a value

Or you can just write value attribute to it:

$(':radio[value=<yourvalue>]').attr('checked',true);

This works for me.

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.


This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

How can I use optional parameters in a T-SQL stored procedure?

This also works:

    ...
    WHERE
        (FirstName IS NULL OR FirstName = ISNULL(@FirstName, FirstName)) AND
        (LastName IS NULL OR LastName = ISNULL(@LastName, LastName)) AND
        (Title IS NULL OR Title = ISNULL(@Title, Title))

Controlling a USB power supply (on/off) with Linux

USB 5v power is always on (even when the computer is turned off, on some computers and on some ports.) You will probably need to program an Arduino with some sort of switch, and control it via Serial library from USB plugged in to the computer.

In other words, a combination of this switch tutorial and this tutorial on communicating via Serial libary to Arduino plugged in via USB.

How to check whether a given string is valid JSON in Java

String jsonInput = "{\"mob no\":\"9846716175\"}";//Read input Here
JSONReader reader = new JSONValidatingReader();
Object result = reader.read(jsonInput);
System.out.println("Validation Success !!");

Please download stringtree-json library

HttpClient.GetAsync(...) never returns when using await/async

These two schools are not really excluding.

Here is the scenario where you simply have to use

   Task.Run(() => AsyncOperation()).Wait(); 

or something like

   AsyncContext.Run(AsyncOperation);

I have a MVC action that is under database transaction attribute. The idea was (probably) to roll back everything done in the action if something goes wrong. This does not allow context switching, otherwise transaction rollback or commit is going to fail itself.

The library I need is async as it is expected to run async.

The only option. Run it as a normal sync call.

I am just saying to each its own.

Convert timestamp in milliseconds to string formatted time in Java

    long hours = TimeUnit.MILLISECONDS.toHours(timeInMilliseconds);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours));
    long seconds = TimeUnit.MILLISECONDS
            .toSeconds(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes));
    long milliseconds = timeInMilliseconds - TimeUnit.HOURS.toMillis(hours)
            - TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds);
    return String.format("%02d:%02d:%02d:%d", hours, minutes, seconds, milliseconds);

Do you recommend using semicolons after every statement in JavaScript?

I think this is similar to what the last podcast discussed. The "Be liberal in what you accept" means that extra work had to be put into the Javascript parser to fix cases where semicolons were left out. Now we have a boatload of pages out there floating around with bad syntax, that might break one day in the future when some browser decides to be a little more stringent on what it accepts. This type of rule should also apply to HTML and CSS. You can write broken HTML and CSS, but don't be surprise when you get weird and hard to debug behaviors when some browser doesn't properly interpret your incorrect code.

Difference between del, remove, and pop on lists

Since no-one else has mentioned it, note that del (unlike pop) allows the removal of a range of indexes because of list slicing:

>>> lst = [3, 2, 2, 1]
>>> del lst[1:]
>>> lst
[3]

This also allows avoidance of an IndexError if the index is not in the list:

>>> lst = [3, 2, 2, 1]
>>> del lst[10:]
>>> lst
[3, 2, 2, 1]

How to make div follow scrolling smoothly with jQuery?

This is my final code .... (based on previous fixes, thank you big time for headstart, saved a lot of time experimenting). What bugged me was scrolling up, as well as scrolling down ... :)

it always makes me wonder how jquery can be elegant!!!

$(document).ready(function(){

    //run once
    var el=$('#scrolldiv');
    var originalelpos=el.offset().top; // take it where it originally is on the page

    //run on scroll
     $(window).scroll(function(){
        var el = $('#scrolldiv'); // important! (local)
        var elpos = el.offset().top; // take current situation
        var windowpos = $(window).scrollTop();
        var finaldestination = windowpos+originalelpos;
        el.stop().animate({'top':finaldestination},500);
     });

});

Get exit code of a background process

#/bin/bash

#pgm to monitor
tail -f /var/log/messages >> /tmp/log&
# background cmd pid
pid=$!
# loop to monitor running background cmd
while :
do
    ps ax | grep $pid | grep -v grep
    ret=$?
    if test "$ret" != "0"
    then
        echo "Monitored pid ended"
        break
    fi
    sleep 5

done

wait $pid
echo $?

How can I compare two ordered lists in python?

If you want to just check if they are identical or not, a == b should give you true / false with ordering taken into account.

In case you want to compare elements, you can use numpy for comparison

c = (numpy.array(a) == numpy.array(b))

Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.

Creating a List of Lists in C#

or this example, just to make it more visible:

public class CustomerListList : List<CustomerList> { }  

public class CustomerList : List<Customer> { }

public class Customer
{
   public int ID { get; set; }
   public string SomethingWithText { get; set; }
}

and you can keep it going. to the infinity and beyond !

How to jump back to NERDTree from file in tab?

The top answers here mention using T to open a file in a new tab silently, or Ctrl+WW to hop back to nerd-tree window after file is opened normally.

IF WORKING WITH BUFFERS: use go to open a file in a new buffer, silently, meaning your focus will remain on nerd-tree.

Use this to open multiple files fast :)

MySQL config file location - redhat linux server

Just found it, it is /etc/my.cnf

Simple PHP calculator

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Calculator</title>
    </head>
    <body>
    HTML Code is here:

         <form method="post">
            <input type="text" name="numb1">
            <input type="text" name="numb2">
            <select name="operator" id="">
               <option>None</option>
               <option>Add</option>
               <option>Subtract</option>
               <option>Multiply</option>
               <option>Divide</option>
               <option>Square</option>
            </select>
            <button type="submit" name="submit" value="submit">Calculate</button>
         </form>

    PHP Code:

        <?php 

            if (isset($_POST['submit'])) {
                $result1 = $_POST['numb1'];
                $result2 = $_POST['numb2'];
                $operator = $_POST['operator'];
                switch ($operator) {
                    case 'None':
                        echo "You need to select any operator";
                        break;
                    case 'Add':
                        echo $result1 + $result2;
                        break;
                    case 'Subtract':
                        echo $result1 - $result2;
                        break;
                    case 'Multiply':
                        echo $result1 * $result2;
                        break;
                    case 'Divide':
                        echo $result1 / $result2;
                        break;
                    case 'Square':
                        echo $result1 ** $result2;
                        break;
                }
            }


         ?>
        enter code here

    </body>
    </html>

adding multiple entries to a HashMap at once in one statement

    boolean x;
    for (x = false, 
        map.put("One", new Integer(1)), 
        map.put("Two", new Integer(2)),      
        map.put("Three", new Integer(3)); x;);

Ignoring the declaration of x (which is necessary to avoid an "unreachable statement" diagnostic), technically it's only one statement.

IllegalMonitorStateException on wait() call

wait is defined in Object, and not it Thread. The monitor on Thread is a little unpredictable.

Although all Java objects have monitors, it is generally better to have a dedicated lock:

private final Object lock = new Object();

You can get slightly easier to read diagnostics, at a small memory cost (about 2K per process) by using a named class:

private static final class Lock { }
private final Object lock = new Lock();

In order to wait or notify/notifyAll an object, you need to be holding the lock with the synchronized statement. Also, you will need a while loop to check for the wakeup condition (find a good text on threading to explain why).

synchronized (lock) {
    while (!isWakeupNeeded()) {
        lock.wait();
    }
}

To notify:

synchronized (lock) {
    makeWakeupNeeded();
    lock.notifyAll();
}

It is well worth getting to understand both Java language and java.util.concurrent.locks locks (and java.util.concurrent.atomic) when getting into multithreading. But use java.util.concurrent data structures whenever you can.

Comparing user-inputted characters in C

answer shouldn't be a pointer, the intent is obviously to hold a character. scanf takes the address of this character, so it should be called as

char answer;
scanf(" %c", &answer);

Next, your "or" statement is formed incorrectly.

if (answer == 'Y' || answer == 'y')

What you wrote originally asks to compare answer with the result of 'Y' || 'y', which I'm guessing isn't quite what you wanted to do.

Python truncate a long string

info = data[:min(len(data), 75)

Best way to test if a row exists in a MySQL table

For non-InnoDB tables you could also use the information schema tables:

http://dev.mysql.com/doc/refman/5.1/en/tables-table.html

Connecting to a network folder with username/password in Powershell

At first glance one really wants to use New-PSDrive supplying it credentials.

> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user

Fails!

New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.

The documentation states that you can provide a PSCredential object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.

Therefore you can either use net use or the WScript.Network object, calling the MapNetworkDrive function:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")

Edit for New-PSDrive in PowerShell 3.0

Apparently with newer versions of PowerShell, the New-PSDrive cmdlet works to map network shares with credentials!

New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist

Command-line svn for Windows?

Install MSYS2, it has svn in its repository (besides lots of other Unix goodies). MSYS2 installs without Windows Admin rights.

$ pacman -S svn

The tools can be used from cmd, too:

C:\>C:\msys64\usr\bin\svn.exe co http://somehost/somerepo/

PHP max_input_vars

Just to complement. On a shared server using mod_suphp I was having the same issue.

Declaring 4 max_input_vars (suhosin included), didn't solved it, it just kept truncating on 1000 vars (default), and declaring "php_value max_input_vars 6000" on .htaccess threw error 500.

What solved it was to add the following on .htaccess, which applies the php.ini file recursively to that path

suPHP_ConfigPath /home/myuser/public_html

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

In addition to the headers consider serving your page via https. Many browsers will not cache https by default.

Val and Var in Kotlin

val - Immutable(once initialized can't be reassigned)

var - Mutable(can able to change value)

Example

in Kotlin - val n = 20 & var n = 20

In Java - final int n = 20; & int n = 20;

Create a File object in memory from a string in Java

FileReader r = new FileReader(file);

Use a file reader load the file and then write its contents to a string buffer.

example

The link above shows you an example of how to accomplish this. As other post to this answer say to load a file into memory you do not need write access as long as you do not plan on making changes to the actual file.

How to make circular background using css?

Check with following css. Demo

.circle { 
   width: 140px;
   height: 140px;
   background: red; 
   -moz-border-radius: 70px; 
   -webkit-border-radius: 70px; 
   border-radius: 70px;
}

For more shapes you can follow following urls:

http://davidwalsh.name/css-triangles

What is a "web service" in plain English?

Simplified, non-technical explanation: A web serivce allows a PROGRAM to talk to a web page, instead of using your browser to open a web page.

Example: I can go to maps.google.com, and type in my home address, and see a map of where I live in my browser.

But what if you were writing a computer program where you wanted to take an address and show a pretty map, just like Google maps?

Well, you could write a whole new mapping program from scratch, OR you could call a web service that Google maps provides, send it the address, and it will return a graphical map of the location, which you can display in your program.

There is a lot more to it, as some of the other posts go into, but the upshot is that it allows your application to either retrieve information FROM, or submit information TO some resource. Some other examples:

  1. You can use a web service to retrieve information about books at Amazon.com
  2. You can use a similar web service to submit an order to Amazon.com
  3. You could CREATE a web service to allow outside applications to find out about product information within your company
  4. you could create a web service to allow outside applications to submit orders to your company.

How do I add a newline using printf?

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget

Visual Studio Code open tab in new window

Just an update, Feb 1, 2019: cmd+shift+n on Mac now opens a new window where you can drag over tabs. I didn't find that out until I when through KyleMit's response and saw his key mapping suggestion was already mapped to the correct action.

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt

jQuery - What are differences between $(document).ready and $(window).load?

From the jQuery API Document

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.


Answer to the second question -

No, they are identical as long as you are not using jQuery in no conflict mode.

Drawing an SVG file on a HTML5 canvas

EDIT Dec 16th, 2019

Path2D is supported by all major browsers now

EDIT November 5th, 2014

You can now use ctx.drawImage to draw HTMLImageElements that have a .svg source in some but not all browsers. Chrome, IE11, and Safari work, Firefox works with some bugs (but nightly has fixed them).

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";

Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg> element inserted into the DOM for reference.

You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:

var path = new Path2D('M 100,100 h 50 v 50 h 50');
ctx.stroke(path);

Live example of that here.


Old posterity answer:

There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.

I'd suggest looking in to canvg:

http://code.google.com/p/canvg/

http://canvg.googlecode.com/svn/trunk/examples/index.htm

Linux command for extracting war file?

Or

jar xvf myproject.war

Magento - How to add/remove links on my account navigation?

Its work 100% i am Sure.

Step 1: Go To ( YourTemplate/customer/account/navigation.phtml )

Step 2: Replace This Line: <?php $_count = count($_links); ?> With:

<?php $_count = count($_links); /* Add or Remove Account Left Navigation Links Here -*/
unset($_links['account']); /* Account Info */     
unset($_links['account_edit']); /* Account Info */            
unset($_links['tags']); /* My Tags */
unset($_links['invitations']); /* My Invitations */
unset($_links['reviews']);  /* Reviews */
unset($_links['wishlist']); /* Wishlist */
unset($_links['newsletter']); /* Newsletter */
unset($_links['orders']); /* My Orders */
unset($_links['address_book']); /* Address */
unset($_links['enterprise_customerbalance']); /* Store Credit */
unset($_links['OAuth Customer Tokens']); /* My Applications */
unset($_links['enterprise_reward']); /* Reward Points */
unset($_links['giftregistry']); /* Gift Registry */
unset($_links['downloadable_products']); /* My Downloadable Products */
unset($_links['recurring_profiles']); /* Recurring Profiles */
unset($_links['billing_agreements']); /* Billing Agreements */
unset($_links['enterprise_giftcardaccount']); /* Gift Card Link */

?>

Convert ascii value to char

To convert an int ASCII value to character you can also use:

int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z

How do I style a <select> dropdown with only CSS?

You definitely should do it like in Styling select, optgroup and options with CSS. In many ways, background-color and color are just what you would typically need to style options, not the entire select.

Multi-dimensional associative arrays in JavaScript

Just use a regular JavaScript object, which would 'read' the same way as your associative arrays. You have to remember to initialize them first as well.

var obj = {};

obj['fred'] = {};
if('fred' in obj ){ } // can check for the presence of 'fred'
if(obj.fred) { } // also checks for presence of 'fred'
if(obj['fred']) { } // also checks for presence of 'fred'

// The following statements would all work
obj['fred']['apples'] = 1;
obj.fred.apples = 1;
obj['fred'].apples = 1;

// or build or initialize the structure outright
var obj = { fred: { apples: 1, oranges: 2 }, alice: { lemons: 1 } };

If you're looking over values, you might have something that looks like this:

var people = ['fred', 'alice'];
var fruit = ['apples', 'lemons'];

var grid = {};
for(var i = 0; i < people.length; i++){
    var name = people[i];
    if(name in grid == false){
        grid[name] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors
    }

    for(var j = 0; j < fruit.length; j++){
        var fruitName = fruit[j];
        grid[name][fruitName] = 0;
    }
}

Javascript extends class

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

How to use relative/absolute paths in css URLs?

The URL is relative to the location of the CSS file, so this should work for you:

url('../../images/image.jpg')

The relative URL goes two folders back, and then to the images folder - it should work for both cases, as long as the structure is the same.

From https://www.w3.org/TR/CSS1/#url:

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document

Drop all tables command

Once you've dropped all the tables (and the indexes will disappear when the table goes) then there's nothing left in a SQLite database as far as I know, although the file doesn't seem to shrink (from a quick test I just did).

So deleting the file would seem to be fastest - it should just be recreated when your app tries to access the db file.

How to configure custom PYTHONPATH with VM and PyCharm?

For PyCharm 5 (or 2016.1), you can:

  1. select Preferences > Project Interpreter
  2. to the right of interpreter selector there is a "..." button, click it
  3. select "more..."
  4. pop up a new "Project Interpreters" window
  5. select the rightest button (named "show paths for the selected interpreter")
  6. pop up a "Interpreter Paths" window
  7. click the "+" buttom > select your desired PYTHONPATH directory (the folder which contains python modules) and click OK
  8. Done! Enjoy it!

enter image description here

enter image description here

enter image description here enter image description here

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

I've noticed that sometimes eclipse somehow picks up some of the jars and keeps a lock on them (in Windows only) and when you try to do mvn clean it says:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.2:clean (default-clean) on project

The only solution so far is to close eclipse and run the mvn build again.

And these are random jars - it can pick up anything it wants... Why that happens is a mystery to me. Probably eclipse opens the jars when you do Type Search or Resource Search and forgets to close them / release the file handlers..

Python functions call by reference

Technically python do not pass arguments by value: all by reference. But ... since python has two types of objects: immutable and mutable, here is what happens:

  • Immutable arguments are effectively passed by value: string, integer, tuple are all immutable object types. While they are technically "passed by reference" (like all parameters), since you can't change them in-place inside the function it looks/behaves as if it is passed by value.

  • Mutable arguments are effectively passed by reference: lists or dictionaries are passed by its pointers. Any in-place change inside the function like (append or del) will affect the original object.

This is how Python is designed: no copies and all are passed by reference. You can explicitly pass a copy.

def sort(array):
    # do sort
    return array

data = [1, 2, 3]
sort(data[:]) # here you passed a copy

Last point I would like to mention which is a function has its own scope.

def do_any_stuff_to_these_objects(a, b): 
    a = a * 2 
    del b['last_name']

number = 1 # immutable
hashmap = {'first_name' : 'john', 'last_name': 'legend'} # mutable
do_any_stuff_to_these_objects(number, hashmap) 
print(number) # 1 , oh  it should be 2 ! no a is changed inisde the function scope
print(hashmap) # {'first_name': 'john'}

Removing pip's cache?

On my mac I had to remove the cache directory ~/Library/Caches/pip/

How to set session attribute in java?

By default session object is available on jsp page(implicit object). It will not available in normal POJO java class. You can get the reference of HttpSession object on Servelt by using HttpServletRequest

HttpSession s=request.getSession()
s.setAttribute("name","value");

You can get session on an ActionSupport based Action POJO class as follows

 ActionContext ctx= ActionContext.getContext();
   Map m=ctx.getSession();
   m.put("name", value);

look at: http://ohmjavaclasses.blogspot.com/2011/12/access-session-in-action-class-struts2.html

Disable scrolling in webview?

I don't know if you still need it or not, but here is the solution:

appView = (WebView) findViewById(R.id.appView); 
appView.setVerticalScrollBarEnabled(false);
appView.setHorizontalScrollBarEnabled(false);

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:

<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
    <div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
        <div class="uil-default-css">
            <img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
        </div>
        <div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;">&nbsp;</div>
    </div>
    <div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>

Finally, replace .loader-text element's content on the fly on every navigation event and turn on the #resultloading div, note that it is initially hidden.

var showLoader = function (text) {
    $('#resultLoading').show();
    $('#resultLoading').find('.loader-text').html(text);
};

jQuery(document).ready(function () {
    jQuery(window).on("beforeunload ", function () {
        showLoader('Loading, please wait...');
    });
});

This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.

The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.

Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.

How to join (merge) data frames (inner, outer, left, right)

  1. Using merge function we can select the variable of left table or right table, same way like we all familiar with select statement in SQL (EX : Select a.* ...or Select b.* from .....)
  2. We have to add extra code which will subset from the newly joined table .

    • SQL :- select a.* from df1 a inner join df2 b on a.CustomerId=b.CustomerId

    • R :- merge(df1, df2, by.x = "CustomerId", by.y = "CustomerId")[,names(df1)]

Same way

  • SQL :- select b.* from df1 a inner join df2 b on a.CustomerId=b.CustomerId

  • R :- merge(df1, df2, by.x = "CustomerId", by.y = "CustomerId")[,names(df2)]

Why does Boolean.ToString output "True" and not "true"

Only people from Microsoft can really answer that question. However, I'd like to offer some fun facts about it ;)

First, this is what it says in MSDN about the Boolean.ToString() method:

Return Value

Type: System.String

TrueString if the value of this instance is true, or FalseString if the value of this instance is false.

Remarks

This method returns the constants "True" or "False". Note that XML is case-sensitive, and that the XML specification recognizes "true" and "false" as the valid set of Boolean values. If the String object returned by the ToString() method is to be written to an XML file, its String.ToLower method should be called first to convert it to lowercase.

Here comes the fun fact #1: it doesn't return TrueString or FalseString at all. It uses hardcoded literals "True" and "False". Wouldn't do you any good if it used the fields, because they're marked as readonly, so there's no changing them.

The alternative method, Boolean.ToString(IFormatProvider) is even funnier:

Remarks

The provider parameter is reserved. It does not participate in the execution of this method. This means that the Boolean.ToString(IFormatProvider) method, unlike most methods with a provider parameter, does not reflect culture-specific settings.

What's the solution? Depends on what exactly you're trying to do. Whatever it is, I bet it will require a hack ;)

How can I rotate an HTML <div> 90 degrees?

Use following in your CSS

div {
    -webkit-transform: rotate(90deg); /* Safari and Chrome */
    -moz-transform: rotate(90deg);   /* Firefox */
    -ms-transform: rotate(90deg);   /* IE 9 */
    -o-transform: rotate(90deg);   /* Opera */
    transform: rotate(90deg);
} 

Why use argparse rather than optparse?

There are also new kids on the block!

  • Besides the already mentioned deprecated optparse. [DO NOT USE]
  • argparse was also mentioned, which is a solution for people not willing to include external libs.
  • docopt is an external lib worth looking at, which uses a documentation string as the parser for your input.
  • click is also external lib and uses decorators for defining arguments. (My source recommends: Why Click)
  • python-inquirer For selection focused tools and based on Inquirer.js (repo)

If you need a more in-depth comparison please read this and you may end up using docopt or click. Thanks to Kyle Purdon!

How to get Python requests to trust a self signed SSL certificate?

Setting export SSL_CERT_FILE=/path/file.crt should do the job.

Is there a way to avoid null check before the for-each loop iteration starts?

It's already 2017, and you can now use Apache Commons Collections4

The usage:

for(Object obj : CollectionUtils.emptyIfNull(list1)){
    // Do your stuff
}

R - Markdown avoiding package loading messages

```{r results='hide', message=FALSE, warning=FALSE}
library(RJSONIO)
library(AnotherPackage)
```

see Chunk Options in the Knitr docs

text-align:center won't work with form <label> tag (?)

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

NVIDIA NVML Driver/library version mismatch

This also happened to me on Ubuntu 16.04 using the nvidia-348 package (latest nvidia version on Ubuntu 16.04).

However I could resolve the problem by installing nvidia-390 through the Proprietary GPU Drivers PPA.

So a solution to the described problem on Ubuntu 16.04 is doing this:

  • sudo add-apt-repository ppa:graphics-drivers/ppa
  • sudo apt-get update
  • sudo apt-get install nvidia-390

Note: This guide assumes a clean Ubuntu install. If you have previous drivers installed a reboot migh be needed to reload all the kernel modules.

Command /usr/bin/codesign failed with exit code 1

Steps to Fix this issue:

  1. Go to Key Chain Access.
    1. Select the i-Phone Developer certificate.
    2. Lock the Certificate.( Menu bar - Lock Button)
    3. Give the Machine Password.
    4. Unlock the Certificate.

Now clean and rebuild the project, this issue will resolve.

How do I jump out of a foreach loop in C#?

Use break; and this will exit the foreach loop

How to sort a List of objects by their date (java collections, List<Object>)

In Java 8, it's now as simple as:

movieItems.sort(Comparator.comparing(Movie::getDate));

C string append

strcpy(str1+strlen(str1), str2);

What is the difference/usage of homebrew, macports or other package installation tools?

Homebrew and macports both solve the same problem - that is the installation of common libraries and utilities that are not bundled with osx.

Typically these are development related libraries and the most common use of these tools is for developers working on osx.

They both need the xcode command line tools installed (which you can download separately from https://developer.apple.com/), and for some specific packages you will need the entire xcode IDE installed.

xcode can be installed from the mac app store, its a free download but it takes a while since its around 5GB (if I remember correctly).

macports is an osx version of the port utility from BSD (as osx is derived from BSD, this was a natural choice). For anyone familiar with any of the BSD distributions, macports will feel right at home.

One major difference between homebrew and macports; and the reason I prefer homebrew is that it will not overwrite things that should be installed "natively" in osx. This means that if there is a native package available, homebrew will notify you instead of overwriting it and causing problems further down the line. It also installs libraries in the user space (thus, you don't need to use "sudo" to install things). This helps when getting rid of libraries as well since everything is in a path accessible to you.

homebrew also enjoys a more active user community and its packages (called formulas) are updated quite often.


macports does not overwrite native OSX packages - it supplies its own version - This is the main reason I prefer macports over home-brew, you need to be certain of what you are using and Apple's change at different times to the ports and have been know to be years behind updates in some projects

Can you give a reference showing that macports overwrites native OS X packages? As far as I can tell, all macports installation happens in /opt/local

Perhaps I should clarify - I did not say anywhere in my answer that macports overwrites OSX native packages. They both install items separately.

Homebrew will warn you when you should install things "natively" (using the library/tool's preferred installer) for better compatibility. This is what I meant. It will also use as many of the local libraries that are available in OS X. From the wiki:

We really don’t like dupes in Homebrew/homebrew

However, we do like dupes in the tap!

Stuff that comes with OS X or is a library that is provided by RubyGems, CPAN or PyPi should not be duped. There are good reasons for this:

  • Duplicate libraries regularly break builds
  • Subtle bugs emerge with duplicate libraries, and to a lesser extent, duplicate tools
  • We want you to try harder to make your formula work with what OS X comes with

You can optionally overwrite the macosx supplied versions of utilities with homebrew.

Parallel.ForEach vs Task.Factory.StartNew

Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

How to select the row with the maximum value in each group

A dplyr solution:

library(dplyr)
ID <- c(1,1,1,2,2,2,2,3,3)
Value <- c(2,3,5,2,5,8,17,3,5)
Event <- c(1,1,2,1,2,1,2,2,2)
group <- data.frame(Subject=ID, pt=Value, Event=Event)

group %>%
    group_by(Subject) %>%
    summarize(max.pt = max(pt))

This yields the following data frame:

  Subject max.pt
1       1      5
2       2     17
3       3      5

Python sum() function with list parameter

In the last answer, you don't need to make a list from numbers; it is already a list:

numbers = [1, 2, 3]
numsum = sum(numbers)
print(numsum)

How can I find the number of days between two Date objects in Ruby?

This worked for me:

(endDate - beginDate).to_i

What is .htaccess file?

You are allow to use php_value to change php setting in .htaccess file. Same like how php.ini did.

Example:

php_value date.timezone Asia/Kuala_Lumpur

For other php setting, please read http://www.php.net/manual/en/ini.list.php

Maven with Eclipse Juno

You should be able to install m2e (maven project for eclipse) using the Help -> Install New Software dialog. On that dialog open the Juno site (http://download.eclipse.org/releases/juno) and expand the Collaboration group (or type m2e into the filter). Select the two m2e options and follow the installation dialog

How to get indices of a sorted array in Python

If you do not want to use numpy,

sorted(range(len(seq)), key=seq.__getitem__)

is fastest, as demonstrated here.

How do I append a node to an existing XML file in java

You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));

Element root = document.getDocumentElement();

for (Server newServer : Collection<Server> bunchOfNewServers){
  Element server = Document.createElement("server");
  /* create and setup the server node...*/

 root.appendChild(server);
}

/* use whatever method to output DOM to XML (for example, using transformer like you did).*/

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

Calculate the display width of a string in Java

It doesn't always need to be toolkit-dependent or one doesn't always need use the FontMetrics approach since it requires one to first obtain a graphics object which is absent in a web container or in a headless enviroment.

I have tested this in a web servlet and it does calculate the text width.

import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

...

String text = "Hello World";
AffineTransform affinetransform = new AffineTransform();     
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);     
Font font = new Font("Tahoma", Font.PLAIN, 12);
int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
int textheight = (int)(font.getStringBounds(text, frc).getHeight());

Add the necessary values to these dimensions to create any required margin.

What are some reasons for jquery .focus() not working?

This solved!!!

setTimeout(function(){
    $("#name").filter(':visible').focus();
}, 500);

You can adjust time accordingly.

CSS "and" and "or"

To select properties a AND b of a X element:

X[a][b]

To select properties a OR b of a X element:

X[a],X[b]

Foreach loop, determine which is the last iteration of the loop

var last = objList.LastOrDefault();
foreach (var item in objList)
{
  if (item.Equals(last))
  {
  
  }
}

Getting "type or namespace name could not be found" but everything seems ok?

To solve this issue it can also help to delete and recreate the *.sln.DotSettings file of the associated solution.

JPanel setBackground(Color.BLACK) does nothing

You need to create a new Jpanel object in the Board constructor. for example

public Board(){
    JPanel pane = new JPanel();
    pane.setBackground(Color.ORANGE);// sets the background to orange
} 

How to store NULL values in datetime fields in MySQL?

Specifically relating to the error you're getting, you can't do something like this in PHP for a nullable field in MySQL:

$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . null . ')';

Because null in PHP will equate to an empty string which is not the same as a NULL value in MysQL. Instead you want to do this:

$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . (is_null($col2) ? 'NULL' : $col2). ')';

Of course you don't have to use is_null but I figure that it demonstrates the point a little better. Probably safer to use empty() or something like that. And if $col2 happens to be a string which you would enclose in double quotes in the query, don't forget not to include those around the 'NULL' string, otherwise it wont work.

Hope that helps!

Can I call methods in constructor in Java?

Why not to use Static Initialization Blocks ? Additional details here: Static Initialization Blocks

how to convert a string to an array in php

Take a look at the explode function.

<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>

Redirect to specified URL on PHP script completion?

Note that this will not work:

header('Location: $url');

You need to do this (for variable expansion):

header("Location: $url");

Working with huge files in VIM

It's already late but if you just want to navigate through the file without editing it, cat can do the job too.

% cat filename | less

or alternatively simple:

% less filename

Publish to IIS, setting Environment Variable

To extend on @tredder's answer you can alter the environmentVariables using appcmd

Staging

%windir%\system32\inetsrv\appcmd set config "staging.example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Staging'] /commit:APPHOST

Production

%windir%\system32\inetsrv\appcmd set config "example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Production'] /commit:APPHOST

How to insert double and float values to sqlite?

I think you should give the data types of the column as NUMERIC or DOUBLE or FLOAT or REAL

Read http://sqlite.org/datatype3.html to more info.

How to list all AWS S3 objects in a bucket using Java

This worked for me.

Thread thread = new Thread(new Runnable(){
    @Override
    public void run() {
        try {
            List<String> listing = getObjectNamesForBucket(bucket, s3Client);
            Log.e(TAG, "listing "+ listing);

        }
        catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "Exception found while listing "+ e);
        }
    }
});

thread.start();



  private List<String> getObjectNamesForBucket(String bucket, AmazonS3 s3Client) {
        ObjectListing objects=s3Client.listObjects(bucket);
        List<String> objectNames=new ArrayList<String>(objects.getObjectSummaries().size());
        Iterator<S3ObjectSummary> oIter=objects.getObjectSummaries().iterator();
        while (oIter.hasNext()) {
            objectNames.add(oIter.next().getKey());
        }
        while (objects.isTruncated()) {
            objects=s3Client.listNextBatchOfObjects(objects);
            oIter=objects.getObjectSummaries().iterator();
            while (oIter.hasNext()) {
                objectNames.add(oIter.next().getKey());
            }
        }
        return objectNames;
}

How to get a Docker container's IP address from the host

The accepted answer does not work well with multiple networks per container:

> docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' cc54d96d63ea

172.20.0.4172.18.0.5

The next best answer is closer:

> docker inspect cc54d96d63ea | grep "IPAddress"

"SecondaryIPAddresses": null,
"IPAddress": "",
    "IPAddress": "172.20.0.4",
    "IPAddress": "172.18.0.5",

I like to use jq to parse the network JSON:

> docker inspect cc54d96d63ea | jq -r 'map(.NetworkSettings.Networks) []'

{
  "proxy": {
    "IPAMConfig": null,
    "Links": [
      "server1_php_1:php",
      "server1_php_1:php_1",
      "server1_php_1:server1_php_1"
    ],
    "Aliases": [
      "cc54d96d63ea",
      "web"
    ],
    "NetworkID": "7779959d7383e9cef09c970c38c24a1a6ff44695178d314e3cb646bfa30d9935",
    "EndpointID": "4ac2c26113bf10715048579dd77304008904186d9679cdbc8fcea65eee0bf13b",
    "Gateway": "172.20.0.1",
    "IPAddress": "172.20.0.4",
    "IPPrefixLen": 24,
    "IPv6Gateway": "",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "MacAddress": "02:42:ac:14:00:04",
    "DriverOpts": null
  },
  "webservers": {
    "IPAMConfig": null,
    "Links": [
      "server1_php_1:php",
      "server1_php_1:php_1",
      "server1_php_1:server1_php_1"
    ],
    "Aliases": [
      "cc54d96d63ea",
      "web"
    ],
    "NetworkID": "907a7fba8816cd0ad89b7f5603bbc91122a2dd99902b504be6af16427c11a0a6",
    "EndpointID": "7febabe380d040b96b4e795417ba0954a103ac3fd37e9f6110189d9de92fbdae",
    "Gateway": "172.18.0.1",
    "IPAddress": "172.18.0.5",
    "IPPrefixLen": 24,
    "IPv6Gateway": "",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "MacAddress": "02:42:ac:12:00:05",
    "DriverOpts": null
  }
}

To list the IP addresses of every container then becomes:

for s in `docker ps -q`; do
  echo `docker inspect -f "{{.Name}}" ${s}`:
  docker inspect ${s} | jq -r 'map(.NetworkSettings.Networks) []' | grep "IPAddress";
done

/server1_web_1:
    "IPAddress": "172.20.0.4",
    "IPAddress": "172.18.0.5",
/server1_php_1:
    "IPAddress": "172.20.0.3",
    "IPAddress": "172.18.0.4",
/docker-gen:
    "IPAddress": "172.18.0.3",
/nginx-proxy:
    "IPAddress": "172.20.0.2",
    "IPAddress": "172.18.0.2",

How to show DatePickerDialog on Button click?

Following code works..

datePickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(0);
        }
    });

@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
    return new DatePickerDialog(this, datePickerListener, year, month, day);
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear,
                          int selectedMonth, int selectedDay) {
        day = selectedDay;
        month = selectedMonth;
        year = selectedYear;
        datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
                + selectedYear);
    }
};

Get the data received in a Flask request

To parse JSON, use request.get_json().

@app.route("/something", methods=["POST"])
def do_something():
    result = handle(request.get_json())
    return jsonify(data=result)

How to use UIScrollView in Storyboard

You should only set the contentSize property on the viewDidAppear, like this sample:

- (void)viewDidAppear:(BOOL)animated{

     [super viewDidAppear:animated];
     self.scrollView.contentSize=CGSizeMake(306,400.0);

}

It solve the autolayout problems, and works fine on iOS7.