Programs & Examples On #Click

In user interfaces, click refers to the depressing of a mouse button or similar input device.

Simulate a click on 'a' element using javascript/jquery

The code you've already tried:

document.getElementById("gift-close").click();

...should work as long as the element actually exists in the DOM at the time you run it. Some possible ways to ensure that include:

  1. Run your code from an onload handler for the window. http://jsfiddle.net/LKNYg/
  2. Run your code from a document ready handler if you're using jQuery. http://jsfiddle.net/LKNYg/1/
  3. Put the code in a script block that is after the element in the source html.

So:

$(document).ready(function() {
    document.getElementById("gift-close").click();
    // OR
    $("#gift-close")[0].click();
});

HTML/Javascript Button Click Counter

After looking at the code you're having typos, here is the updated code

var clicks = 0; // should be var not int
    function clickME() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks; //getElementById() not getElementByID() Which you corrected in edit
 }

Demo

Note: Don't use in-built handlers, as .click() is javascript function try giving different name like clickME()

trigger click event from angularjs directive

This is an extension to Langdon's answer with a directive approach to the problem. If you're going to have multiple galleries on the page this may be one way to go about it without much fuss.

Usage:

<gallery images="items"></gallery>
<gallery images="cats"></gallery>

See it working here

How to handle ListView click in Android

You need to set the inflated view "Clickable" and "able to listen to click events" in your adapter class getView() method.

convertView = mInflater.inflate(R.layout.list_item_text, null);
convertView.setClickable(true);
convertView.setOnClickListener(myClickListener);

and declare the click listener in your ListActivity as follows,

public OnClickListener myClickListener = new OnClickListener() {
public void onClick(View v) {
                 //code to be written to handle the click event
    }
};

This holds true only when you are customizing the Adapter by extending BaseAdapter.

Refer the ANDROID_SDK/samples/ApiDemos/src/com/example/android/apis/view/List14.java for more details

open a url on click of ok button in android

create an intent and set an action for it while passing the url to the intent

yourbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String theurl = "http://google.com";
                Uri urlstr = Uri.parse(theurl);
                Intent urlintent = new Intent();
                urlintent.setData(urlstr);
                urlintent.setAction(Intent.ACTION_VIEW);
                startActivity(urlintent);

How to create a checkbox with a clickable label?

You could also use CSS pseudo elements to pick and display your labels from all your checkbox's value attributes (respectively).
Edit: This will only work with webkit and blink based browsers (Chrome(ium), Safari, Opera....) and thus most mobile browsers. No Firefox or IE support here.
This may only be useful when embedding webkit/blink onto your apps.

<input type="checkbox" value="My checkbox label value" />
<style>
[type=checkbox]:after {
    content: attr(value);
    margin: -3px 15px;
    vertical-align: top;
    white-space:nowrap;
    display: inline-block;
}
</style>

All pseudo element labels will be clickable.

Demo:http://codepen.io/mrmoje/pen/oteLl, + The gist of it

CSS Animation onClick

Add a

-webkit-animation-play-state: paused;

to your CSS file, then you can control whether the animation is running or not by using this JS line:

document.getElementById("myDIV").style.WebkitAnimationPlayState = "running";

if you want the animation to run once, every time you click. Remember to set

-webkit-animation-iteration-count: 1;

how to make div click-able?

I suggest to use jQuery:

$('#mydiv')
  .css('cursor', 'pointer')
  .click(
    function(){
     alert('Click event is fired');
    }
  )
  .hover(
    function(){
      $(this).css('background', '#ff00ff');
    },
    function(){
      $(this).css('background', '');
    }
  );

Using jQuery to programmatically click an <a> link

If you are using jQuery, you can do it with jQuery.trigger http://api.jquery.com/trigger/

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
    <a id="foo" onclick="action()"></a>
    <script type="text/javascript">
        function action(){
            window.location.replace("http://stackoverflow.com/q/9081426/5526354")
        }

        $("#foo").trigger("click");
    </script>
</body>
</html>

jQuery click events firing multiple times

In my case, onclick event was firing multiple times coz I had made a generic event handler comparatively as

  `$('div').on("click", 'a[data-toggle="tab"]',function () {
        console.log("dynamic bootstrap tab clicked");
        var href = $(this).attr('href');
        window.location.hash = href;
   });`

changed to

    `$('div#mainData').on("click", 'a[data-toggle="tab"]',function () {
        console.log("dynamic bootstrap tab clicked");
        var href = $(this).attr('href');
        window.location.hash = href;
    });`

and also have to make separate handlers for static and dynamic clicks, for static tab click

    `$('a[data-toggle="tab"]').on("click",function () {
        console.log("static bootstrap tab clicked");
        var href = $(this).attr('href');
        window.location.hash = href;
    });`

How to make a whole 'div' clickable in html and css without JavaScript?

<div onclick="location.href='#';" style="cursor: pointer;">
</div>

Get clicked element using jQuery on event?

The conventional way of handling this doesn't play well with ES6. You can do this instead:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);

  this.delete(clickedElement.data('id'));
});

Note that the event target will be the clicked element, which may not be the element you want (it could be a child that received the event). To get the actual element:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);
  const targetElement = clickedElement.closest('.delete');

  this.delete(targetElement.data('id'));
});

jQuery click events not working in iOS

Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.

Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):

onClick=""

OR

The element css needs to have the following declaration:

cursor:pointer

Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working

Combine hover and click functions (jQuery)?

Use mouseover instead hover.

$('#target').on('click mouseover', function () {
    // Do something for both
});

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Check Safari developer reference on Touch class.

According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX and not PageX

Javascript Click on Element by Class

If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll('.love-button.love-button--loved'); 

for (i = 0; i < divs.length; ++i) {
  divs[i].click();
};

With ES6 and Babel (cannot be run in the browser console directly)

[...document.querySelectorAll('.love-button.love-button--loved')]
   .forEach(div => { div.click(); })

How to do "If Clicked Else .."

This is all you need: http://api.jquery.com/click/

Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.

How to get the id of the element clicked using jQuery

I wanted to share how you can use this to change a attribute of the button, because it took me some time to figure it out...

For example in order to change it's background to yellow:

$("#"+String(this.id)).css("background-color","yellow");

exit application when click button - iOS

You can use exit method to quit an ios app :

exit(0);

You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

jQuery click anywhere in the page except on 1 div

here is what i did. wanted to make sure i could click any of the children in my datepicker without closing it.

$('html').click(function(e){
    if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
        // clicked menu content or children
    } else {
        // didnt click menu content
    }
});

my actual code:

$('html').click(function(e){
    if (e.target.id != 'datepicker'
        && $(e.target).parents('#datepicker').length == 0
        && !$(e.target).hasClass('datepicker')
    ) {
        $('#datepicker').remove();
    }
});

How to stop default link click behavior with jQuery

$('.update-cart').click(function(e) {
    updateCartWidget();
    e.stopPropagation();
    e.preventDefault();
});

$('.update-cart').click(function() {
    updateCartWidget();
    return false;
});

The following methods achieve the exact same thing.

C# Checking if button was clicked

button1, button2 and button3 have same even handler

private void button1_Click(Object sender, EventArgs e)
    {
        Button btnSender = (Button)sender;
        if (btnSender == button1 || btnSender == button2)
        {
            //some code here
        }
        else if (btnSender == button3)
            //some code here
    }

Clicking submit button of an HTML form by a Javascript code

You can do :

document.forms["loginForm"].submit()

But this won't call the onclick action of your button, so you will need to call it by hand.

Be aware that you must use the name of your form and not the id to access it.

How to remove all click event handlers using jQuery?

Is there a way to remove all previous click events that have been assigned to a button?

$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});

Created Button Click Event c#

    public MainWindow()
    {
        // This button needs to exist on your form.
        myButton.Click += myButton_Click;
    }

    void myButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Message here");
        this.Close();
    }

Play sound on button click android

This is the most important part in the code provided in the original post.

Button one = (Button) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        mp.start();
    }
});

To explain it step by step:

Button one = (Button) this.findViewById(R.id.button1);

First is the initialization of the button to be used in playing the sound. We use the Activity's findViewById, passing the Id we assigned to it (in this example's case: R.id.button1), to get the button that we need. We cast it as a Button so that it is easy to assign it to the variable one that we are initializing. Explaining more of how this works is out of scope for this answer. This gives a brief insight on how it works.

final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);

This is how to initialize a MediaPlayer. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create() method and pass it the context and the resource Id of the sound we want to play, in this case R.raw.soho. We declare it as final. Jon Skeet provided a great explanation on why we do so here.

one.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        //code
    }
});

Finally, we set what our previously initialized button will do. Play a sound on button click! To do this, we set the OnClickListener of our button one. Inside is only one method, onClick() which contains what instructions the button should do on click.

public void onClick(View v) {
    mp.start();
}

To play the sound, we call MediaPlayer's start() method. This method starts the playback of the sound.

There, you can now play a sound on button click in Android!


Bonus part:

As noted in the comment belowThanks Langusten Gustel!, and as recommended in the Android Developer Reference, it is important to call the release() method to free up resources that will no longer be used. Usually, this is done once the sound to be played has completed playing. To do so, we add an OnCompletionListener to our mp like so:

mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        //code
    }
});

Inside the onCompletion method, we release it like so:

public void onCompletion(MediaPlayer mp) {
    mp.release();
}

There are obviously better ways of implementing this. For example, you can make the MediaPlayer a class variable and handle its lifecycle along with the lifecycle of the Fragment or Activity that uses it. However, this is a topic for another question. To keep the scope of this answer small, I wrote it just to illustrate how to play a sound on button click in Android.


Original Post

First. You should put your statements inside a block, and in this case the onCreate method.

Second. You initialized the button as variable one, then you used a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.

Third, put the logic to play the sound inside the onClick.

In summary:

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BasicScreenActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic_screen);

        Button one = (Button)this.findViewById(R.id.button1);
        final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
        one.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {
                mp.start();
            }
        });
    }
}

How to trigger a click on a link using jQuery

Since this question is ranked #1 in Google for "triggering a click on an <a> element" and no answer actually mentions how you do that, this is how you do it:

$('#titleee a')[0].click();

Explanation: you trigger a click on the underlying html-element, not the jQuery-object.

You're welcome googlers :)

How do I programmatically click a link with javascript?

The jQuery way to click a link is

$('#LinkID').click();

For mailTo link, you have to write the following code

$('#LinkID')[0].click();

Hide particular div onload and then show div after click

You are missing # hash character before id selectors, this should work:

$(document).ready(function() {
    $("#div2").hide();

    $("#preview").click(function() {
      $("#div1").hide();
      $("#div2").show();
    });

});

Learn More about jQuery ID Selectors

HTML "overlay" which allows clicks to fall through to elements behind it

In case anyone else is running in to the same problem, the only solution I could find that satisfied me was to have the canvas cover everything and then to raise the Z-index of all clickable elements. You can't draw on them, but at least they are clickable...

Add and remove a class on click using jQuery?

Why not try something like this?

$('#menu li a').on('click', function(){
    $('#menu li a.current').removeClass('current');
    $(this).addClass('current');
});

JSFiddle

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

JavaScript/jQuery doesn't support the default behavior of links "clicked" programmatically.

Instead, you can create a form and submit it. This way you don't have to use window.location or window.open, which are often blocked as unwanted popups by browsers.

This script has two different methods: one that tries to open three new tabs/windows (it opens only one in Internet Explorer and Chrome, more information is below) and one that fires a custom event on a link click.

Here is how:

HTML

<html>
<head>
    <script src="jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="script.js" type="text/javascript"></script>
</head>

<body>
    <button id="testbtn">Test</button><br><br>

    <a href="https://google.nl">Google</a><br>
    <a href="http://en.wikipedia.org/wiki/Main_Page">Wikipedia</a><br>
    <a href="https://stackoverflow.com/">Stack Overflow</a>
</body>

</html>

jQuery (file script.js)

$(function()
{
    // Try to open all three links by pressing the button
    // - Firefox opens all three links
    // - Chrome only opens one of them without a popup warning
    // - Internet Explorer only opens one of them WITH a popup warning
    $("#testbtn").on("click", function()
    {
        $("a").each(function()
        {
            var form = $("<form></form>");
            form.attr(
            {
                id     : "formform",
                action : $(this).attr("href"),
                method : "GET",
                // Open in new window/tab
                target : "_blank"
            });

            $("body").append(form);
            $("#formform").submit();
            $("#formform").remove();
        });
    });

    // Or click the link and fire a custom event
    // (open your own window without following 
    // the link itself)
    $("a").on("click", function()
    {
        var form = $("<form></form>");
        form.attr(
        {
            id     : "formform",
            // The location given in the link itself
            action : $(this).attr("href"),
            method : "GET",
            // Open in new window/tab
            target : "_blank"
        });

        $("body").append(form);
        $("#formform").submit();
        $("#formform").remove();

        // Prevent the link from opening normally
        return false;
    });
});

For each link element, it:

  1. Creates a form
  2. Gives it attributes
  3. Appends it to the DOM so it can be submitted
  4. Submits it
  5. Removes the form from the DOM, removing all traces *Insert evil laugh*

Now you have a new tab/window loading "https://google.nl" (or any URL you want, just replace it). Unfortunately when you try to open more than one window this way, you get an Popup blocked messagebar when trying to open the second one (the first one is still opened).


More information on how I got to this method is found here:

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

How to trigger click event on href element

I was facing a similar issue how to click a button, instead of a link. It did not success in the methods .trigger('click') or [0].click(), and I did not know why. At last, the following was working for me:

$('#elementid').mousedown();

Use jquery click to handle anchor onClick()

You are assigning an onclick event inside an function. That means once the function has executed once, the second onclick event is assigned to the element as well.

Either assign the function onclick or use jquery click().

There's no need to have both

How do I detect a click outside an element?

This might be a better fix for some people.

$(".menu_link").click(function(){
    // show menu code
});

$(".menu_link").mouseleave(function(){
    //hide menu code, you may add a timer for 3 seconds before code to be run
});

I know mouseleave does not only mean a click outside, it also means leaving that element's area.

Once the menu itself is inside the menu_link element then the menu itself should not be a problem to click on or move on.

jQuery, checkboxes and .is(":checked")

Most fastest and easy way:

$('#myCheckbox').change(function(){
    alert(this.checked);
});

$el[0].checked;

$el - is jquery element of selection.

Enjoy!

trigger body click with jQuery

As mentioned by Seeker, the problem could have been that you setup the click() function too soon. From your code snippet, we cannot know where you placed the script and whether it gets run at the right time.

An important point is to run such scripts after the document is ready. This is done by placing the click() initialization within that other function as in:

jQuery(document).ready(function()
  {
    jQuery("body").click(function()
      {
        // ... your click code here ...
      });
  });

This is usually the best method, especially if you include your JavaScript code in your <head> tag. If you include it at the very bottom of the page, then the ready() function is less important, but it may still be useful.

How to bind 'touchstart' and 'click' events but not respond to both?

find the document scroll move difference (both horizontal and vertical ) touchstart and touchend , if one of them is larger than 1 pixel, then it is move rather than click

var touchstartverscrollpos , touchstarthorscrollpos;


    $('body').on('touchstart','.thumbnail',function(e){

        touchstartverscrollpos = $(document).scrollTop();
        touchstarthorscrollpos = $(document).scrollLeft();


    });



    $('body').on('touchend','.thumbnail',function(e){


        var touchendverscrollpos = $(document).scrollTop();
        var touchendhorscrollpos = $(document).scrollLeft();

        var verdiff = touchendverscrollpos - touchstartverscrollpos;
        var hordiff = touchendhorscrollpos - touchstarthorscrollpos;


        if (Math.abs(verdiff) <1 && Math.abs(hordiff)<1){

// do you own function () here 



            e.stopImmediatePropagation();

            return false;
        }

    });

python selenium click on button

For python, use the

from selenium.webdriver import ActionChains

and

ActionChains(browser).click(element).perform()

Why is this jQuery click function not working?

Just a quick check, if you are using client-side templating engine such as handlebars, your js will load after document.ready, hence there will be no element to bind the event to, therefore either use onclick handler or use it on the body and check for current target

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset the selected options

$('select option:selected').removeAttr('selected');

If you actually want to remove the options (although I don't think you mean this).

$('select').empty();

Substitute select for the most appropriate selector in your case (this may be by id or by CSS class). Using as is will reset all <select> elements on the page

$(document).on("click"... not working?

Try this:

$("#test-element").on("click" ,function() {
    alert("click");
});

The document way of doing it is weird too. That would make sense to me if used for a class selector, but in the case of an id you probably just have useless DOM traversing there. In the case of the id selector, you get that element instantly.

$(document).click() not working correctly on iPhone. jquery

On mobile iOS the click event does not bubble to the document body and thus cannot be used with .live() events. If you have to use a non native click-able element like a div or section is to use cursor: pointer; in your css for the non-hover on the element in question. If that is ugly you could look into delegate().

jQuery Button.click() event is triggered twice

Unless you want your button to be a submit button, code it as Remove items That should solve your problem. If you do not specify the type for a button element, it will default to a submit button, leading to the problem you identified.

Difference between .on('click') vs .click()

As far as ilearned from internet and some friends .on() is used when you dynamically add elements. But when i used it in a simple login page where click event should send AJAX to node.js and at return append new elements it started to call multi-AJAX calls. When i changed it to click() everything went right. Actually i did not faced with this problem before.

How to click an element in Selenium WebDriver using JavaScript

const {Builder, By, Key, util} = require('selenium-webdriver')

// FUNÇÃO PARA PAUSA
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function example() {

    // chrome
    let driver = await new Builder().forBrowser("firefox").build()
    await driver.get('https://www.google.com.br')
    // await driver.findElement(By.name('q')).sendKeys('Selenium' ,Key.RETURN)

    await sleep(2000)

    await driver.findElement(By.name('q')).sendKeys('Selenium')

    await sleep(2000)

    // CLICAR
    driver.findElement(By.name('btnK')).click()


}
example()

Com essas últimas linhas, você pode clicar !

C# Creating an array of arrays

What you need to do is this:

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[][] lists = new int[][] {  list1 ,  list2 ,  list3 ,  list4  };

Another alternative would be to create a List<int[]> type:

List<int[]> data=new List<int[]>(){list1,list2,list3,list4};

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

Counting the occurrences / frequency of array elements

Try this:

Array.prototype.getItemCount = function(item) {
    var counts = {};
    for(var i = 0; i< this.length; i++) {
        var num = this[i];
        counts[num] = counts[num] ? counts[num]+1 : 1;
    }
    return counts[item] || 0;
}

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

How to Execute SQL Server Stored Procedure in SQL Developer?

You don't need EXEC clause. Simply use

proc_name paramValue1, paramValue2

(and you need commas as Misnomer mentioned)

How to add a new audio (not mixing) into a video using ffmpeg?

None of these solutions quite worked for me. My original audio was being overwritten, or I was getting an error like "failed to map memory" with the more complex 'amerge' example. It seems I needed -filter_complex amix.

ffmpeg -i videowithaudioyouwanttokeep.mp4 -i audiotooverlay.mp3 -vcodec copy -filter_complex amix -map 0:v -map 0:a -map 1:a -shortest -b:a 144k out.mkv

Applying styles to tables with Twitter Bootstrap

Just another good looking table. I added "table-hover" class because it gives a nice hovering effect.

   <h3>NATO Phonetic Alphabet</h3>    
   <table class="table table-striped table-bordered table-condensed table-hover">
   <thead>
    <tr> 
        <th>Letter</th>
        <th>Phonetic Letter</th>

    </tr>
    </thead>
  <tr>
    <th>A</th>
    <th>Alpha</th>

  </tr>
  <tr>
    <td>B</td>
    <td>Bravo</td>

  </tr>
  <tr>
    <td>C</td>
    <td>Charlie</td>

  </tr>

</table>

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Javascript event handler with parameters

Short answer:

x.addEventListener("click", function(e){myfunction(e, param1, param2)});

... 

function myfunction(e, param1, param1) {
    ... 
} 

How to get MAC address of client using PHP?

The MAC address (the low-level local network interface address) does not survive hops through IP routers. You can't find the client MAC address from a remote server.

In a local subnet, the MAC addresses are mapped to IP addresses through the ARP system. Interfaces on the local net know how to map IP addresses to MAC addresses. However, when your packets have been routed on the local subnet to (and through) the gateway out to the "real" Internet, the originating MAC address is lost. Simplistically, each subnet-to-subnet hop of your packets involve the same sort of IP-to-MAC mapping for local routing in each subnet.

How prevent CPU usage 100% because of worker process in iis

I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.

Solution:

First of all find the application which is causing heavy memory usage.

You can find this in the Details section of the Task Manager.

Next.

  1. Open the IIS manager.
  2. Click on Application Pools. You'll find many application pools which your system is using.
  3. Now from the task manager you've found which application is causing the heavy memory consumption. There would be multiple options for that and you need to select the one which is having '1' in it's Application column of your web application.
  4. When you click on the application pool on the right hand side you'll see an option Advance settings under Edit Application pools. Go to Advanced Settings. 5.Now under General category set the Enable 32-bit Applications to True
  5. Restart the IIS server or you can see the consumption goes down in performance section of your Task Manager.

If this solution works for you please add a comment so that I can know.

How to save an activity state using save instance state?

Not sure if my solution is frowned upon or not, but I use a bound service to persist ViewModel state. Whether you store it in memory in the service or persist and retrieve it from a SQLite database depends on your requirements. This is what services of any flavor do, they provide services such as maintaining application state and abstract common business logic.

Because of memory and processing constraints inherent on mobile devices, I treat Android views in a similar way to a web page. The page does not maintain state, it is purely a presentation layer component whose only purpose is to present application state and accept user input. Recent trends in web app architecture employ the use of the age-old Model, View, Controller (MVC) pattern, where the page is the View, domain data is the model, and the controller sits behind a web service. The same pattern can be employed in Android with the View being, well ... the View, the model is your domain data, and the Controller is implemented as an Android bound service. Whenever you want a view to interact with the controller, bind to it on start/resume and unbind on stop/pause.

This approach gives you the added bonus of enforcing the Separation of Concern design principle in that all of you application business logic can be moved into your service which reduces duplicated logic across multiple views and allows the view to enforce another important design principle, Single Responsibility.

Select 2 columns in one and combine them

The + operator should do the trick just fine. Keep something in mind though, if one of the columns is null or does not have any value, it will give you a NULL result. Instead, combine + with the function COALESCE and you'll be set.

Here is an example:

SELECT COALESCE(column1,'') + COALESCE(column2,'') FROM table1. 

For this example, if column1 is NULL, then the results of column2 will show up, instead of a simple NULL.

Hope this helps!

Changing text of UIButton programmatically swift

Swift 3

When you make the @IBAction:

@IBAction func btnAction(_ sender: UIButton) {
  sender.setTitle("string goes here", for: .normal)
}

This sets the sender as UIButton (instead of Any) so it targets the btnAction as a UIButton

SQL Server find and replace specific word in all rows of specific column

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'

or simply this if you are sure that you have no values like this CKIT002

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')

What is boilerplate code?

A boilerplate is a unit of writing that can be reused over and over without change. By extension, the idea is sometimes applied to reusable programming, as in “boilerplate code

How to place Text and an Image next to each other in HTML?

You can use vertical-align and floating.

In most cases you want to vertical-align: middle, the image.

Here is a test: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_vertical-align

vertical-align: baseline|length|sub|super|top|text-top|middle|bottom|text-bottom|initial|inherit;

For middle, the definition is: The element is placed in the middle of the parent element.

So you might want to apply that to all elements within the element.

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

What does -save-dev mean in npm install grunt --save-dev

For me the first answer appears a bit confusing, so to make it short and clean:

npm install <package_name> saves any specified packages into dependencies by default. Additionally, you can control where and how they get saved with some additional flags:

npm install <package_name> --no-save Prevents saving to dependencies.

npm install <package_name> ---save-dev updates the devDependencies in your package. These are only used for local testing and development.

You can read more at in the dcu

mysql.h file can't be found

For those who are using Eclipse IDE.

After installing the full MySQL together with mysql client and mysql server and any mysql dev libraries,

You will need to tell Eclipse IDE about the following

  • Where to find mysql.h
  • Where to find libmysqlclient library
  • The path to search for libmysqlclient library

Here is how you go about it.

To Add mysql.h

1. GCC C Compiler -> Includes -> Include paths(-l) then click + and add path to your mysql.h In my case it was /usr/include/mysql

enter image description here

To add mysqlclient library and search path to where mysqlclient library see steps 3 and 4.

2. GCC C Linker -> Libraries -> Libraries(-l) then click + and add mysqlcient

enter image description here

3. GCC C Linker -> Libraries -> Library search path (-L) then click + and add search path to mysqlcient. In my case it was /usr/lib64/mysql because I am using a 64 bit Linux OS and a 64 bit MySQL Database.

Otherwise, if you are using a 32 bit Linux OS, you may find that it is found at /usr/lib/mysql

enter image description here

How do I get a substring of a string in Python?

a="Helloo"
print(a[:-1])

In the above code, [:-1] declares to print from the starting till the maximum limit-1.

OUTPUT :

>>> Hello

Note: Here a [:-1] is also the same as a [0:-1] and a [0:len(a)-1]

a="I Am Siva"
print(a[2:])

OUTPUT:

>>> Am Siva

In the above code a [2:] declares to print a from index 2 till the last element.

Remember that if you set the maximum limit to print a string, as (x) then it will print the string till (x-1) and also remember that the index of a list or string will always start from 0.

How to bring view in front of everything?

Thanks to Stack user over this explanation, I've got this working even on Android 4.1.1

((View)myView.getParent()).requestLayout();
myView.bringToFront();

On my dynamic use, for example, I did

public void onMyClick(View v)
     {
     ((View)v.getParent()).requestLayout();
     v.bringToFront();
     }

And Bamm !

How to delete a file or folder?

My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.

In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...

It also wraps shutil.rmtree:

$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib

# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)

# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)

you can find it on github or PyPi


Disclaimer: I'm the author of the pathlib3x library.

Jquery select this + class

Use $(this).find(), or pass this in context, using jQuery context with selector.

Using $(this).find()

$(".class").click(function(){
     $(this).find(".subclass").css("visibility","visible");
});

Using this in context, $( selector, context ), it will internally call find function, so better to use find on first place.

$(".class").click(function(){
     $(".subclass", this).css("visibility","visible");
});

Javascript : get <img> src and set as variable?

As long as the script is after the img, then:

var youtubeimgsrc = document.getElementById("youtubeimg").src;

See getElementById in the DOM specification.

If the script is before the img, then of course the img doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body element.


Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:

<img id="foo" src="/images/example.png">

...the src reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com, document.getElementById("foo").src would give you "http://www.example.com/images/example.png".

If you wanted the src attribute's content as is, without being resolved, you'd use getAttribute instead: document.getElementById("foo").getAttribute("src"). That would give you "/images/example.png" with my example above.

If you have an absolute URL, like the one in your question, it doesn't matter.

This version of the application is not configured for billing through Google Play

If you want to debug IAB what do you have to do is:

  1. Submit to google play a version of your app with the IAB permission on the manifest:

  2. Add a product to your app on google play: Administering In-app Billing

  3. Set a custom debug keystore signed: Configure Eclipse to use signed keystore

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

I had similar issue but got solved when I corrected my zookeeper.yaml file which had the service name mismatch with file deployment's container names. It got resolved by making them same.

apiVersion: v1
kind: Service
metadata:
  name: zk1
  namespace: nbd-mlbpoc-lab
  labels:
    app: zk-1
spec:
  ports:
  - name: client
    port: 2181
    protocol: TCP
  - name: follower
    port: 2888
    protocol: TCP
  - name: leader
    port: 3888
    protocol: TCP
  selector:
    app: zk-1
---
kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  name: zk-deployment
  namespace: nbd-mlbpoc-lab
spec:
  template:
    metadata:
      labels:
        app: zk-1
    spec:
      containers:
      - name: zk1
        image: digitalwonderland/zookeeper
        ports:
        - containerPort: 2181
        env:
        - name: ZOOKEEPER_ID
          value: "1"
        - name: ZOOKEEPER_SERVER_1
          value: zk1

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:

var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); 
return des.data.Count.ToString();

Deserializing JSON array into strongly typed .NET object

Getting data from selected datagridview row and which event?

You can use SelectionChanged event since you are using FullRowSelect selection mode. Than inside the handler you can access SelectedRows property and get data from it. Example:

private void dataGridView_SelectionChanged(object sender, EventArgs e) 
{
    foreach (DataGridViewRow row in dataGridView.SelectedRows) 
    {
        string value1 = row.Cells[0].Value.ToString();
        string value2 = row.Cells[1].Value.ToString();
        //...
    }
}

You can also walk through the column collection instead of typing indexes...

PHP-FPM and Nginx: 502 Bad Gateway

All right after trying every solution on the web I ended up figuare out the issue using very simple method , first I cheked php-fpm err log

cat /var/log/php5-fpm.log 

and the most repeated error was

" WARNING: [pool www] server reached pm.max_children setting (5), consider raising it "

I edit PHP-fpm pools setting

nano /etc/php5/fpm/pool.d/www.conf

I chenged This Line

pm.max_children = 5

To new Value

pm.max_children = 10

BTW I'm using low end VPS with 128MB ram As everyone else I was thinkin redusing pm.max_children will make my server run faster consume less memory , but the setting we using were too low tho even start PHP-fpm process . I hope this help others since I found this after 24 hour testing and failing , ever my webhost support were not able to solve the issue .

Script Tag - async & defer

Keep your scripts right before </body>. Async can be used with scripts located there in a few circumstances (see discussion below). Defer won't make much of a difference for scripts located there because the DOM parsing work has pretty much already been done anyway.

Here's an article that explains the difference between async and defer: http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/.

Your HTML will display quicker in older browsers if you keep the scripts at the end of the body right before </body>. So, to preserve the load speed in older browsers, you don't want to put them anywhere else.

If your second script depends upon the first script (e.g. your second script uses the jQuery loaded in the first script), then you can't make them async without additional code to control execution order, but you can make them defer because defer scripts will still be executed in order, just not until after the document has been parsed. If you have that code and you don't need the scripts to run right away, you can make them async or defer.

You could put the scripts in the <head> tag and set them to defer and the loading of the scripts will be deferred until the DOM has been parsed and that will get fast page display in new browsers that support defer, but it won't help you at all in older browsers and it isn't really any faster than just putting the scripts right before </body> which works in all browsers. So, you can see why it's just best to put them right before </body>.

Async is more useful when you really don't care when the script loads and nothing else that is user dependent depends upon that script loading. The most often cited example for using async is an analytics script like Google Analytics that you don't want anything to wait for and it's not urgent to run soon and it stands alone so nothing else depends upon it.

Usually the jQuery library is not a good candidate for async because other scripts depend upon it and you want to install event handlers so your page can start responding to user events and you may need to run some jQuery-based initialization code to establish the initial state of the page. It can be used async, but other scripts will have to be coded to not execute until jQuery is loaded.

JavaScript: filter() for Objects

If you have Symbol properties in your object, that should be filtered too, you can not use: Object.keys Object.entries Object.fromEntries, ... because:

Symbol keys are not enumerable !

You could use Reflect.ownKeys and filter keys in reduce

Reflect.ownKeys(o).reduce((a, k) => allow.includes(k) && {...a, [k]: o[k]} || a, {});

(Open DevTools for log output - Symbols are not logged on Stackoverflow UI)

_x000D_
_x000D_
const bKey = Symbol('b_k');
const o = {
    a:                 1,
    [bKey]:            'b',
    c:                 [1, 3],
    [Symbol.for('d')]: 'd'
};

const allow = ['a', bKey, Symbol.for('d')];

const z1 = Reflect.ownKeys(o).reduce((a, k) => allow.includes(k) && {...a, [k]: o[k]} || a, {});

console.log(z1);                   // {a: 1, Symbol(b_k): "b", Symbol(d): "d"}
console.log(bKey in z1)            // true
console.log(Symbol.for('d') in z1) // true
_x000D_
_x000D_
_x000D_

This is equal to this

const z2 = Reflect.ownKeys(o).reduce((a, k) => allow.includes(k) && Object.assign(a, {[k]: o[k]}) || a, {});
const z3 = Reflect.ownKeys(o).reduce((a, k) => allow.includes(k) && Object.defineProperty(a, k, {value: o[k]}) || a, {});

console.log(z2); // {a: 1, Symbol(b_k): "b", Symbol(d): "d"}
console.log(z3); // {a: 1, Symbol(b_k): "b", Symbol(d): "d"}

Wrapped in a filter() function, an optional target object could be passed

const filter = (o, allow, t = {}) => Reflect.ownKeys(o).reduce(
    (a, k) => allow.includes(k) && {...a, [k]: o[k]} || a, 
    t
);

console.log(filter(o, allow));           // {a: 1, Symbol(b_k): "b", Symbol(d): "d"}
console.log(filter(o, allow, {e: 'e'})); // {a: 1, e: "e", Symbol(b_k): "b", Symbol(d): "d"}

Can I write native iPhone apps using Python?

I think it was not possible earlier but I recently heard about PyMob, which seems interesting because the apps are written in Python and the final outputs are native source codes in various platforms (Obj-C for iOS, Java for Android etc). This is certainly quite unique. This webpage explains it in more detail.

I haven't given it a shot yet, but will take a look soon.

Android: Go back to previous activity

If you have setup correctly the AndroidManifest.xml file with activity parent, you can use :

NavUtils.navigateUpFromSameTask(this);

Where this is your child activity.

How to add a border to a widget in Flutter?

Using BoxDecoration() is the best way to show border.

Container(
  decoration: BoxDecoration(
    border: Border.all(
    color: Color(0xff000000),
    width: 4,
  )),
  child: //Your child widget
),

You can also view full format here

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

Codesign wants to access key "access" in your keychain, I put in my login password but keeps asking me

Enter the password you use to open you Mac session and click on "Always allow" until all alerts are closed. The other buttons do not work...

How do I install imagemagick with homebrew?

You could try:

brew update && brew install imagemagick

True and False for && logic and || Logic table

I think You ask for Boolean algebra which describes the output of various operations performed on boolean variables. Just look at the article on Wikipedia.

'invalid value encountered in double_scalars' warning, possibly numpy

It looks like a floating-point calculation error. Check the numpy.seterr function to get more information about where it happens.

Playing HTML5 video on fullscreen in android webview

Edit: please see my other answer, as you probably don't need this now.

As you said, in API levels 11+ a HTML5VideoFullScreen$VideoSurfaceView is passed. But I don't think you are right when you say that "it doens't have a MediaPlayer".

This is the way to reach the MediaPlayer instance from the HTML5VideoFullScreen$VideoSurfaceView instance using reflection:

@SuppressWarnings("rawtypes")
Class c1 = Class.forName("android.webkit.HTML5VideoFullScreen$VideoSurfaceView");
Field f1 = c1.getDeclaredField("this$0");
f1.setAccessible(true);

@SuppressWarnings("rawtypes")
Class c2 = f1.getType().getSuperclass();
Field f2 = c2.getDeclaredField("mPlayer");
f2.setAccessible(true);

Object ___html5VideoViewInstance = f1.get(focusedChild); // Look at the code in my other answer to this same question to see whats focusedChild

Object ___mpInstance = f2.get(___html5VideoViewInstance); // This is the MediaPlayer instance.

So, now you could set the onCompletion listener of the MediaPlayer instance like this:

OnCompletionListener ocl = new OnCompletionListener()
{
    @Override
    public void onCompletion(MediaPlayer mp)
    {
        // Do stuff
    }
};

Method m1 = f2.getType().getMethod("setOnCompletionListener", new Class[] { Class.forName("android.media.MediaPlayer$OnCompletionListener") });
m1.invoke(___mpInstance, ocl);

The code doesn't fail but I'm not completely sure if that onCompletion listener will really be called or if it could be useful to your situation. But just in case someone would like to try it.

Python TypeError must be str not int

Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

Best practices for API versioning?

Versioning your REST API is analogous to the versioning of any other API. Minor changes can be done in place, major changes might require a whole new API. The easiest for you is to start from scratch every time, which is when putting the version in the URL makes most sense. If you want to make life easier for the client you try to maintain backwards compatibility, which you can do with deprecation (permanent redirect), resources in several versions etc. This is more fiddly and requires more effort. But it's also what REST encourages in "Cool URIs don't change".

In the end it's just like any other API design. Weigh effort against client convenience. Consider adopting semantic versioning for your API, which makes it clear for your clients how backwards compatible your new version is.

Pass Method as Parameter using C#

You can use the Func delegate in .net 3.5 as the parameter in your RunTheMethod method. The Func delegate allows you to specify a method that takes a number of parameters of a specific type and returns a single argument of a specific type. Here is an example that should work:

public class Class1
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }

    public bool Test()
    {
        return RunTheMethod(Method1);
    }
}

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

@CookieValue(value="abc",required=true) String m

when I changed required from true to false,it worked out.

JavaScript replace/regex

Your regex pattern should have the g modifier:

var pattern = /[somepattern]+/g;

notice the g at the end. it tells the replacer to do a global replace.

Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

var pattern = /[0-9a-zA-Z]+/g;

a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");

But you would need to change your replace function to this:

this.markup = this.markup.replace(pattern, value);

How to count number of records per day?

SELECT DateAdded, COUNT(1) AS NUMBERADDBYDAY
FROM Responses
WHERE DateAdded >= dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded

struct.error: unpack requires a string argument of length 4

By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.

To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding:

>>> struct.calcsize('=BH')
3

The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.

How can I let a table's body scroll but keep its head fixed in place?

Live JsFiddle

It is possible with only HTML & CSS

_x000D_
_x000D_
table.scrollTable {_x000D_
  border: 1px solid #963;_x000D_
  width: 718px;_x000D_
}_x000D_
_x000D_
thead.fixedHeader {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
thead.fixedHeader tr {_x000D_
  height: 30px;_x000D_
  background: #c96;_x000D_
}_x000D_
_x000D_
thead.fixedHeader tr th {_x000D_
  border-right: 1px solid black;_x000D_
}_x000D_
_x000D_
tbody.scrollContent {_x000D_
  display: block;_x000D_
  height: 262px;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
tbody.scrollContent td {_x000D_
  background: #eee;_x000D_
  border-right: 1px solid black;_x000D_
  height: 25px;_x000D_
}_x000D_
_x000D_
tbody.scrollContent tr.alternateRow td {_x000D_
  background: #fff;_x000D_
}_x000D_
_x000D_
thead.fixedHeader th {_x000D_
  width: 233px;_x000D_
}_x000D_
_x000D_
thead.fixedHeader th:last-child {_x000D_
  width: 251px;_x000D_
}_x000D_
_x000D_
tbody.scrollContent td {_x000D_
  width: 233px;_x000D_
}
_x000D_
<table cellspacing="0" cellpadding="0" class="scrollTable">_x000D_
  <thead class="fixedHeader">_x000D_
    <tr class="alternateRow">_x000D_
      <th>Header 1</th>_x000D_
      <th>Header 2</th>_x000D_
      <th>Header 3</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody class="scrollContent">_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>End of Cell Content 1</td>_x000D_
      <td>End of Cell Content 2</td>_x000D_
      <td>End of Cell Content 3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

setTimeout in for-loop does not print consecutive values

The function argument to setTimeout is closing over the loop variable. The loop finishes before the first timeout and displays the current value of i, which is 3.

Because JavaScript variables only have function scope, the solution is to pass the loop variable to a function that sets the timeout. You can declare and call such a function like this:

for (var i = 1; i <= 2; i++) {
    (function (x) {
        setTimeout(function () { alert(x); }, 100);
    })(i);
}

How to create number input field in Flutter?

The TextField widget is required to set keyboardType: TextInputType.number, and inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly] to accept numbers only as input.

     TextField(
            keyboardType: TextInputType.number,
            inputFormatters: <TextInputFormatter>[
              FilteringTextInputFormatter.digitsOnly
            ], // Only numbers can be entered
          ),

Example in DartPad

screenshot of dartpad

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

    void main() => runApp(new MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: HomePage(),
          theme: ThemeData(primarySwatch: Colors.blue),
        );
      }
    }
    
    class HomePage extends StatefulWidget {
      @override
      State<StatefulWidget> createState() {
        return HomePageState();
      }
    }
    
    class HomePageState extends State<HomePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: Container(
              padding: const EdgeInsets.all(40.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text("This Input accepts Numbers only"),
                  SizedBox(height: 20),
                  TextField(
                    decoration: InputDecoration(
                      focusedBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(color: Colors.greenAccent, width: 5.0),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.red, width: 5.0),
                      ),
                      hintText: 'Mobile Number',
                    ),
                    keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly
                    ], // Only numbers can be entered
                  ),
                  SizedBox(height: 20),
                  Text("You can test be Typing"),
                ],
              )),
        );
      }
    }

writing a batch file that opens a chrome URL

It's very simple. Just try:

start chrome https://www.google.co.in/

it will open the Google page in the Chrome browser.

If you wish to open the page in Firefox, try:

start firefox https://www.google.co.in/

Have Fun!

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

@Mihai-Andrei Dinculescu's answer is correct, but for the benefit of searchers, there is also a subtle point that can cause this error.

Adding a '/' on the end of your URL will stop EnableCors from working in all instances (e.g. from the homepage).

I.e. This will not work

var cors = new EnableCorsAttribute("http://testing.azurewebsites.net/", "*", "*");
config.EnableCors(cors);

but this will work:

var cors = new EnableCorsAttribute("http://testing.azurewebsites.net", "*", "*");
config.EnableCors(cors);

The effect is the same if using the EnableCors Attribute.

Automatically add all files in a folder to a target using CMake?

Extension for @Kleist answer:

Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB) and file(GLOB_RECURSE). With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.

However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.

Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB) or file(GLOB_RECURSE) for collect the sources.

Cannot read property 'getContext' of null, using canvas

You should put javascript tag in your html file. because browser load your webpage according to html flow, you should put your javascript file<script src="javascript/game.js"> after the <canvas>element tag. otherwise,if you put your javascript in the header of html.Browser load script first but it doesn't find the canvas. So your canvas doesn't work.

Split string to equal length substrings in Java

public static String[] split(String src, int len) {
    String[] result = new String[(int)Math.ceil((double)src.length()/(double)len)];
    for (int i=0; i<result.length; i++)
        result[i] = src.substring(i*len, Math.min(src.length(), (i+1)*len));
    return result;
}

Copying files using rsync from remote server to local machine

I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).

If you have configured ssh key to connect to your remote server, you could use the following command:

rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/

Where v option is --verbose, a option is --archive - archive mode, P option same as --partial - keep partially transferred files, e option is --rsh=COMMAND - specifying the remote shell to use.

rsync man page

Best practices for copying files with Maven

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.3</version>
        </plugin>
    </plugins>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include> **/*.properties</include>
            </includes>
        </resource>
    </resources>
    ...
</build>

Passing struct to function

You need to specify a type on person:

void addStudent(struct student person) {
...
}

Also, you can typedef your struct to avoid having to type struct every time you use it:

typedef struct student{
...
} student_t;

void addStudent(student_t person) {
...
}

Could not find module FindOpenCV.cmake ( Error in configuration process)

Another possibility is to denote where you can find OpenCV_DIR in the CMakeLists.txt file. For example, the following cmake scripts work for me:

cmake_minimum_required(VERSION 2.8)

project(performance_test)

set(OpenCV_STATIC ON)
set(OpenCV_CUDA OFF)
set(OpenCV_DIR "${CMAKE_SOURCE_DIR}/../install")

find_package(OpenCV REQUIRED)

include_directories(${OpenCV_INCLUDE_DIRS})

link_directories(${OpenCV_LIB_DIR})

file(GLOB my_source_files ./src/*)

add_executable( performance_test ${my_source_files})

target_link_libraries(performance_test ${OpenCV_LIBS})

Just to remind that you should set OpenCV_STATIC and OpenCV_CUDA as well before you invoke OpenCVConfig.cmake. In my case the built library is static library that does not use CUDA.

Case insensitive access for generic dictionary

There's no way to specify a StringComparer at the point where you try to get a value. If you think about it, "foo".GetHashCode() and "FOO".GetHashCode() are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.

You can, however, create a case-insensitive dictionary in the first place using:-

var comparer = StringComparer.OrdinalIgnoreCase;
var caseInsensitiveDictionary = new Dictionary<string, int>(comparer);

Or create a new case-insensitive dictionary with the contents of an existing case-sensitive dictionary (if you're sure there are no case collisions):-

var oldDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var newDictionary = new Dictionary<string, int>(oldDictionary, comparer);

This new dictionary then uses the GetHashCode() implementation on StringComparer.OrdinalIgnoreCase so comparer.GetHashCode("foo") and comparer.GetHashcode("FOO") give you the same value.

Alternately, if there are only a few elements in the dictionary, and/or you only need to lookup once or twice, you can treat the original dictionary as an IEnumerable<KeyValuePair<TKey, TValue>> and just iterate over it:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var value = myDictionary.FirstOrDefault(x => String.Equals(x.Key, myKey, comparer)).Value;

Or if you prefer, without the LINQ:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
int? value;
foreach (var element in myDictionary)
{
  if (String.Equals(element.Key, myKey, comparer))
  {
    value = element.Value;
    break;
  }
}

This saves you the cost of creating a new data structure, but in return the cost of a lookup is O(n) instead of O(1).

Change font color and background in html on mouseover

Either do it with CSS like the other answers did or change the text style color directly via the onMouseOver and onMouseOut event:

onmouseover="this.bgColor='white'; this.style.color='black'"

onmouseout="this.bgColor='black'; this.style.color='white'"

Git for beginners: The definitive practical guide

What is rebasing?

Rebase explanation taken from the book Pragmatic Guide to Git - Travis Swicegood

Chapter III

16 . Rewriting History by Rebasing

Rebasing commits is the one concept in Git that has no counterpart inside the traditional version control world. Using git rebase, you can rewrite the history of a repository in a variety of ways. It is one of the most powerful commands in Git, which makes it one of the most dangerous.

rebase takes a series of commits (normally a branch) and replays them on top of another commit (normally the last commit in another branch). The parent commit changes so all the commit IDs are recalculated. This can cause problems for other developers who have your code because the IDs don’t match up.

There’s a simple rule of thumb with git rebase: use it as much as you want on local commits. Once you’ve shared changes with another developer, the headache is generally not worth the trouble.

How to detect when an Android app goes to the background and come back to the foreground

I found a good method to detect application whether enter foreground or background. Here is my code. Hope this help you.

/**
 * Custom Application which can detect application state of whether it enter
 * background or enter foreground.
 *
 * @reference http://www.vardhan-justlikethat.blogspot.sg/2014/02/android-solution-to-detect-when-android.html
 */
 public abstract class StatusApplication extends Application implements ActivityLifecycleCallbacks {

public static final int STATE_UNKNOWN = 0x00;
public static final int STATE_CREATED = 0x01;
public static final int STATE_STARTED = 0x02;
public static final int STATE_RESUMED = 0x03;
public static final int STATE_PAUSED = 0x04;
public static final int STATE_STOPPED = 0x05;
public static final int STATE_DESTROYED = 0x06;

private static final int FLAG_STATE_FOREGROUND = -1;
private static final int FLAG_STATE_BACKGROUND = -2;

private int mCurrentState = STATE_UNKNOWN;
private int mStateFlag = FLAG_STATE_BACKGROUND;

@Override
public void onCreate() {
    super.onCreate();
    mCurrentState = STATE_UNKNOWN;
    registerActivityLifecycleCallbacks(this);
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    // mCurrentState = STATE_CREATED;
}

@Override
public void onActivityStarted(Activity activity) {
    if (mCurrentState == STATE_UNKNOWN || mCurrentState == STATE_STOPPED) {
        if (mStateFlag == FLAG_STATE_BACKGROUND) {
            applicationWillEnterForeground();
            mStateFlag = FLAG_STATE_FOREGROUND;
        }
    }
    mCurrentState = STATE_STARTED;

}

@Override
public void onActivityResumed(Activity activity) {
    mCurrentState = STATE_RESUMED;

}

@Override
public void onActivityPaused(Activity activity) {
    mCurrentState = STATE_PAUSED;

}

@Override
public void onActivityStopped(Activity activity) {
    mCurrentState = STATE_STOPPED;

}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

}

@Override
public void onActivityDestroyed(Activity activity) {
    mCurrentState = STATE_DESTROYED;
}

@Override
public void onTrimMemory(int level) {
    super.onTrimMemory(level);
    if (mCurrentState == STATE_STOPPED && level >= TRIM_MEMORY_UI_HIDDEN) {
        if (mStateFlag == FLAG_STATE_FOREGROUND) {
            applicationDidEnterBackground();
            mStateFlag = FLAG_STATE_BACKGROUND;
        }
    }else if (mCurrentState == STATE_DESTROYED && level >= TRIM_MEMORY_UI_HIDDEN) {
        if (mStateFlag == FLAG_STATE_FOREGROUND) {
            applicationDidDestroyed();
            mStateFlag = FLAG_STATE_BACKGROUND;
        }
    }
}

/**
 * The method be called when the application been destroyed. But when the
 * device screen off,this method will not invoked.
 */
protected abstract void applicationDidDestroyed();

/**
 * The method be called when the application enter background. But when the
 * device screen off,this method will not invoked.
 */
protected abstract void applicationDidEnterBackground();

/**
 * The method be called when the application enter foreground.
 */
protected abstract void applicationWillEnterForeground();

}

How to unload a package without restarting R

I would like to add an alternative solution. This solution does not directly answer your question on unloading a package but, IMHO, provides a cleaner alternative to achieve your desired goal, which I understand, is broadly concerned with avoiding name conflicts and trying different functions, as stated:

mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use

Solution

Function with_package offered via the withr package offers the possibility to:

attache a package to the search path, executes the code, then removes the package from the search path. The package namespace is not unloaded, however.

Example

library(withr)
with_package("ggplot2", {
  ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context 
exists("geom_point")
# [1] FALSE

geom_point used in the example is not accessible from the global namespace. I reckon it may be a cleaner way of handling conflicts than loading and unloading packages.

Can I have an IF block in DOS batch file?

Logically, Cody's answer should work. However I don't think the command prompt handles a code block logically. For the life of me I can't get that to work properly with any more than a single command within the block. In my case, extensive testing revealed that all of the commands within the block are being cached, and executed simultaneously at the end of the block. This of course doesn't yield the expected results. Here is an oversimplified example:

if %ERRORLEVEL%==0 (
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
)

This should provide var3 with the following value:

blue_cheese

but instead yields:

_

because all 3 commands are cached and executed simultaneously upon exiting the code block.

I was able to overcome this problem by re-writing the if block to only execute one command - goto - and adding a few labels. Its clunky, and I don't much like it, but at least it works.

if %ERRORLEVEL%==0 goto :error0
goto :endif

:error0
set var1=blue
set var2=cheese
set var3=%var1%_%var2%

:endif

Spring not autowiring in unit tests with JUnit

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {

    @Autowired
    protected SessionFactory sessionFactory;

    @Test
    public void testDBSourceIsCorrect() throws SQLException {
        String databaseProductName = sessionFactory.getCurrentSession()
                .connection()
                .getMetaData()
                .getDatabaseProductName();
        assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

undefined reference to `std::ios_base::Init::Init()'

You can resolve this in several ways:

  • Use g++ in stead of gcc: g++ -g -o MatSim MatSim.cpp
  • Add -lstdc++: gcc -g -o MatSim MatSim.cpp -lstdc++
  • Replace <string.h> by <string>

This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.

Convert a tensor to numpy array in Tensorflow?

If you see there is a method _numpy(), e.g for an EagerTensor simply call the above method and you will get an ndarray.

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

Functionally, you should be able to use

SELECT column_name
  FROM table_name
 WHERE TRIM(column_name) IS NULL

The problem there is that an index on COLUMN_NAME would not be used. You would need to have a function-based index on TRIM(column_name) if that is a selective condition.

Does the join order matter in SQL?

For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.*, b.*, c.*.


For (LEFT, RIGHT or FULL) OUTER joins, yes, the order matters - and (updated) things are much more complicated.

First, outer joins are not commutative, so a LEFT JOIN b is not the same as b LEFT JOIN a

Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id
  LEFT JOIN c
    ON c.ac_id = a.ac_id

is equivalent to:

a LEFT JOIN c 
    ON c.ac_id = a.ac_id
  LEFT JOIN b
    ON b.ab_id = a.ab_id

but:

a LEFT JOIN b 
    ON  b.ab_id = a.ab_id
  LEFT JOIN c
    ON  c.ac_id = a.ac_id
    AND c.bc_id = b.bc_id

is not equivalent to:

a LEFT JOIN c 
    ON  c.ac_id = a.ac_id
  LEFT JOIN b
    ON  b.ab_id = a.ab_id
    AND b.bc_id = c.bc_id

Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id          -- AB condition
 LEFT JOIN c
    ON c.bc_id = b.bc_id          -- BC condition

This is equivalent to a LEFT JOIN (b LEFT JOIN c):

a LEFT JOIN  
    b LEFT JOIN c
        ON c.bc_id = b.bc_id          -- BC condition
    ON b.ab_id = a.ab_id          -- AB condition

only because we have "nice" ON conditions. Both ON b.ab_id = a.ab_id and c.bc_id = b.bc_id are equality checks and do not involve NULL comparisons.

You can even have conditions with other operators or more complex ones like: ON a.x <= b.x or ON a.x = 7 or ON a.x LIKE b.x or ON (a.x, a.y) = (b.x, b.y) and the two queries would still be equivalent.

If however, any of these involved IS NULL or a function that is related to nulls like COALESCE(), for example if the condition was b.ab_id IS NULL, then the two queries would not be equivalent.

C# Enum - How to Compare Value

use this

if (userProfile.AccountType == AccountType.Retailer)
{
     ...
}

If you want to get int from your AccountType enum and compare it (don't know why) do this:

if((int)userProfile.AccountType == 1)
{ 
     ...
}

Objet reference not set to an instance of an object exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.

EDIT (thanks to @Rik and @KonradMorawski) :

Maybe you can do some check before:

if(userProfile!=null)
{
}

or

if(userProfile==null)
{
   throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

For those who are trying to use gulp for swagger local deployment, following code will help

var gulp = require("gulp");
var yaml = require("js-yaml");
var path = require("path");
var fs = require("fs");

//Converts yaml to json
gulp.task("swagger", done => {
    var doc = yaml.safeLoad(fs.readFileSync(path.join(__dirname,"api/swagger/swagger.yaml")));
    fs.writeFileSync(
        path.join(__dirname,"../yourjsonfile.json"),
        JSON.stringify(doc, null, " ")
        );
    done();
});

//Watches for changes    
gulp.task('watch', function() {
  gulp.watch('api/swagger/swagger.yaml', gulp.series('swagger'));  
});

Android SeekBar setOnSeekBarChangeListener

onProgressChanged() should be called on every progress changed, not just on first and last touch (that why you have onStartTrackingTouch() and onStopTrackingTouch() methods).

Make sure that your SeekBar have more than 1 value, that is to say your MAX>=3.

In your onCreate:

 yourSeekBar=(SeekBar) findViewById(R.id.yourSeekBar);
 yourSeekBar.setOnSeekBarChangeListener(new yourListener());

Your listener:

private class yourListener implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
                            // Log the progress
            Log.d("DEBUG", "Progress is: "+progress);
                            //set textView's text
            yourTextView.setText(""+progress);
        }

        public void onStartTrackingTouch(SeekBar seekBar) {}

        public void onStopTrackingTouch(SeekBar seekBar) {}

    }

Please share some code and the Log results for furter help.

How to remove stop words using nltk or python

In case your data are stored as a Pandas DataFrame, you can use remove_stopwords from textero that use the NLTK stopwords list by default.

import pandas as pd
import texthero as hero
df['text_without_stopwords'] = hero.remove_stopwords(df['text'])

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

I found that (at least in Visual Studio 2010) you need to set the output verbosity to at least Detailed to be able to spot the problem.

It might be that my problem was a reference that was previously a GAC reference, but that was no longer the case after my machine's reinstall.

A div with auto resize when changing window width\height

In this scenario, the outer <div> has a width and height of 90%. The inner div> has a width of 100% of its parent. Both scale when re-sizing the window.

HTML

<div>
    <div>Hello there</div>
</div>

CSS

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

body > div {
    width: 90%;
    height: 100%;
    background: green;
}

body > div > div {
    width: 100%;
    background: red;
}

Demo

Try before buy

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

I have made some researches on this subject recently. The way to implement it has to be different if the field is a TEXT field, a non unique field.

I have made some tests with a TEXT field. Considering the fact that we have a table with 1M entries. 37 entries are equal to 'something':

  • SELECT * FROM test WHERE text LIKE '%something%' LIMIT 1 with mysql_num_rows() : 0.039061069488525s. (FASTER)
  • SELECT count(*) as count FROM test WHERE text LIKE '%something% : 16.028197050095s.
  • SELECT EXISTS(SELECT 1 FROM test WHERE text LIKE '%something%') : 0.87045907974243s.
  • SELECT EXISTS(SELECT 1 FROM test WHERE text LIKE '%something%' LIMIT 1) : 0.044898986816406s.

But now, with a BIGINT PK field, only one entry is equal to '321321' :

  • SELECT * FROM test2 WHERE id ='321321' LIMIT 1 with mysql_num_rows() : 0.0089840888977051s.
  • SELECT count(*) as count FROM test2 WHERE id ='321321' : 0.00033879280090332s.
  • SELECT EXISTS(SELECT 1 FROM test2 WHERE id ='321321') : 0.00023889541625977s.
  • SELECT EXISTS(SELECT 1 FROM test2 WHERE id ='321321' LIMIT 1) : 0.00020313262939453s. (FASTER)

How to comment multiple lines with space or indent

Might just be for Visual Studio '15, if you right-click on source code, there's an option for insert comment

This puts summary tags around your comment section, but it does give the indentation that you want.

Converting Dictionary to List?

 >>> a = {'foo': 'bar', 'baz': 'quux', 'hello': 'world'}
 >>> list(reduce(lambda x, y: x + y, a.items()))
 ['foo', 'bar', 'baz', 'quux', 'hello', 'world']

To explain: a.items() returns a list of tuples. Adding two tuples together makes one tuple containing all elements. Thus the reduction creates one tuple containing all keys and values and then the list(...) makes a list from that.

Remove leading comma from a string

To turn a string into an array I usually use split()

> var s = ",'first string','more','even more'"
> s.split("','")
[",'first string", "more", "even more'"]

This is almost what you want. Now you just have to strip the first two and the last character:

> s.slice(2, s.length-1)
"first string','more','even more"

> s.slice(2, s.length-2).split("','");
["first string", "more", "even more"]

To extract a substring from a string I usually use slice() but substr() and substring() also do the job.

Passing arrays as parameters in bash

Requirement: Function to find a string in an array.
This is a slight simplification of DevSolar's solution in that it uses the arguments passed rather than copying them.

myarray=('foobar' 'foxbat')

function isInArray() {
  local item=$1
  shift
  for one in $@; do
    if [ $one = $item ]; then
      return 0   # found
    fi
  done
  return 1       # not found
}

var='foobar'
if isInArray $var ${myarray[@]}; then
  echo "$var found in array"
else
  echo "$var not found in array"
fi 

How to pass List from Controller to View in MVC 3

You can use the dynamic object ViewBag to pass data from Controllers to Views.

Add the following to your controller:

ViewBag.MyList = myList;

Then you can acces it from your view:

@ViewBag.MyList

// e.g.
@foreach (var item in ViewBag.MyList) { ... }

Push an associative item into an array in JavaScript

Another method for creating a JavaScript associative array

First create an array of objects,

 var arr = {'name': []};

Next, push the value to the object.

  var val = 2;
  arr['name'].push(val);

To read from it:

var val = arr.name[0];

Setting timezone in Python

You can use pytz as well..

import datetime
import pytz
def utcnow():
    return datetime.datetime.now(tz=pytz.utc)
utcnow()
   datetime.datetime(2020, 8, 15, 14, 45, 19, 182703, tzinfo=<UTC>)
utcnow().isoformat()

'

2020-08-15T14:45:21.982600+00:00'

How do I generate a random integer between min and max in Java?

As the solutions above do not consider the possible overflow of doing max-min when min is negative, here another solution (similar to the one of kerouac)

public static int getRandom(int min, int max) {
    if (min > max) {
        throw new IllegalArgumentException("Min " + min + " greater than max " + max);
    }      
    return (int) ( (long) min + Math.random() * ((long)max - min + 1));
}

this works even if you call it with:

getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE) 

How to clear input buffer in C?

But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'?? if so, in the input buffer still remains the '\n' character??? Am I misunderstanding something??

The thing you may not realize is that the comparison happens after getchar() removes the character from the input buffer. So when you reach the '\n', it is consumed and then you break out of the loop.

convert datetime to date format dd/mm/yyyy

As everyone else said, but remember CultureInfo.InvariantCulture!

string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)

OR escape the '/'.

Create a new database with MySQL Workbench

  1. Launch MySQL Workbench.
  2. On the left pane of the welcome window, choose a database to connect to under "Open Connection to Start Querying".
  3. The query window will open. On its left pane, there is a section titled "Object Browser", which shows the list of databases. (Side note: The terms "schema" and "database" are synonymous in this program.)
  4. Right-click on one of the existing databases and click "Create Schema...". This will launch a wizard that will help you create a database.

If you'd prefer to do it in SQL, enter this query into the query window:

CREATE SCHEMA Test

Press CTRL + Enter to submit it, and you should see confirmation in the output pane underneath the query window. You'll have to right-click on an existing schema in the Object panel and click "Refresh All" to see it show up, though.

Apache and IIS side by side (both listening to port 80) on windows2003

That's not quite true. E.g. for HTTP Windows supports URL based port sharing, allowing multiple processes to use the same IP address and Port.

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

Suppress output of a function

you can use 'capture.output' like below. This allows you to use the data later:

log <- capture.output({
  test <- CensReg.SMN(cc=cc,x=x,y=y, nu=NULL, type="Normal")
})

test$betas

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

As I faced this error, somewhere in your code your funcs or libraries that used run on different threads, so try to call all code on the same thread , it fixed my problem.

If you call methods on WebView from any thread other than your app's UI thread, it can cause unexpected results. For example, if your app uses multiple threads, you can use the runOnUiThread() method to ensure your code executes on the UI thread:

Google reference link

Find object by its property in array of objects with AngularJS way

The solucion that work for me is the following

$filter('filter')(data, {'id':10}) 

Convert text into number in MySQL query

This should work:

SELECT field,CONVERT(SUBSTRING_INDEX(field,'-',-1),UNSIGNED INTEGER) AS num
FROM table
ORDER BY num;

Unable to find valid certification path to requested target - error even after cert imported

Unfortunately - it could be many things - and lots of app servers and other java 'wrappers' are prone to play with properties and their 'own' take on keychains and what not. So it may be looking at something totally different.

Short of truss-ing - I'd try:

java -Djavax.net.debug=all -Djavax.net.ssl.trustStore=trustStore ...

to see if that helps. Instead of 'all' one can also set it to 'ssl', key manager and trust manager - which may help in your case. Setting it to 'help' will list something like below on most platforms.

Regardless - do make sure you fully understand the difference between the keystore (in which you have the private key and cert you prove your own identity with) and the trust store (which determines who you trust) - and the fact that your own identity also has a 'chain' of trust to the root - which is separate from any chain to a root you need to figure out 'who' you trust.

all            turn on all debugging
ssl            turn on ssl debugging

The   following can be used with ssl:
    record       enable per-record tracing
    handshake    print each handshake message
    keygen       print key generation data
    session      print session activity
    defaultctx   print default SSL initialization
    sslctx       print SSLContext tracing
    sessioncache print session cache tracing
    keymanager   print key manager tracing
    trustmanager print trust manager tracing
    pluggability print pluggability tracing

    handshake debugging can be widened with:
    data         hex dump of each handshake message
    verbose      verbose handshake message printing

    record debugging can be widened with:
    plaintext    hex dump of record plaintext
    packet       print raw SSL/TLS packets

Source: # See http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#Debug

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

No visible cause for "Unexpected token ILLEGAL"

This also could be happening if you're copying code from another document (like a PDF) into your console and trying to run it.

I was trying to run some example code out of a Javascript book I'm reading and was surprised it didn't run in the console.

Apparently, copying from the PDF introduces some unexpected, illegal, and invisible characters into the code.

How to get the number of characters in a string

There are several ways to get a string length:

package main

import (
    "bytes"
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    b := "?????"
    len1 := len([]rune(b))
    len2 := bytes.Count([]byte(b), nil) -1
    len3 := strings.Count(b, "") - 1
    len4 := utf8.RuneCountInString(b)
    fmt.Println(len1)
    fmt.Println(len2)
    fmt.Println(len3)
    fmt.Println(len4)

}

Example using Hyperlink in WPF

In addition to Fuji's response, we can make the handler reusable turning it into an attached property:

public static class HyperlinkExtensions
{
    public static bool GetIsExternal(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsExternalProperty);
    }

    public static void SetIsExternal(DependencyObject obj, bool value)
    {
        obj.SetValue(IsExternalProperty, value);
    }
    public static readonly DependencyProperty IsExternalProperty =
        DependencyProperty.RegisterAttached("IsExternal", typeof(bool), typeof(HyperlinkExtensions), new UIPropertyMetadata(false, OnIsExternalChanged));

    private static void OnIsExternalChanged(object sender, DependencyPropertyChangedEventArgs args)
    {
        var hyperlink = sender as Hyperlink;

        if ((bool)args.NewValue)
            hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
        else
            hyperlink.RequestNavigate -= Hyperlink_RequestNavigate;
    }

    private static void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
    {
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
        e.Handled = true;
    }
}

And use it like this:

<TextBlock>
    <Hyperlink NavigateUri="https://stackoverflow.com"
               custom:HyperlinkExtensions.IsExternal="true">
        Click here
    </Hyperlink>
</TextBlock>

Warning: #1265 Data truncated for column 'pdd' at row 1

You are most likely pushing a string 'NULL' to the table, rather then an actual NULL, but other things may be going on as well, an illustration:

mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)

mysql> show warnings;
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM date_test;
+------------+
| pdd        |
+------------+
| 0000-00-00 |
+------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
Query OK, 1 row affected (0.15 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)

mysql> SELECT * FROM date_test;
+------------+
| pdd        |
+------------+
| 0000-00-00 |
| NULL       |
+------------+
2 rows in set (0.00 sec)

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

I had the EXACT same issue as the OP. My configuration and situation were identical. I finally narrowed it down to being an issue in WCFStorm after creating a service reference in a test project in Visual Studio and confirming that the service was working. In Storm you need to click on the "Config" settings option (NOT THE "Client Config"). After clicking on that, click on the "Security" tab on the dialog that pops up. Make sure "Authentication Type" is set to "None" (The default is "Windows Authentication"). Presto, it works! I always test out my methods in WCFStorm as I'm building them out, but have never tried using it to connect to one that has already been set up on SSL. Hope this helps someone!

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

I have faced the same issue. I almost wasted almost couple of weeks to resolved this issue. Finally I had on doubt on myself and tried to create another project by copy and paste some startup files like SplashScreen & LoginScreen.

But with the same code still i was getting SPAN_EXCLUSIVE_EXCLUSIVE.

Then i have removed the handler code from splash screen and tried again and Wow its working. I am not getting SPAN_EXCLUSIVE_EXCLUSIVE issue in logcat.

I wondering, why it is? till the time did not get any other solution but by removing handler from splash screen it is working.

Try and update here if it is resolved or not.

GenyMotion Unable to start the Genymotion virtual device

In my case, the only option was to remove the VM and download it again. No re-configuration of the host-only adapter did not help, I used different addressing of DHCP. Virtual Box I updated to version 4.3.4 and Genymotion to 2.0.2

How do I concatenate strings with variables in PowerShell?

Try the Join-Path cmdlet:

Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
    Join-Path -Path  $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)" 
}

How to return temporary table from stored procedure

YES YOU CAN.

In your stored procedure, you fill the table @tbRetour.

At the very end of your stored procedure, you write:

SELECT * FROM @tbRetour 

To execute the stored procedure, you write:

USE [...]
GO

DECLARE @return_value int

EXEC @return_value = [dbo].[getEnregistrementWithDetails]
@id_enregistrement_entete = '(guid)'

GO

How to add,set and get Header in request of HttpClient?

You can use HttpPost, there are methods to add Header to the Request.

DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("header-name" , "header-value");

HttpResponse response = httpclient.execute(httpPost);

Applying function with multiple arguments to create a new pandas column

This solves the problem:

df['newcolumn'] = df.A * df.B

You could also do:

def fab(row):
  return row['A'] * row['B']

df['newcolumn'] = df.apply(fab, axis=1)

How do I select child elements of any depth using XPath?

//form/descendant::input[@type='submit']

Split data frame string column into multiple columns

This question is pretty old but I'll add the solution I found the be the simplest at present.

library(reshape2)
before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
newColNames <- c("type1", "type2")
newCols <- colsplit(before$type, "_and_", newColNames)
after <- cbind(before, newCols)
after$type <- NULL
after

jQuery - Dynamically Create Button and Attach Event Handler

You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html() call will not serialize the event.

IE6/IE7 css border on select element

Check out this code... hope ur happy :)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<style type="text/css">
*{margin:0;padding:0;}
select {font: normal 13px Arial, SansSerif, Verdana; color: black;}
.wrapper{width:198px; position: relative;  height: 20px; overflow: hidden; border-top:1px solid #dddddd; border-left:1px solid #dddddd;}
.Select{color: black; background: #fff;position: absolute; width: 200px; top: -2px; left: -2px;}
optgroup{background-color:#0099CC;color:#ffffff;}
</style>
</head>

<body>
<div class="wrapper">
<select class="Select">
<optgroup label="WebDevelopment"></optgroup>
<option>ASP</option>
<option>PHP</option>
<option>ColdFusion</option>
<optgroup label="Web Design"></optgroup>
<option>Adobe Photoshop</option>
<option>DreamWeaver</option>
<option>CSS</option>
<option>Adobe Flash</option>
</select>
</div>
</body>
</html>

Sajay

What's the best way to join on the same table twice?

First, I would try and refactor these tables to get away from using phone numbers as natural keys. I am not a fan of natural keys and this is a great example why. Natural keys, especially things like phone numbers, can change and frequently so. Updating your database when that change happens will be a HUGE, error-prone headache. *

Method 1 as you describe it is your best bet though. It looks a bit terse due to the naming scheme and the short aliases but... aliasing is your friend when it comes to joining the same table multiple times or using subqueries etc.

I would just clean things up a bit:

SELECT t.PhoneNumber1, t.PhoneNumber2, 
   t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2
FROM Table1 t
JOIN Table2 t1 ON t1.PhoneNumber = t.PhoneNumber1
JOIN Table2 t2 ON t2.PhoneNumber = t.PhoneNumber2

What i did:

  • No need to specify INNER - it's implied by the fact that you don't specify LEFT or RIGHT
  • Don't n-suffix your primary lookup table
  • N-Suffix the table aliases that you will use multiple times to make it obvious

*One way DBAs avoid the headaches of updating natural keys is to not specify primary keys and foreign key constraints which further compounds the issues with poor db design. I've actually seen this more often than not.

Get the length of a String

If you are just trying to see if a string is empty or not (checking for length of 0), Swift offers a simple boolean test method on String

myString.isEmpty

The other side of this coin was people asking in ObjectiveC how to ask if a string was empty where the answer was to check for a length of 0:

NSString is empty

Python 3 Online Interpreter / Shell

I recently came across Python 3 interpreter at CompileOnline.

git with development, staging and production branches

The thought process here is that you spend most of your time in development. When in development, you create a feature branch (off of development), complete the feature, and then merge back into development. This can then be added to the final production version by merging into production.

See A Successful Git Branching Model for more detail on this approach.

How to get address location from latitude and longitude in Google Map.?

You have to make one ajax call to get the required result, in this case you can use Google API to get the same

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false

Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level

How do I combine the first character of a cell with another cell in Excel?

Not sure why no one is using semicolons. This is how it works for me:

=CONCATENATE(LEFT(A1;1); B1)

Solutions with comma produce an error in Excel.

android pinch zoom

For android 2.2+ (api level8), you can use ScaleGestureDetector.

you need a member:

private ScaleGestureDetector mScaleDetector;

in your constructor (or onCreate()) you add:

mScaleDetector = new ScaleGestureDetector(context, new OnScaleGestureListener() {
    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
    }
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        return true;
    }
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        Log.d(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor());
        return false;
    }
});

You override onTouchEvent:

@Override
public boolean onTouchEvent(MotionEvent event) {
    mScaleDetector.onTouchEvent(event);
    return true;
}

If you draw your View by hand, in the onScale() you probably do store the scale factor in a member, then call invalidate() and use the scale factor when drawing in your onDraw(). Otherwise you can directly modify font sizes or things like that in the onScale().

Finding the 'type' of an input element

If you are using jQuery you can easily check the type of any element.

    function(elementID){    
    var type = $(elementId).attr('type');
    if(type == "text") //inputBox
     console.log("input text" + $(elementId).val().size());
   }

similarly you can check the other types and take appropriate action.

How can I stream webcam video with C#?

Another option to stream images from a webcam to a browser is via mjpeg. This is just a series of jpeg images that most modern browsers support as part of the tag. Here's a sample server written in c#:

https://www.codeproject.com/articles/371955/motion-jpeg-streaming-server

This works well over a LAN, but not as well over the internet as mjpeg is not as effcient as other video codecs (h264, VP8 etc..)

Group by with multiple columns using lambda

Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.

return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
                .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
                .SelectMany(a => a)
                .ToList();

Where CustomerGroupingKey takes the group keys:

    private class CustomerGroupingKey
    {
        public CustomerGroupingKey(string country, string gender)
        {
            Country = country;
            Gender = gender;
        }

        public string Country { get; }

        public string Gender { get; }
    }

Create an Oracle function that returns a table

  CREATE OR REPLACE PACKAGE BODY TEST AS 

   FUNCTION GET_UPS(
   TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
   STARTING_DATE_IN DATE,
   ENDING_DATE_IN DATE
   )RETURN MEASURE_TABLE IS

    T MEASURE_TABLE;

 BEGIN

    **SELECT   MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
             PERIOD,VALUE )  BULK COLLECT  INTO    T
    FROM    ...**

  ;

   RETURN T;

   END GET_UPS;

END TEST;

Android error: Failed to install *.apk on device *: timeout

Try changing the ADB connection timeout. I think it defaults that to 5000ms and I changed mine to 10000ms to get rid of that problem.

If you are in Eclipse, you can do this by going through

Window -> Preferences -> Android -> DDMS -> ADB Connection Timeout (ms)

Is there a MySQL option/feature to track history of changes to records?

Here's a straightforward way to do this:

First, create a history table for each data table you want to track (example query below). This table will have an entry for each insert, update, and delete query performed on each row in the data table.

The structure of the history table will be the same as the data table it tracks except for three additional columns: a column to store the operation that occured (let's call it 'action'), the date and time of the operation, and a column to store a sequence number ('revision'), which increments per operation and is grouped by the primary key column of the data table.

To do this sequencing behavior a two column (composite) index is created on the primary key column and revision column. Note that you can only do sequencing in this fashion if the engine used by the history table is MyISAM (See 'MyISAM Notes' on this page)

The history table is fairly easy to create. In the ALTER TABLE query below (and in the trigger queries below that), replace 'primary_key_column' with the actual name of that column in your data table.

CREATE TABLE MyDB.data_history LIKE MyDB.data;

ALTER TABLE MyDB.data_history MODIFY COLUMN primary_key_column int(11) NOT NULL, 
   DROP PRIMARY KEY, ENGINE = MyISAM, ADD action VARCHAR(8) DEFAULT 'insert' FIRST, 
   ADD revision INT(6) NOT NULL AUTO_INCREMENT AFTER action,
   ADD dt_datetime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER revision,
   ADD PRIMARY KEY (primary_key_column, revision);

And then you create the triggers:

DROP TRIGGER IF EXISTS MyDB.data__ai;
DROP TRIGGER IF EXISTS MyDB.data__au;
DROP TRIGGER IF EXISTS MyDB.data__bd;

CREATE TRIGGER MyDB.data__ai AFTER INSERT ON MyDB.data FOR EACH ROW
    INSERT INTO MyDB.data_history SELECT 'insert', NULL, NOW(), d.* 
    FROM MyDB.data AS d WHERE d.primary_key_column = NEW.primary_key_column;

CREATE TRIGGER MyDB.data__au AFTER UPDATE ON MyDB.data FOR EACH ROW
    INSERT INTO MyDB.data_history SELECT 'update', NULL, NOW(), d.*
    FROM MyDB.data AS d WHERE d.primary_key_column = NEW.primary_key_column;

CREATE TRIGGER MyDB.data__bd BEFORE DELETE ON MyDB.data FOR EACH ROW
    INSERT INTO MyDB.data_history SELECT 'delete', NULL, NOW(), d.* 
    FROM MyDB.data AS d WHERE d.primary_key_column = OLD.primary_key_column;

And you're done. Now, all the inserts, updates and deletes in 'MyDb.data' will be recorded in 'MyDb.data_history', giving you a history table like this (minus the contrived 'data_columns' column)

ID    revision   action    data columns..
1     1         'insert'   ....          initial entry for row where ID = 1
1     2         'update'   ....          changes made to row where ID = 1
2     1         'insert'   ....          initial entry, ID = 2
3     1         'insert'   ....          initial entry, ID = 3 
1     3         'update'   ....          more changes made to row where ID = 1
3     2         'update'   ....          changes made to row where ID = 3
2     2         'delete'   ....          deletion of row where ID = 2 

To display the changes for a given column or columns from update to update, you'll need to join the history table to itself on the primary key and sequence columns. You could create a view for this purpose, for example:

CREATE VIEW data_history_changes AS 
   SELECT t2.dt_datetime, t2.action, t1.primary_key_column as 'row id', 
   IF(t1.a_column = t2.a_column, t1.a_column, CONCAT(t1.a_column, " to ", t2.a_column)) as a_column
   FROM MyDB.data_history as t1 INNER join MyDB.data_history as t2 on t1.primary_key_column = t2.primary_key_column 
   WHERE (t1.revision = 1 AND t2.revision = 1) OR t2.revision = t1.revision+1
   ORDER BY t1.primary_key_column ASC, t2.revision ASC

Edit: Oh wow, people like my history table thing from 6 years ago :P

My implementation of it is still humming along, getting bigger and more unwieldy, I would assume. I wrote views and pretty nice UI to look at the history in this database, but I don't think it was ever used much. So it goes.

To address some comments in no particular order:

  • I did my own implementation in PHP that was a little more involved, and avoided some of the problems described in comments (having indexes transferred over, signifcantly. If you transfer over unique indexes to the history table, things will break. There are solutions for this in the comments). Following this post to the letter could be an adventure, depending on how established your database is.

  • If the relationship between the primary key and the revision column seems off it usually means the composite key is borked somehow. On a few rare occasions I had this happen and was at a loss to the cause.

  • I found this solution to be pretty performant, using triggers as it does. Also, MyISAM is fast at inserts, which is all the triggers do. You can improve this further with smart indexing (or lack of...). Inserting a single row into a MyISAM table with a primary key shouldn't be an operation you need to optimize, really, unless you have significant issues going on elsewhere. In the entire time I was running the MySQL database this history table implementation was on, it was never the cause of any of the (many) performance problems that came up.

  • if you're getting repeated inserts, check your software layer for INSERT IGNORE type queries. Hrmm, can't remember now, but I think there are issues with this scheme and transactions which ultimately fail after running multiple DML actions. Something to be aware of, at least.

  • It's important that the fields in the history table and the data table match up. Or, rather, that your data table doesn't have MORE columns than the history table. Otherwise, insert/update/del queries on the data table will fail, when the inserts to the history tables put columns in the query that don't exist (due to d.* in the trigger queries), and the trigger fails. t would be awesome if MySQL had something like schema-triggers, where you could alter the history table if columns were added to the data table. Does MySQL have that now? I do React these days :P

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

PHP Fatal error: Class 'PDO' not found

Ensure they are being called in the php.ini file

If the PDO is displayed in the list of currently installed php modules, you will want to check the php.ini file in the relevant folder to ensure they are being called. Somewhere in the php.ini file you should see the following:

extension=pdo.so
extension=pdo_sqlite.so
extension=pdo_mysql.so
extension=sqlite.so

If they are not present, simply add the lines above to the bottom of the php.ini file and save it.

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

Two more (similar) approaches with one generalized example:

1) first approach - removing field in save() method, e.g. (not tested ;) ):

def save(self, *args, **kwargs):
    for fname in self.readonly_fields:
        if fname in self.cleaned_data:
            del self.cleaned_data[fname]
    return super(<form-name>, self).save(*args,**kwargs)

2) second approach - reset field to initial value in clean method:

def clean_<fieldname>(self):
    return self.initial[<fieldname>] # or getattr(self.instance, fieldname)

Based on second approach I generalized it like this:

from functools                 import partial

class <Form-name>(...):

    def __init__(self, ...):
        ...
        super(<Form-name>, self).__init__(*args, **kwargs)
        ...
        for i, (fname, field) in enumerate(self.fields.iteritems()):
            if fname in self.readonly_fields:
                field.widget.attrs['readonly'] = "readonly"
                field.required = False
                # set clean method to reset value back
                clean_method_name = "clean_%s" % fname
                assert clean_method_name not in dir(self)
                setattr(self, clean_method_name, partial(self._clean_for_readonly_field, fname=fname))

    def _clean_for_readonly_field(self, fname):
        """ will reset value to initial - nothing will be changed 
            needs to be added dynamically - partial, see init_fields
        """
        return self.initial[fname] # or getattr(self.instance, fieldname)

Importing CSV data using PHP/MySQL

$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($i>0){
    $import="INSERT into importing(text,number)values('".$data[0]."','".$data[1]."')";
    mysql_query($import) or die(mysql_error());
}
$i=1;
}

How do I set multipart in axios with react?

Here's how I do file upload in react using axios

import React from 'react'
import axios, { post } from 'axios';

class SimpleReactFileUpload extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault() // Stop form submit
    this.fileUpload(this.state.file).then((response)=>{
      console.log(response.data);
    })
  }

  onChange(e) {
    this.setState({file:e.target.files[0]})
  }

  fileUpload(file){
    const url = 'http://example.com/file-upload';
    const formData = new FormData();
    formData.append('file',file)
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    return  post(url, formData,config)
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}



export default SimpleReactFileUpload

Source

Predicate in Java

A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:

public interface Predicate<ARGTYPE>
{
    public boolean evaluate(ARGTYPE arg);
}

And then you might have an implementation such as:

public class Tautology<E> implements Predicate<E>
{
     public boolean evaluate(E arg){
         return true;
     }
}

To get a better conceptual understanding, you might want to read about first-order logic.

Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.

Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true to a function instead of defining a named Tautology subclass like the above.

What is the different between RESTful and RESTless

REST stands for REpresentational State Transfer and goes a little something like this:

We have a bunch of uniquely addressable 'entities' that we want made available via a web application. Those entities each have some identifier and can be accessed in various formats. REST defines a bunch of stuff about what GET, POST, etc mean for these purposes.

the basic idea with REST is that you can attach a bunch of 'renderers' to different entities so that they can be available in different formats easily using the same HTTP verbs and url formats.

For more clarification on what RESTful means and how it is used google rails. Rails is a RESTful framework so there's loads of good information available in its docs and associated blog posts. Worth a read even if you arent keen to use the framework. For example: http://www.sitepoint.com/restful-rails-part-i/

RESTless means not restful. If you have a web app that does not adhere to RESTful principles then it is not RESTful

Where are $_SESSION variables stored?

Many of the answers above are opaque. In my opinion the author of this question simply wants to know where session variables are stored by default. According to this:https://canvas.seattlecentral.edu/courses/937693/pages/10-advanced-php-sessions they are simply stored on the server by default. Hopefully, others will find this contribution meaningful.

How to retrieve raw post data from HttpServletRequest in java

We had a situation where IE forced us to post as text/plain, so we had to manually parse the parameters using getReader. The servlet was being used for long polling, so when AsyncContext::dispatch was executed after a delay, it was literally reposting the request empty handed.

So I just stored the post in the request when it first appeared by using HttpServletRequest::setAttribute. The getReader method empties the buffer, where getParameter empties the buffer too but stores the parameters automagically.

    String input = null;

    // we have to store the string, which can only be read one time, because when the
    // servlet awakens an AsyncContext, it reposts the request and returns here empty handed
    if ((input = (String) request.getAttribute("com.xp.input")) == null) {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();

        String line;
        while((line = reader.readLine()) != null){
            buffer.append(line);
        }
        // reqBytes = buffer.toString().getBytes();

        input = buffer.toString();
        request.setAttribute("com.xp.input", input);
    }

    if (input == null) {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print("{\"act\":\"fail\",\"msg\":\"invalid\"}");
    }       

How to fix the height of a <div> element?

You can also use min-height and max-height. It was very useful for me

label or @html.Label ASP.net MVC 4

Depends on what your are doing.

If you have SPA (Single-Page Application) the you can use:

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

Otherwise using Html helpers is recommended, to get your controls bound with your model.

What is the difference between HTTP and REST?

REST is a specific way of approaching the design of big systems (like the web).

It's a set of 'rules' (or 'constraints').

HTTP is a protocol that tries to obey those rules.

CFNetwork SSLHandshake failed iOS 9

This error was showing up in the logs sometimes when I was using a buggy/crashy Cordova iOS version. It went away when I upgraded or downgraded cordova iOS.

The server I was connecting to was using TLSv1.2 SSL so I knew that was not the problem.

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

Create Generic method constraining T to an Enum

C# = 7.3

Starting with C# 7.3 (available with Visual Studio 2017 = v15.7), this code is now completely valid:

public static TEnum Parse<TEnum>(string value)
    where TEnum : struct, Enum
{
 ...
}

C# = 7.2

You can have a real compiler enforced enum constraint by abusing constraint inheritance. The following code specifies both a class and a struct constraints at the same time:

public abstract class EnumClassUtils<TClass>
where TClass : class
{

    public static TEnum Parse<TEnum>(string value)
    where TEnum : struct, TClass
    {
        return (TEnum) Enum.Parse(typeof(TEnum), value);
    }

}

public class EnumUtils : EnumClassUtils<Enum>
{
}

Usage:

EnumUtils.Parse<SomeEnum>("value");

Note: this is specifically stated in the C# 5.0 language specification:

If type parameter S depends on type parameter T then: [...] It is valid for S to have the value type constraint and T to have the reference type constraint. Effectively this limits T to the types System.Object, System.ValueType, System.Enum, and any interface type.

log4j: Log output of a specific class to a specific appender

Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern it will create 0 byte file and not write anything:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false"/>
        <param name="maxFileSize" value="1GB"/>
        <param name="maxBackupIndex" value="2"/>
        <param name="file" value="/tmp/bd.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <logger name="com.example.mypackage" additivity="false">
        <level value="debug"/>
        <appender-ref ref="bdfile"/>
    </logger>

    <root>
        <priority value="info"/>
        <appender-ref ref="bdfile"/>
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>

Jar mismatch! Fix your dependencies

Remove android-support-v4.jar file from the libs folder from your project.

Testing socket connection in Python

You should really post:

  1. The complete source code of your example
  2. The actual result of it, not a summary

Here is my code, which works:

import socket, sys

def alert(msg):
    print >>sys.stderr, msg
    sys.exit(1)

(family, socktype, proto, garbage, address) = \
         socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)

try:
    s.connect(address) 
except Exception, e:
    alert("Something's wrong with %s. Exception type is %s" % (address, e))

When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:

Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')

Footnotes for tables in LaTeX

If your table is already working with tabular, then easiest is to switch it to longtable, remembering to add

\usepackage{longtable}

For example:

\begin{longtable}{ll}
  2014--2015 & Something cool\footnote{first footnote} \\
  2016-- & Something cooler\footnote{second footnote}
\end{longtable}

Calling stored procedure with return value

Or if you're using EnterpriseLibrary rather than standard ADO.NET...

Database db = DatabaseFactory.CreateDatabase();
using (DbCommand cmd = db.GetStoredProcCommand("usp_GetNewSeqVal"))
{
    db.AddInParameter(cmd, "SeqName", DbType.String, "SeqNameValue");
    db.AddParameter(cmd, "RetVal", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);

    db.ExecuteNonQuery(cmd);

    var result = (int)cmd.Parameters["RetVal"].Value;
}

Loading a .json file into c# program

You really should use an established library, such as Newtonsoft.Json (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.

Here's a sample of reading JSON using Newtonsoft.Json:

JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));

// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
  JObject o2 = (JObject) JToken.ReadFrom(reader);
}

How to make a window always stay on top in .Net?

Why not making your form a dialogue box:

myForm.ShowDialog();

Ideal way to cancel an executing AsyncTask

Just discovered that AlertDialogs's boolean cancel(...); I've been using everywhere actually does nothing. Great.
So...

public class MyTask extends AsyncTask<Void, Void, Void> {

    private volatile boolean running = true;
    private final ProgressDialog progressDialog;

    public MyTask(Context ctx) {
        progressDialog = gimmeOne(ctx);

        progressDialog.setCancelable(true);
        progressDialog.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                // actually could set running = false; right here, but I'll
                // stick to contract.
                cancel(true);
            }
        });

    }

    @Override
    protected void onPreExecute() {
        progressDialog.show();
    }

    @Override
    protected void onCancelled() {
        running = false;
    }

    @Override
    protected Void doInBackground(Void... params) {

        while (running) {
            // does the hard work
        }
        return null;
    }

    // ...

}

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

You can do by xlwings as well

import xlwings as xw
for book in xlwings.books:
    print(book)

How in node to split string by newline ('\n')?

It looks like regex /\r\n|\r|\n/ handles CR, LF, and CRLF line endings, their mixed sequences, and keeps all the empty lines inbetween. Try that!

_x000D_
_x000D_
    function splitLines(t) { return t.split(/\r\n|\r|\n/); }

    // single newlines
    console.log(splitLines("AAA\rBBB\nCCC\r\nDDD"));
    // double newlines
    console.log(splitLines("EEE\r\rFFF\n\nGGG\r\n\r\nHHH"));
    // mixed sequences
    console.log(splitLines("III\n\r\nJJJ\r\r\nKKK\r\n\nLLL\r\n\rMMM"));
_x000D_
_x000D_
_x000D_

You should get these arrays as a result:

[ "AAA", "BBB", "CCC", "DDD" ]
[ "EEE", "", "FFF", "", "GGG", "", "HHH" ]
[ "III", "", "JJJ", "", "KKK", "", "LLL", "", "MMM" ]

You can also teach that regex to recognize other legit Unicode line terminators by adding |\xHH or |\uHHHH parts, where H's are hexadecimal digits of the additional terminator character codepoint (as seen in Wikipedia article as U+HHHH).

Align Bootstrap Navigation to Center

Add 'justified' class to 'ul'.

<ul class="nav navbar-nav justified">

CSS:

.justified {
    position:absolute;
    left:50%;
}

Now, calculate its 'margin-left' in order to align it to center.

// calculating margin-left to align it to center;
var width = $('.justified').width();
$('.justified').css('margin-left', '-' + (width / 2)+'px');

JSFiddle Code

JSFiddle Embedded Link

Cannot make a static reference to the non-static method

There are some good answers already with explanations of why the mixture of the non-static Context method getText() can't be used with your static final String.

A good question to ask is: why do you want to do this? You are attempting to load a String from your strings resource, and populate its value into a public static field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context into your other classes and call context.getText(R.string.TTT) from within them.

public class NonActivity {

    public static void doStuff(Context context) {
        String TTT = context.getText(R.string.TTT);
        ...
    }
}

And to call this from your Activity:

NonActivity.doStuff(this);

This will allow you to access your String resource without needing to use a public static field.

Getting all types that implement an interface

Edit: I've just seen the edit to clarify that the original question was for the reduction of iterations / code and that's all well and good as an exercise, but in real-world situations you're going to want the fastest implementation, regardless of how cool the underlying LINQ looks.

Here's my Utils method for iterating through the loaded types. It handles regular classes as well as interfaces, and the excludeSystemTypes option speeds things up hugely if you are looking for implementations in your own / third-party codebase.

public static List<Type> GetSubclassesOf(this Type type, bool excludeSystemTypes) {
    List<Type> list = new List<Type>();
    IEnumerator enumerator = Thread.GetDomain().GetAssemblies().GetEnumerator();
    while (enumerator.MoveNext()) {
        try {
            Type[] types = ((Assembly) enumerator.Current).GetTypes();
            if (!excludeSystemTypes || (excludeSystemTypes && !((Assembly) enumerator.Current).FullName.StartsWith("System."))) {
                IEnumerator enumerator2 = types.GetEnumerator();
                while (enumerator2.MoveNext()) {
                    Type current = (Type) enumerator2.Current;
                    if (type.IsInterface) {
                        if (current.GetInterface(type.FullName) != null) {
                            list.Add(current);
                        }
                    } else if (current.IsSubclassOf(type)) {
                        list.Add(current);
                    }
                }
            }
        } catch {
        }
    }
    return list;
}

It's not pretty, I'll admit.

Enable & Disable a Div and its elements in Javascript

You should be able to set these via the attr() or prop() functions in jQuery as shown below:

jQuery (< 1.7):

// This will disable just the div
$("#dcacl").attr('disabled','disabled');

or

// This will disable everything contained in the div
$("#dcacl").children().attr("disabled","disabled");

jQuery (>= 1.7):

// This will disable just the div
$("#dcacl").prop('disabled',true);

or

// This will disable everything contained in the div
$("#dcacl").children().prop('disabled',true);

or

//  disable ALL descendants of the DIV
$("#dcacl *").prop('disabled',true);

Javascript:

// This will disable just the div
document.getElementById("dcalc").disabled = true;

or

// This will disable all the children of the div
var nodes = document.getElementById("dcalc").getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++){
     nodes[i].disabled = true;
}

Adding a stylesheet to asp.net (using Visual Studio 2010)

Several things here.

First off, you're defining your CSS in 3 places!

In line, in the head and externally. I suggest you only choose one. I'm going to suggest externally.

I suggest you update your code in your ASP form from

<td style="background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;" 
        class="style6">

to this:

<td  class="style6">

And then update your css too

.style6
    {
        height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
    }

This removes the inline.

Now, to move it from the head of the webForm.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AR Toolbox</title>
    <link rel="Stylesheet" href="css/master.css" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<table class="style1">
    <tr>
        <td class="style6">
            <asp:Menu ID="Menu1" runat="server">
                <Items>
                    <asp:MenuItem Text="Home" Value="Home"></asp:MenuItem>
                    <asp:MenuItem Text="About" Value="About"></asp:MenuItem>
                    <asp:MenuItem Text="Compliance" Value="Compliance">
                        <asp:MenuItem Text="Item 1" Value="Item 1"></asp:MenuItem>
                        <asp:MenuItem Text="Item 2" Value="Item 2"></asp:MenuItem>
                    </asp:MenuItem>
                    <asp:MenuItem Text="Tools" Value="Tools"></asp:MenuItem>
                    <asp:MenuItem Text="Contact" Value="Contact"></asp:MenuItem>
                </Items>
            </asp:Menu>
        </td>
    </tr>
    <tr>
        <td class="style6">
            <img alt="South University'" class="style7" 
                src="file:///C:/Users/jnewnam/Documents/Visual%20Studio%202010/WebSites/WebSite1/img/suo_n_seal_hor_pantone.png" /></td>
    </tr>
    <tr>
        <td class="style2">
            <table class="style3">
                <tr>
                    <td>
                        &nbsp;</td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td style="color: #FFFFFF; background-color: #A3A3A3">
            This is the footer.</td>
    </tr>
</table>
</form>
</body>
</html>

Now, in a new file called master.css (in your css folder) add

ul {
list-style-type:none;
margin:0;
padding:0;
}

li {
display:inline;
padding:20px;
}
.style1
{
    width: 100%;
}
.style2
{
    height: 459px;
}
.style3
{
    width: 100%;
    height: 100%;
}
.style6
{
    height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
.style7
{
    width: 345px;
    height: 73px;
}

creating list of objects in Javascript

Maybe you can create an array like this:

     var myList = new Array();
     myList.push('Hello');
     myList.push('bye');

     for (var i = 0; i < myList .length; i ++ ){
        window.console.log(myList[i]);
     }

How to convert byte array to string and vice versa?

Read the bytes from String using ByteArrayInputStream and wrap it with BufferedReader which is Char Stream instead of Byte Stream which converts the byte data to String.

package com.cs.sajal;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class TestCls {

    public static void main(String[] args) {

        String s=new String("Sajal is  a good boy");

        try
        {
        ByteArrayInputStream bis;
        bis=new ByteArrayInputStream(s.getBytes("UTF-8"));

        BufferedReader br=new BufferedReader(new InputStreamReader(bis));
        System.out.println(br.readLine());

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}

Output is:

Sajal is a good boy

How do I update a formula with Homebrew?

I prefer to upgrade all homebrew formulae and homebrew cask formulae.

I added a Bourne shell function to my environment for this one (I load a .bashrc)

function updatebrew() {
set -x;
brew update;
brew cleanup;
brew cask upgrade --greedy
)
}
  • set -x for transparency: So that the terminal outputs whatever Homebrew is doing in the background.
  • brew update to update homebrew formulas
  • brew cleanup to remove any change left over after installations
  • brew cask upgrade --greedy will install all casks; both those with versioning information and those without

IsNullOrEmpty with Object

Why would you need any other way? Comparing an Object reference with null is the least-verbose way to check if it's null.

How to find serial number of Android device?

public static String getManufacturerSerialNumber() {
  String serial = null; 
  try {
      Class<?> c = Class.forName("android.os.SystemProperties");
      Method get = c.getMethod("get", String.class, String.class);
      serial = (String) get.invoke(c, "ril.serialnumber", "unknown");
  } catch (Exception ignored) {}
  return serial;
}

Works on API 29 and 30, tested on Samsung galaxy s7 s9 Xcover

OwinStartup not firing

If you've upgraded from an older MVC version make sure you don't have

  <add key="owin:AutomaticAppStartup" value="false" />

in your web.config. It will suppress calling the startup logic.

Instead change it to true

  <add key="owin:AutomaticAppStartup" value="true" />

I realize you already mentioned this but sometimes people (like me) don't read the whole question and just jump to the answers...

Somewhere along the line - when I upgraded to MVC 5 this got added and I never saw it until today.

Is there a way to 'pretty' print MongoDB shell output to a file?

Also there is mongoexport for that, but I'm not sure since which version it is available.

Example:

mongoexport -d dbname -c collection --jsonArray --pretty --quiet --out output.json

PHP - concatenate or directly insert variables in string

I know this question already has a chosen answer, but I found this article that evidently shows that string interpolation works faster than concatenation. It might be helpful for those who are still in doubt.

Styling HTML5 input type number

There is a way:

<input type="number" min="0" max="100" step="5"/>  

Fit website background image to screen size

You can do it like what I did with my website:

background-repeat: no-repeat;

background-size: cover;

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

As it turns out, one should not forget to include jacson dependency into the pom file. This solved the issue for me:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

GROUP BY having MAX date

Putting the subquery in the WHERE clause and restricting it to n.control_number means it runs the subquery many times. This is called a correlated subquery, and it's often a performance killer.

It's better to run the subquery once, in the FROM clause, to get the max date per control number.

SELECT n.* 
FROM tblpm n 
INNER JOIN (
  SELECT control_number, MAX(date_updated) AS date_updated
  FROM tblpm GROUP BY control_number
) AS max USING (control_number, date_updated);

adding onclick event to dynamically added button?

I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:

//Bad code.
var btn = document.createElement('button');
btn.onClick = function() {  console.log("hey");  }

to this:

//Working Code.  I don't like it, but it works. 
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);

document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){  console.log("hey");  }

I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.

How to move Docker containers between different hosts?

What eventually worked for me, after lot's of confusing manuals and confusing tutorials, since Docker is obviously at time of my writing at peek of inflated expectations, is:

  1. Save the docker image into archive:
    docker save image_name > image_name.tar
  2. copy on another machine
  3. on that other docker machine, run docker load in a following way:
    cat image_name.tar | docker load

Export and import, as proposed in another answers does not export ports and variables, which might be required for your container to run. And you might end up with stuff like "No command specified" etc... When you try to load it on another machine.

So, difference between save and export is that save command saves whole image with history and metadata, while export command exports only files structure (without history or metadata).

Needless to say is that, if you already have those ports taken on the docker hyper-visor you are doing import, by some other docker container, you will end-up in conflict, and you will have to reconfigure exposed ports.

Note: In order to move data with docker, you might be having persistent storage somewhere, which should also be moved alongside with containers.

How to read barcodes with the camera on Android?

There are two parts in building barcode scanning feature, one capturing barcode image using camera and second extracting barcode value from the image.

Barcode image can be captured from your app using camera app and barcode value can be extracted using Firebase Machine Learning Kit barcode scanning API.

Here is an example app https://www.zoftino.com/android-barcode-scanning-example

How to create a QR code reader in a HTML5 website?

The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

JavaScript by reference vs. by value

My understanding is that this is actually very simple:

  • Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.
  • Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
  • However, changing a property of an object referenced by a variable does change the underlying object.

So, to work through some of your examples:

function f(a,b,c) {
    // Argument a is re-assigned to a new value.
    // The object or primitive referenced by the original a is unchanged.
    a = 3;
    // Calling b.push changes its properties - it adds
    // a new property b[b.length] with the value "foo".
    // So the object referenced by b has been changed.
    b.push("foo");
    // The "first" property of argument c has been changed.
    // So the object referenced by c has been changed (unless c is a primitive)
    c.first = false;
}

var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false

Example 2:

var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4";   // a is now ["1", "4", {foo:"bar"}]; b still has the value
              // it had at the time of assignment
a[2] = "5";   // a is now ["1", "4", "5"]; c still has the value
              // it had at the time of assignment, i.e. a reference to
              // the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"

What is the difference between user variables and system variables?

Just recreate the Path variable in users. Go to user variables, highlight path, then new, the type in value. Look on another computer with same version windows. Usually it is in windows 10: Path %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;

How organize uploaded media in WP?

As of October 2015, WP 4.3.1 I have found only two plugins actually affecting image locations as in “folders & subfolders”:

  • Custom Upload Dir, but as the name says, just on upload. You can work from your %post_slug% or %categories%, upload your images in the context of these post/pages, and this tool will form subfolders from it. Which is great, SEO-wise.

    Or you just even ignore all that and mandate under “Build a path template” i.e. travels/france/paris-at-night to upload to that subdir of your WP-Uploads folder. (Of course you'd have to keep changing for the uploads to follow. Limiting my overall faith, that this is a stable long-term tool, despite 10.000+ active installs).

  • Media File Manager allows to move already uploaded images and changes the paths in posts and pages using them accordingly. Its interface reminds of “Norton Commander 1.0” but it does the job. (Except for folder renames and deletes. So if you want to rename, better move images to a newly namend folder, then manually deleting the old.)

All of the following do NOT do the job:

  • WP Media Folder is NOT changing actual direcory location, thus not actually changing paths to your images thus also not affecting image URLs. Despite its name, Folder is just their visualisation of yet-another-taxonomy. I invested $19 to learn that.

  • Enhance Media Library is big, free and very popular (wordpress counts 40.000 installs) but is also not changing physical location and (thus) URLs. ? Thus the accepted answer is in my opinion wrong.

  • Media File Manager advanced appears gone and is deemed dangerous!

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

that is the right behavior.

if you set @item1 to a value the below expression will be true

IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)

Anyway in SQL Server there is not a such function but you can create your own:

CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
    RETURN 0
ELSE
    RETURN 1
END

Entry point for Java applications: main(), init(), or run()?

The main method is the entry point of a Java application.

Specifically?when the Java Virtual Machine is told to run an application by specifying its class (by using the java application launcher), it will look for the main method with the signature of public static void main(String[]).

From Sun's java command page:

The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.

The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration must look like the following:

public static void main(String args[])

For additional resources on how an Java application is executed, please refer to the following sources:

  1. Chapter 12: Execution from the Java Language Specification, Third Edition.
  2. Chapter 5: Linking, Loading, Initializing from the Java Virtual Machine Specifications, Second Edition.
  3. A Closer Look at the "Hello World" Application from the Java Tutorials.

The run method is the entry point for a new Thread or an class implementing the Runnable interface. It is not called by the Java Virutal Machine when it is started up by the java command.

As a Thread or Runnable itself cannot be run directly by the Java Virtual Machine, so it must be invoked by the Thread.start() method. This can be accomplished by instantiating a Thread and calling its start method in the main method of the application:

public class MyRunnable implements Runnable
{
    public void run()
    {
        System.out.println("Hello World!");
    }

    public static void main(String[] args)
    {
        new Thread(new MyRunnable()).start();
    }
}

For more information and an example of how to start a subclass of Thread or a class implementing Runnable, see Defining and Starting a Thread from the Java Tutorials.


The init method is the first method called in an Applet or JApplet.

When an applet is loaded by the Java plugin of a browser or by an applet viewer, it will first call the Applet.init method. Any initializations that are required to use the applet should be executed here. After the init method is complete, the start method is called.

For more information about when the init method of an applet is called, please read about the lifecycle of an applet at The Life Cycle of an Applet from the Java Tutorials.

See also: How to Make Applets from the Java Tutorial.

Rounding to 2 decimal places in SQL

This works too. The below statement rounds to two decimal places.

SELECT ROUND(92.258,2) from dual;

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

Replace all double quotes within String

This is to remove double quotes in a string.

str1 = str.replace(/"/g, "");
alert(str1);

error: member access into incomplete type : forward declaration of

Move doSomething definition outside of its class declaration and after B and also make add accessible to A by public-ing it or friend-ing it.

class B;

class A
{
    void doSomething(B * b);
};

class B
{
public:
    void add() {}
};

void A::doSomething(B * b)
{
    b->add();
}

Check if SQL Connection is Open or Closed

Here is what I'm using:

if (mySQLConnection.State != ConnectionState.Open)
{
    mySQLConnection.Close();
    mySQLConnection.Open();
}

The reason I'm not simply using:

if (mySQLConnection.State == ConnectionState.Closed)
{
    mySQLConnection.Open();
}

Is because the ConnectionState can also be:

Broken, Connnecting, Executing, Fetching

In addition to

Open, Closed

Additionally Microsoft states that Closing, and then Re-opening the connection "will refresh the value of State." See here http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.state(v=vs.110).aspx

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

It may be because you are not stopping your tomcat service properly. To do that, Open your task manager there you can see a javaw.exe service. First stop that service. Now restart your tomcat it works fine.

Send XML data to webservice using php curl

Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml to read your $_POST. You can use file_get_contents('php://input') to get the raw post data as plain XML.

Sql query to insert datetime in SQL Server

I encounter into a more generic problem: getting different (and not necessarily known) datetime formats and insert them into datetime column. I've solved it using this statement, which was finally became a scalar function (relevant for ODBC canonical, american, ANSI and british\franch date style - can be expanded):

insert into <tableName>(<dateTime column>) values(coalesce 
(TRY_CONVERT(datetime, <DateString, 121), TRY_CONVERT(datetime, <DateString>, 
101), TRY_CONVERT(datetime, <DateString>, 102), TRY_CONVERT(datetime, 
<DateString>, 103))) 

Reading inputStream using BufferedReader.readLine() is too slow

I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader's fault. Try measuring this:

InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing

I think you'll find it's almost exactly the same time as when you're parsing the text.

Note that you should also give InputStreamReader an appropriate encoding - the platform default encoding is almost certainly not what you should be using.

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

You're looking for

foreach (Control x in this.Controls)
{
  if (x is TextBox)
  {
    ((TextBox)x).Text = String.Empty;
  }
}

How do I use popover from Twitter Bootstrap to display an image?

Very simple :)

<a href="#" id="blob" class="btn large primary" rel="popover">hover for popover</a>

var img = '<img src="https://si0.twimg.com/a/1339639284/images/three_circles/twitter-bird-white-on-blue.png" />';

$("#blob").popover({ title: 'Look! A bird!', content: img, html:true });

http://jsfiddle.net/weuWk/

C error: Expected expression before int

{ } -->

defines scope, so if(a==1) { int b = 10; } says, you are defining int b, for {}- this scope. For

if(a==1)
  int b =10;

there is no scope. And you will not be able to use b anywhere.

How do I extract part of a string in t-sql

declare @data as varchar(50)
set @data='ciao335'


--get text
Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1)    ---->>ciao

--get numeric
Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) )   ---->>335

How to get indices of a sorted array in Python

Import numpy as np

FOR INDEX

S=[11,2,44,55,66,0,10,3,33]

r=np.argsort(S)

[output]=array([5, 1, 7, 6, 0, 8, 2, 3, 4])

argsort Returns the indices of S in sorted order

FOR VALUE

np.sort(S)

[output]=array([ 0,  2,  3, 10, 11, 33, 44, 55, 66])

How to remove all duplicate items from a list

Just make a new list to populate, if the item for your list is not yet in the new list input it, else just move on to the next item in your original list.

for i in mylist:
  if i not in newlist:
    newlist.append(i)

I think this is the correct syntax, but my python is a bit shaky, I hope you at least get the idea.

Factorial using Recursion in Java

public class Factorial2 {
    public static long factorial(long x) {
        if (x < 0) 
            throw new IllegalArgumentException("x must be >= 0");
        if (x <= 1) 
            return 1;  // Stop recursing here
        else 
           return x * factorial(x-1);  // Recurse by calling ourselves
    }
}

How to create a session using JavaScript?

Here is what I did and it worked, created a session in PHP and used xmlhhtprequest to check if session is set whenever an HTML page loads and it worked for Cordova.

Making a triangle shape using xml definitions?

 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <rotate
                android:fromDegrees="45"
                android:pivotX="135%"
                android:pivotY="1%"
                android:toDegrees="45">
                <shape android:shape="rectangle">
                    <stroke
                        android:width="-60dp"
                        android:color="@android:color/transparent" />
                    <solid android:color="@color/orange" />
                </shape>
            </rotate>
        </item>
    </layer-list>

How to check if a file exists in Documents folder?

Swift 2.0

This is how to check if the file exists using Swift

func isFileExistsInDirectory() -> Bool {
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDirectory: AnyObject = paths[0]
    let dataPath = documentsDirectory.stringByAppendingPathComponent("/YourFileName")

    return NSFileManager.defaultManager().fileExistsAtPath(dataPath)
}

What does character set and collation mean exactly?

I suggest to use utf8mb4_unicode_ci, which is based on the Unicode standard for sorting and comparison, which sorts accurately in a very wide range of languages.