Programs & Examples On #Appendto

Delete dynamically-generated table row using jQuery

You should use Event Delegation, because of the fact that you are creating dynamic rows.

$(document).on('click','button.removebutton', function() {
    alert("aa");
  $(this).closest('tr').remove();
  return false;
});

Live Demo

Adding click event for a button created dynamically using jQuery

Use

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

to add the listener for the dynamically created button.

alert($("#btn_a").val());

will give you the value of the button

How to get jQuery dropdown value onchange event

Add try this code .. Its working grt.......

_x000D_
_x000D_
<body>_x000D_
<?php_x000D_
 if (isset($_POST['nav'])) {_x000D_
   header("Location: $_POST[nav]");_x000D_
 }_x000D_
?>_x000D_
<form id="page-changer" action="" method="post">_x000D_
    <select name="nav">_x000D_
        <option value="">Go to page...</option>_x000D_
        <option value="http://css-tricks.com/">CSS-Tricks</option>_x000D_
        <option value="http://digwp.com/">Digging Into WordPress</option>_x000D_
        <option value="http://quotesondesign.com/">Quotes on Design</option>_x000D_
    </select>_x000D_
    <input type="submit" value="Go" id="submit" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<script>_x000D_
$(function() {_x000D_
_x000D_
    $("#submit").hide();_x000D_
_x000D_
    $("#page-changer select").change(function() {_x000D_
        window.location = $("#page-changer select option:selected").val();_x000D_
    })_x000D_
_x000D_
});_x000D_
</script>_x000D_
</head>
_x000D_
_x000D_
_x000D_

Why is the jquery script not working?

This may not be the answer you are looking for, but may help others whose jquery is not working properly, or working sometimes and not at other times.

This could be because your jquery has not yet loaded and you have started to interact with the page. Either put jquery on top in head (probably not a very great idea) or use a loader or spinner to stop the user from interacting with the page until the entire jquery has loaded.

AngularJS - add HTML element to dom in directive without jQuery

If your destination element is empty and will only contain the <svg> tag you could consider using ng-bind-html as follow :

Declare your HTML tag in the directive scope variable

link: function (scope, iElement, iAttrs) {

    scope.svgTag = '<svg width="600" height="100" class="svg"></svg>';

    ...
}

Then, in your directive template, just add the proper attribute at the exact place you want to append the svg tag :

<!-- start of directive template code -->
...
<!-- end of directive template code -->
<div ng-bind-html="svgTag"></div>

Don't forget to include ngSanitize to allow ng-bind-html to automatically parse the HTML string to trusted HTML and avoid insecure code injection warnings.

See official documentation for more details.

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Your last example is invalid JSON. Single quotes are not allowed in JSON except inside strings. In the second example, the single quotes are not in the string, but serve to show the start and end.

See http://www.json.org/ for the specifications.

Should add: Why do you think this: "like I seem to need to in my real code"? Then maybe we can help you come up with the solution.

Can someone explain how to implement the jQuery File Upload plugin?

Droply.js is perfect for this. It's simple and comes pre-packaged with a demo site that works out of the box.

Using jQuery to build table rows from AJAX response(json)

You could do it something like this:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


    <script>
    $(function(){

    $.ajax({
    url: '<Insert your REST API which you want GET/POST/PUT/DELETE>',
    data: '<any parameters you want to send as the Request body or query string>',
    dataType: json,
    async: true,
    method: "GET"
    success: function(data){

    //If the REST API returned a successful response it'll be stored in data, 
    //just parse that field using jQuery and you're all set

    var tblSomething = '<thead> <tr> <td> Heading Col 1 </td> <td> Heading Col 2 </td> <td> Col 3 </td> </tr> </thead> <tbody>';

    $.each(data, function(idx, obj){

    //Outer .each loop is for traversing the JSON rows
    tblSomething += '<tr>';

    //Inner .each loop is for traversing JSON columns
    $.each(obj, function(key, value){
    tblSomething += '<td>' + value + '</td>';
    });
    tblSomething += '</tr>';
    });

    tblSomething += '</tbody>';

    $('#tblSomething').html(tblSomething);
    },
    error: function(jqXHR, textStatus, errorThrown){
    alert('Hey, something went wrong because: ' + errorThrown);
    }
    });


    });
    </script>


    <table id = "tblSomething" class = "table table-hover"></table>

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

The same issue came up for me inside of $elms.each().

Because:

  1. the function you pass to .each(Function) exposes (at least) two arguments; the first being the index and the second being the element in the current element in the list, and
  2. because other similar looping methods give current the element in the array before the index

you may be tempted to do this:

$elms.each((item) => $(item).addClass('wrong'));

When this is what you need:

$elms.each((index, item) => $(item).addClass('wrong'));

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

Checked/Valid example for:

  • multiple file inputs
  • for one or MULTIPLE FILES upload - $.grep() to remove files from array with errors
  • image and audio format
  • dynamic file types from string by new RegExp()

Notice: acceptFileTypes.test() - check mime types, for adio file like .mp3 it will be audio/mpeg - not only extenstion. For all blueimp options: https://github.com/blueimp/jQuery-File-Upload/wiki/Options

$('input[type="file"]').each(function(i){

    // .form_files is my div/section of form for input file and progressbar
    var $progressbar = $(this).parents('.form_files:first').find('.progress-bar:first');

    var $image_format = 'jpg|jpeg|jpe|png|gif';
    var $audio_format = 'mp3|mpeg';
    var $all_formats = $image_format + '|' + $audio_format;

    var $image_size = 2;
    var $audio_size = 10;
    var mb = 1048576;

    $(this).fileupload({
        // ...
        singleFileUploads: false,   // << send all together, not single
        // ...
        add: function (e, data) {

            // array with all indexes of files with errors
            var error_uploads_indexes = [];

            // when add file - each file
            $.each(data.files, function(index, file) {

                // array for all errors
                var uploadErrors = [];


                // validate all formats first
                if($all_formats){

                    // check all formats first - before size
                    var acceptFileTypes = "(\.|\/)(" + $all_formats + ")$";
                    acceptFileTypes = new RegExp(acceptFileTypes, "i");

                    // when wrong format
                    if(data.files[index]['type'].length && !acceptFileTypes.test(data.files[index]['type'])) {
                        uploadErrors.push('Not an accepted file type');

                    }else{

                        // default size is image_size
                        var $my_size = $image_size;

                            // check audio format
                            var acceptFileTypes = "(\.|\/)(" + $audio_format + ")$";
                            acceptFileTypes = new RegExp(acceptFileTypes, "i");

                            // alert(data.files[index]['type']);
                            // alert(acceptFileTypes.test('audio/mpeg'));

                            // if is audio then size is audio_size
                            if(data.files[index]['type'].length && acceptFileTypes.test(data.files[index]['type'])) {
                                $my_size = $audio_size;
                            }

                        // check size
                        if(data.files[index]['size'] > $my_size * mb) {
                            uploadErrors.push('Filesize is too big');
                        };
                    };

                }; // << all_formats

                // when errors
                if(uploadErrors.length > 0) {
                    //  alert(uploadErrors.join("\n"));

                    // mark index of error file
                    error_uploads_indexes.push(index);
                    // alert error
                    alert(uploadErrors.join("\n"));

                };

            }); // << each


            // remove indexes (files) with error
            data.files = $.grep( data.files, function( n, i ) {
                return $.inArray(i, error_uploads_indexes) ==-1;
            });


            // if are files to upload
            if(data.files.length){
                // upload by ajax
                var jqXHR = data.submit().done(function (result, textStatus, jqXHR) {
                        //...
                     alert('done!') ;
                        // ...
                });
            } // 

        }, // << add
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $progressbar.css(
                'width',
                progress + '%'
                );
        }
    }); // << file_upload

    //          
}); // << each input file

jQuery UI Dialog - missing close icon

I am late to this one by a while, but I'm going to blow your mind, ready?

The reason this is happening, is because you are calling bootstrap in, after you are calling jquery-ui in.

Literally, swap the two so that instead of:

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="js/bootstrap.min.js"></script>

it becomes

<script src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

:)

Edit - 26/06/2015 - this keeps attracting interest months later so I thought it was worth an edit. I actually really like the noConflict solution offered in the comment underneath this answer and clarified by user Pretty Cool as a separate answer. As some have reported issues with the bootstrap tooltip when the scripts are swapped. I didn't experience that issue however because I downloaded jquery UI without the tooltip as I didn't need it because bootstrap. So this issue never came up for me.

Edit - 22/07/2015 - Don't confuse jquery-ui with jquery! While Bootstrap's JavaScript requires jQuery to be loaded before, it doesn't rely on jQuery-UI. So jquery-ui.js can be loaded after bootstrap.min.js, while jquery.js always needs to be loaded before Bootstrap.

Download image with JavaScript

The problem is that jQuery doesn't trigger the native click event for <a> elements so that navigation doesn't happen (the normal behavior of an <a>), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).

To trigger it manually, try:

var a = $("<a>")
    .attr("href", "http://i.stack.imgur.com/L8rHf.png")
    .attr("download", "img.png")
    .appendTo("body");

a[0].click();

a.remove();

DEMO: http://jsfiddle.net/HTggQ/

Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332

if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
        jQuery.acceptData( elem ) ) {

Very Simple Image Slider/Slideshow with left and right button. No autoplay

After reading your comment on my previous answer I thought I might put this as a separate answer.

Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.

That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with

WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/

This is the jQuery

$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();    
$('.active').show();

    $('#button-next').click(function(){

    $('.active').removeClass('active').addClass('oldActive');    
                   if ( $('.oldActive').is(':last-child')) {
        $('.sp').first().addClass('active');
        }
        else{
        $('.oldActive').next().addClass('active');
        }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();


    });

       $('#button-previous').click(function(){
    $('.active').removeClass('active').addClass('oldActive');    
           if ( $('.oldActive').is(':first-child')) {
        $('.sp').last().addClass('active');
        }
           else{
    $('.oldActive').prev().addClass('active');
           }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();
    });




});

So now the explanation.
Stage 1
1) Load the script on document ready.

2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.

3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;

Stage 2 Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.

2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.

3) We remove the class oldActive because it's no longer needed.

4) fadeOut all of the slides

5) fade In the active slides

Step 3

Same as in step two but using some reverse logic for traversing through the elements backwards.

It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.

jQuery-- Populate select from json

$(JSON.parse(response)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#selectorId');

How to add text to an existing div with jquery

You need to define the button text and have valid HTML for the button. I would also suggest using .on for the click handler of the button

_x000D_
_x000D_
$(function () {_x000D_
  $('#Add').on('click', function () {_x000D_
    $('<p>Text</p>').appendTo('#Content');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
    <button id="Add">Add Text</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Also I would make sure the jquery is at the bottom of the page just before the closing </body> tag. Doing so will make it so you do not have to have the whole thing wrapped in $(function but I would still do that. Having your javascript load at the end of the page makes it so the rest of the page loads incase there is a slow down in your javascript somewhere.

Adding rows to tbody of a table using jQuery

As @wirey said appendTo should work, if not then you can try this:

$("#tblEntAttributes tbody").append(newRowContent);

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

I fixed it by added the jquery.slim.min.js after the jquery.min.js, as the Solution Sequence.

Problem Sequence

<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

Solution Sequence

<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/jquery/jquery.slim.min.js"></script>
<script src="./vendor/jquery-easing/jquery.easing.min.js"></script>

Configure Log4Net in web application

1: Add the following line into the AssemblyInfo class

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

2: Make sure you don't use .Net Framework 4 Client Profile as Target Framework (I think this is OK on your side because otherwise it even wouldn't compile)

3: Make sure you log very early in your program. Otherwise, in some scenarios, it will not be initialized properly (read more on log4net FAQ).

So log something during application startup in the Global.asax

public class Global : System.Web.HttpApplication
{
    private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(Global));
    protected void Application_Start(object sender, EventArgs e)
    {
        Log.Info("Startup application.");
    }
}

4: Make sure you have permission to create files and folders on the given path (if the folder itself also doesn't exist)

5: The rest of your given information looks ok

Add / remove input field dynamically with jQuery

You can also use something like this

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add / Remove Table Rows Dynamically</title>
<style type="text/css">
    form{
        margin: 20px 0;
    }
    form input, button{
        padding: 5px;
    }
    table{
        width: 100%;
        margin-bottom: 20px;
        border-collapse: collapse;
    }
    table, th, td{
        border: 1px solid #cdcdcd;
    }
    table th, table td{
        padding: 10px;
        text-align: left;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $(".add-row").click(function(){
            var name = $("#name").val();
            var email = $("#email").val();
            var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
            $("table tbody").append(markup);
        });

        // Find and remove selected table rows
        $(".delete-row").click(function(){
            $("table tbody").find('input[name="record"]').each(function(){
                if($(this).is(":checked")){
                    $(this).parents("tr").remove();
                }
            });
        });
    });    
</script>
</head>
<body>
    <form>
        <input type="text" id="name" placeholder="Name">
        <input type="text" id="email" placeholder="Email Address">
        <input type="button" class="add-row" value="Add Row">
    </form>
    <table>
        <thead>
            <tr>
                <th>Select</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="checkbox" name="record"></td>
                <td>Peter Parker</td>
                <td>[email protected]</td>
            </tr>
        </tbody>
    </table>
    <button type="button" class="delete-row">Delete Row</button>
</body> 
</html>

log4net hierarchy and logging levels

DEBUG will show all messages, INFO all besides DEBUG messages, and so on.
Usually one uses either INFO or WARN. This dependens on the company policy.

document.getElementByID is not a function

It worked like this for me:

document.getElementById("theElementID").setAttribute("src", source);
document.getElementById("task-text").innerHTML = "";

Change the

getElementById("theElementID")

for your element locator (name, css, xpath...)

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

Parse JSON from JQuery.ajax success data

I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this

$.ajax({
    url : url,
    dataType : 'json'
})
.done(function(data, statusText, resObject) {
   var jsonData = resObject.responseJSON
})

how to change onclick event with jquery?

Remove the old event handler

$('#id').unbind('click');

And attach the new one

$('#id').click(function(){
    // your code here
});

How to make a Java Generic method static?

I'll explain it in a simple way.

Generics defined at Class level are completely separate from the generics defined at the (static) method level.

class Greet<T> {

    public static <T> void sayHello(T obj) {
        System.out.println("Hello " + obj);
    }
}

When you see the above code anywhere, please note that the T defined at the class level has nothing to do with the T defined in the static method. The following code is also completely valid and equivalent to the above code.

class Greet<T> {

    public static <E> void sayHello(E obj) {
        System.out.println("Hello " + obj);
    }
}

Why the static method needs to have its own generics separate from those of the Class?

This is because, the static method can be called without even instantiating the Class. So if the Class is not yet instantiated, we do not yet know what is T. This is the reason why the static methods needs to have its own generics.

So, whenever you are calling the static method,

Greet.sayHello("Bob");
Greet.sayHello(123);

JVM interprets it as the following.

Greet.<String>sayHello("Bob");
Greet.<Integer>sayHello(123);

Both giving the same outputs.

Hello Bob
Hello 123

Unexpected token ILLEGAL in webkit

You can use online Minify, it removes these invisible characters efficiently but also changes your code. So be careful.

http://jscompress.com/

jQuery plugin returning "Cannot read property of undefined"

The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:

var len = menuitems.length;
for (var i = 0; i < len; i++){
    (function(i) {
      $('<li/>',{
          'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
          'click':function(){
              menuitems[i].action();
          },
          'class':o.itemClass
      }).appendTo('.'+o.listClass);
    })(i);
}

In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.

jQuery .get error response function?

$.get does not give you the opportunity to set an error handler. You will need to use the low-level $.ajax function instead:

$.ajax({
    url: 'http://example.com/page/2/',
    type: 'GET',
    success: function(data){ 
        $(data).find('#reviews .card').appendTo('#reviews');
    },
    error: function(data) {
        alert('woops!'); //or whatever
    }
});

Edit March '10

Note that with the new jqXHR object in jQuery 1.5, you can set an error handler after calling $.get:

$.get('http://example.com/page/2/', function(data){ 
    $(data).find('#reviews .card').appendTo('#reviews');
}).fail(function() {
    alert('woops'); // or whatever
});

Log4net does not write the log in the log file

In my case, log4net wasn't logging properly due to having a space in my project name. Drove me nuts why the same code worked just fine in a different project, but didn't in the new one. Spaces. A simple space.

So, beware spaces in project names. I've learned my lesson.

Razor view engine - How can I add Partial Views

If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:

public class GameViewModel
{
    public virtual Ship Ship { get; set; }
    public virtual GamePlayer GamePlayer { get; set; }     
}

Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[code to check if results]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.

Where will log4net create this log file?

The file value can either be an absolute path like "c:\logs\log.txt" or a relative path which I believe is relative to the bin directory.

As far as implementing it, I usually place the following at the top of any class I plan to log in:

private static readonly ILog Log = LogManager.GetLogger( 
MethodBase.GetCurrentMethod().DeclaringType);

Finally, you can use it like so:

Log.Debug("This is a DEBUG level message.");

How to move child element from one parent to another using jQuery

As Jage's answer removes the element completely, including event handlers and data, I'm adding a simple solution that doesn't do that, thanks to the detach function.

var element = $('#childNode').detach();
$('#parentNode').append(element);

Edit:

Igor Mukhin suggested an even shorter version in the comments below:

$("#childNode").detach().appendTo("#parentNode");

Prevent jQuery UI dialog from setting focus to first textbox

as first input : <input type="text" style="position:absolute;top:-200px" />

How to prevent buttons from submitting forms

The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.

Check out the function removeItem in the javascript part:

The line:

rows[rows.length-1].html('');

doesn't work. Try this instead:

rows.eq(rows.length-1).html('');

jQuery UI Dialog with ASP.NET button postback

You are close to the solution, just getting the wrong object. It should be like this:

jQuery(function() {
    var dlg = jQuery("#dialog").dialog({
                         draggable: true,
                         resizable: true,
                         show: 'Transfer',
                         hide: 'Transfer',
                         width: 320,
                         autoOpen: false,
                         minHeight: 10,
                         minwidth: 10
                     });
    dlg.parent().appendTo(jQuery("form:first"));
});

Preloading images with jQuery

I usually use this snippet of code on my projects for the loading of the images in a page. You can see the result here https://jsfiddle.net/ftor34ey/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<img src="https://live.staticflickr.com/65535/50020763321_d61d49e505_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50021019427_692a8167e9_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020228418_d730efe386_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020230828_7ef175d07c_k_d.jpg" width="100" />

<div style="background-image: url(https://live.staticflickr.com/65535/50020765826_e8da0aacca_k_d.jpg);"></div>
<style>
    .bg {
        background-image: url("https://live.staticflickr.com/65535/50020765651_af0962c22e_k_d.jpg");
    }
</style>
<div class="bg"></div>

<div id="loadingProgress"></div>

The script save in an array all the src and background-image of the page and load all of them.

You can see/read/show the progress of the loading by the var loadCount.

let backgroundImageArray = [];

function backgroundLoading(i) {

    let loadCount = 0;

    let img = new Image();
    $(img).on('load', function () {

        if (i < backgroundImageArray.length) {

            loadCount = parseInt(((100 / backgroundImageArray.length) * i));
            backgroundLoading(i + 1);

        } else {

            loadCount = 100;
            // do something when the page finished to load all the images
            console.log('loading completed!!!');
            $('#loadingProgress').append('<div>loading completed!!!</div>');

        }

        console.log(loadCount + '%');
        $('#loadingProgress').append('<div>' + loadCount + '%</div>');

    }).attr('src', backgroundImageArray[i - 1]);

}

$(document).ready(function () {

    $('*').each(function () {

        var backgroundImage = $(this).css('background-image');
        var putInArray = false;

        var check = backgroundImage.substr(0, 3);

        if (check == 'url') {

            backgroundImage = backgroundImage.split('url(').join('').split(')').join('');
            backgroundImage = backgroundImage.replace('"', '');
            backgroundImage = backgroundImage.replace('"', '');

            if (backgroundImage.substr(0, 4) == 'http') {
                backgroundImage = backgroundImage;
            }
            putInArray = true;

        } else if ($(this).get(0).tagName == 'IMG') {

            backgroundImage = $(this).attr('src');
            putInArray = true;

        }

        if (putInArray) {
            backgroundImageArray[backgroundImageArray.length] = backgroundImage;
        }

    });

    backgroundLoading(1);

});

Jackson serialization: ignore empty values (or null)

You need to add import com.fasterxml.jackson.annotation.JsonInclude;

Add

@JsonInclude(JsonInclude.Include.NON_NULL)

on top of POJO

If you have nested POJO then

@JsonInclude(JsonInclude.Include.NON_NULL)

need to add on every values.

NOTE: JAXRS (Jersey) automatically handle this scenario 2.6 and above.

How to invoke a Linux shell command from Java

Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(final String[] args) throws IOException, InterruptedException {
        //Build command 
        List<String> commands = new ArrayList<String>();
        commands.add("/bin/cat");
        //Add arguments
        commands.add("/home/narek/pk.txt");
        System.out.println(commands);

        //Run macro on target
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.directory(new File("/home/narek"));
        pb.redirectErrorStream(true);
        Process process = pb.start();

        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                System.out.println(line);
            }

        //Check result
        if (process.waitFor() == 0) {
            System.out.println("Success!");
            System.exit(0);
        }

        //Abnormal termination: Log command parameters and output and throw ExecutionException
        System.err.println(commands);
        System.err.println(out.toString());
        System.exit(1);
    }
}

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Seeing how you draw your canvas with

$("canvas").drawImage();

it seems that you use jQuery Canvas (jCanvas) by Caleb Evans. I actually use that plugin and it has a simple way to retrieve canvas base64 image string with $('canvas').getCanvasImage();

Here's a working Fiddle for you: http://jsfiddle.net/e6nqzxpn/

(HTML) Download a PDF file instead of opening them in browser when clicked

you can add the following code

_x000D_
_x000D_
<a href='http://v2.immo-facile.com/catalog/admin-v2/product_info.pdf' class='btnPdf' title='pdf'  target='_blank' type='application/pdf' >Télécharger la fiche du bien</a>
_x000D_
_x000D_
_x000D_

Specify path to node_modules in package.json

yes you can, just set the NODE_PATH env variable :

export NODE_PATH='yourdir'/node_modules

According to the doc :

If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then node will search those paths for modules if they are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by semicolons instead of colons.)

Additionally, node will search in the following locations:

1: $HOME/.node_modules

2: $HOME/.node_libraries

3: $PREFIX/lib/node

Where $HOME is the user's home directory, and $PREFIX is node's configured node_prefix.

These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in node_modules folders. They will be loaded faster, and more reliably.

Source

How do I remove time part from JavaScript date?

Split it by space and take first part like below. Hope this will help you.

var d = '12/12/1955 12:00:00 AM';
d = d.split(' ')[0];
console.log(d);

How to create a directory in Java?

After ~7 year, I will update it to better approach which is suggested by Bozho.

File theDir = new File("/path/directory");
if (!theDir.exists()){
    theDir.mkdirs();
}

After MySQL install via Brew, I get the error - The server quit without updating PID file

I found that it was a permissions issue with the mysql folder.

chmod -R 777 /usr/local/var/mysql/ 

solved it for me.

LEFT OUTER JOIN in LINQ

Here is a fairly easy to understand version using method syntax:

IEnumerable<JoinPair> outerLeft =
    lefts.SelectMany(l => 
        rights.Where(r => l.Key == r.Key)
              .DefaultIfEmpty(new Item())
              .Select(r => new JoinPair { LeftId = l.Id, RightId = r.Id }));

Using RegEx in SQL Server

SELECT * from SOME_TABLE where NAME like '%[^A-Z]%'

Or some other expression instead of A-Z

Javascript how to parse JSON array

You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.

There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.

By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.

Restore a postgres backup file using the command line?

try this:

psql -U <username> -d <dbname> -f <filename>.sql

Restore DB psql from .sql file

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

"Faceted Project Problem (Java Version Mismatch)" error message

I encountered this issue while running an app on Java 1.6 while I have all three versions of Java 6,7,8 for different apps.I accessed the Navigator View and manually removed the unwanted facet from the facet.core.xml .Clean build and wallah!

<?xml version="1.0" encoding="UTF-8"?>

<fixed facet="jst.java"/>

<fixed facet="jst.web"/>

<installed facet="jst.web" version="2.4"/>

<installed facet="jst.java" version="6.0"/>

<installed facet="jst.utility" version="1.0"/>

login to remote using "mstsc /admin" with password

the command posted by Milad and Sandy did not work for me with mstsc. i had to add TERMSRV to the /generic switch. i found this information here: https://gist.github.com/jdforsythe/48a022ee22c8ec912b7e

cmdkey /generic:TERMSRV/<server> /user:<username> /pass:<password>

i could then use mstsc /v:<server> without getting prompted for the login.

jquery stop child triggering parent event

I stumbled upon this question, looking for another answer.

I wanted to prevent all children from triggering the parent.

JavaScript:

document.getElementById("parent").addEventListener("click",  function (e) {
    if (this !== event.target) return;
    // Do something
});

jQuery:

$("#parent").click(function () {
    // Do something
}).children().on("click", function (e) {
    e.stopPropagation();
});

Display PDF within web browser

The browser's plugin controls those settings, so you can't force it. However, you can do a simple <a href="whatver.pdf"> instead of <a href="whatever.pdf" target="_blank">.

Simulate Keypress With jQuery

The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.

http://docs.jquery.com/Events/trigger#eventdata

Read the above documentation for more details.

convert string array to string

Aggregate can also be used for same.

string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string joinedString = test.Aggregate((prev, current) => prev + " " + current);

Yes/No message box using QMessageBox

QMessageBox includes static methods to quickly ask such questions:

#include <QApplication>
#include <QMessageBox>

int main(int argc, char **argv)
{
    QApplication app{argc, argv};
    while (QMessageBox::question(nullptr,
                                 qApp->translate("my_app", "Test"),
                                 qApp->translate("my_app", "Are you sure you want to quit?"),
                                 QMessageBox::Yes|QMessageBox::No)
           != QMessageBox::Yes)
        // ask again
        ;
}

If your needs are more complex than provided for by the static methods, you should construct a new QMessageBox object, and call its exec() method to show it in its own event loop and obtain the pressed button identifier. For example, we might want to make "No" be the default answer:

#include <QApplication>
#include <QMessageBox>

int main(int argc, char **argv)
{
    QApplication app{argc, argv};
    auto question = new QMessageBox(QMessageBox::Question,
                                    qApp->translate("my_app", "Test"),
                                    qApp->translate("my_app", "Are you sure you want to quit?"),
                                    QMessageBox::Yes|QMessageBox::No,
                                    nullptr);
    question->setDefaultButton(QMessageBox::No);

    while (question->exec() != QMessageBox::Yes)
        // ask again
        ;
}

How can I include null values in a MIN or MAX?

Assuming you have only one record with null in EndDate column for a given RecordID, something like this should give you desired output :

WITH cte1 AS
(
SELECT recordid, MIN(startdate) as min_start , MAX(enddate) as max_end
FROM tmp 
GROUP BY recordid
)

SELECT a.recordid, a.min_start , 
CASE 
   WHEN b.recordid IS  NULL THEN a.max_end
END as max_end
FROM cte1 a
LEFT JOIN tmp b ON (b.recordid = a.recordid AND b.enddate IS NULL)

Create new XML file and write data to it?

With FluidXML you can generate and store an XML document very easily.

$doc = fluidxml();

$doc->add('Album', true)
        ->add('Track', 'Track Title');

$doc->save('album.xml');

Loading a document from a file is equally simple.

$doc = fluidify('album.xml');

$doc->query('//Track')
        ->attr('id', 123);

https://github.com/servo-php/fluidxml

How to vertically center a "div" element for all browsers using CSS?

I find this one most useful.. it gives the most accurate 'H' layout and is very simple to understand.

The benefit in this markup is that you define your content size in a single place -> "PageContent".
The Colors of the page background and its horizontal margins are defined in their corresponding divs.

<div id="PageLayoutConfiguration" 
     style="display: table;
     position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;
     width: 100%; height: 100%;">

        <div id="PageBackground" 
             style="display: table-cell; vertical-align: middle;
             background-color: purple;">

            <div id="PageHorizontalMargins"
                 style="width: 100%;
                 background-color: seashell;">

                <div id="PageContent" 
                     style="width: 1200px; height: 620px; margin: 0 auto;
                     background-color: grey;">

                     my content goes here...

                </div>
            </div>
        </div>
    </div>

And here with CSS separated:

<div id="PageLayoutConfiguration">
     <div id="PageBackground">
          <div id="PageHorizontalMargins">
               <div id="PageContent">
                     my content goes here...
               </div>
          </div>
     </div>
</div>

#PageLayoutConfiguration{
   display: table; width: 100%; height: 100%;
   position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;
}

#PageBackground{
   display: table-cell; vertical-align: middle;
   background-color: purple;
}

#PageHorizontalMargins{
   style="width: 100%;
   background-color: seashell;
}
#PageContent{
   width: 1200px; height: 620px; margin: 0 auto;
   background-color: grey;
}

Django: multiple models in one template using forms

According to Django documentation, inline formsets are for this purpose: "Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key".

See https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets

Is it possible to set a number to NaN or infinity?

Yes, you can use numpy for that.

import numpy as np
a = arange(3,dtype=float)

a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf

a # is now [nan,inf,-inf]

np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True

How can I control Chromedriver open window size?

RUBY


Approach #1

options = {
      'chromeOptions' => {
          'args' => ['start-fullscreen']
      }
  }

caps = Selenium::WebDriver::Remote::Capabilities.chrome(options)
@driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps

Approach #2

options = {
      'chromeOptions' => {
          'args' => ['window-size=640,480']
      }
  }

caps = Selenium::WebDriver::Remote::Capabilities.chrome(options)
@driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps

Approach #3

max_width, max_height = @driver.execute_script("return [window.screen.availWidth, window.screen.availHeight];")
@driver.manage.window.resize_to(max_width, max_height)

Approach #4

@driver.manage.window.maximize

Approach #5

target_size = Selenium::WebDriver::Dimension.new(1600, 1268)
@driver.manage.window.size = target_size

Approach #6

@driver.manage.window.resize_to(640, 480)

Approach #7

@driver.execute_script("window.resizeTo(640, 480);")

Environment variable substitution in sed

With your question edit, I see your problem. Let's say the current directory is /home/yourname ... in this case, your command below:

sed 's/xxx/'$PWD'/'

will be expanded to

sed `s/xxx//home/yourname//

which is not valid. You need to put a \ character in front of each / in your $PWD if you want to do this.

Convert UTC/GMT time to local time

@TimeZoneInfo.ConvertTimeFromUtc(timeUtc, TimeZoneInfo.Local)

CSS - Overflow: Scroll; - Always show vertical scroll bar?

This will make the scroll bars always display when there is content within windows that must be scrolled to access, it applies to all windows and all apps on the Mac:

Launch System Preferences from the ? Apple menu Click on the “General” settings panel Look for ‘Show scroll bars’ and select the radiobox next to “Always” Close out of System Preferences when finished

What design patterns are used in Spring framework?

Observer-Observable: it is used in ApplicationContext's event mechanism

Can I set text box to readonly when using Html.TextBoxFor?

An other possibility :

<%= Html.TextBoxFor(model => Model.SomeFieldName, new Dictionary<string, object>(){{"disabled", "true"}}) %>

Div Background Image Z-Index Issue

For z-index to work, you also need to give it a position:

header {
    width: 100%;
    height: 100px;
    background: url(../img/top.png) repeat-x;
    z-index: 110;
    position: relative;
}

javascript scroll event for iPhone/iPad?

The iPhoneOS does capture onscroll events, except not the way you may expect.

One-finger panning doesn’t generate any events until the user stops panning—an onscroll event is generated when the page stops moving and redraws—as shown in Figure 6-1.

Similarly, scroll with 2 fingers fires onscroll only after you've stopped scrolling.

The usual way of installing the handler works e.g.

window.addEventListener('scroll', function() { alert("Scrolled"); });
// or
$(window).scroll(function() { alert("Scrolled"); });
// or
window.onscroll = function() { alert("Scrolled"); };
// etc 

(See also https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html)

SQLite with encryption/password protection

Keep in mind, the following is not intended to be a substitute for a proper security solution.

After playing around with this for four days, I've put together a solution using only the open source System.Data.SQLite package from NuGet. I don't know how much protection this provides. I'm only using it for my own course of study. This will create the DB, encrypt it, create a table, and add data.

using System.Data.SQLite;

namespace EncryptDB
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = @"C:\Programming\sqlite3\db.db";
            string passwordString = "password";
            byte[] passwordBytes = GetBytes(passwordString);
            SQLiteConnection.CreateFile(connectionString);
            SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString + ";Version=3;");
            conn.SetPassword(passwordBytes);
            conn.Open();
            SQLiteCommand sqlCmd = new SQLiteCommand("CREATE TABLE data(filename TEXT, filepath TEXT, filelength INTEGER, directory TEXT)", conn);
            sqlCmd.ExecuteNonQuery();
            sqlCmd = new SQLiteCommand("INSERT INTO data VALUES('name', 'path', 200, 'dir')", conn);
            sqlCmd.ExecuteNonQuery();
            conn.Close();
        }
        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            bytes = System.Text.Encoding.Default.GetBytes(str);
            return bytes;
        }
    }
}

Optionally, you can remove conn.SetPassword(passwordBytes);, and replace it with conn.ChangePassword("password"); which needs to be placed after conn.Open(); instead of before. Then you won't need the GetBytes method.

To decrypt, it's just a matter of putting the password in your connection string before the call to open.

        string filename = @"C:\Programming\sqlite3\db.db";
        string passwordString = "password";
        SQLiteConnection conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;Password=" + passwordString + ";");
        conn.Open();

How can I maintain fragment state when added to the back stack?

Here, since onSaveInstanceState in fragment does not call when you add fragment into backstack. The fragment lifecycle in backstack when restored start onCreateView and end onDestroyView while onSaveInstanceState is called between onDestroyView and onDestroy. My solution is create instance variable and init in onCreate. Sample code:

private boolean isDataLoading = true;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     isDataLoading = false;
     // init list at once when create fragment
     listData = new ArrayList();
}

And check it in onActivityCreated:

public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if(isDataLoading){
         fetchData();
    }else{
         //get saved instance variable listData()
    }
}

private void fetchData(){
     // do fetch data into listData
}

How to do 3 table JOIN in UPDATE query?

Alternative way of achieving same result is not to use JOIN keyword at all.

UPDATE TABLE_A, TABLE_B
SET TABLE_A.column_c = TABLE_B.column_c + 1
WHERE TABLE_A.join_col = TABLE_B.join_col

Javascript add leading zeroes to date

I found the shorterst way to do this:

 MyDateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');

will add leading zeros to all lonely, single digits

Getting all names in an enum as a String[]

Here`s an elegant solution using Apache Commons Lang 3:

EnumUtils.getEnumList(State.class)

Although it returns a List, you can convert the list easily with list.toArray()

Given a DateTime object, how do I get an ISO 8601 date in string format?

To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.

The following will return the string represention you wanted:

DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)

How do I convert hex to decimal in Python?

If by "hex data" you mean a string of the form

s = "6a48f82d8e828ce82b82"

you can use

i = int(s, 16)

to convert it to an integer and

str(i)

to convert it to a decimal string.

Git: copy all files in a directory from another branch

If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use

git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')

PostgreSQL DISTINCT ON with different ORDER BY

A subquery can solve it:

SELECT *
FROM  (
    SELECT DISTINCT ON (address_id) *
    FROM   purchases
    WHERE  product_id = 1
    ) p
ORDER  BY purchased_at DESC;

Leading expressions in ORDER BY have to agree with columns in DISTINCT ON, so you can't order by different columns in the same SELECT.

Only use an additional ORDER BY in the subquery if you want to pick a particular row from each set:

SELECT *
FROM  (
    SELECT DISTINCT ON (address_id) *
    FROM   purchases
    WHERE  product_id = 1
    ORDER  BY address_id, purchased_at DESC  -- get "latest" row per address_id
    ) p
ORDER  BY purchased_at DESC;

If purchased_at can be NULL, use DESC NULLS LAST - and match your index for best performance. See:

Related, with more explanation:

How to properly validate input values with React.JS?

Sometimes you can have multiple fields with similar validation in your application. In such a case I recommend to create common component field where you keep this validation.

For instance, let's assume that you have mandatory text input in a few places in your application. You can create a TextInput component:

constructor(props) {
    super(props); 
    this.state = {
        touched: false, error: '', class: '', value: ''
    }
}

onValueChanged = (event) => {
    let [error, validClass, value] = ["", "", event.target.value];

    [error, validClass] = (!value && this.props.required) ? 
        ["Value cannot be empty", "is-invalid"] : ["", "is-valid"]

    this.props.onChange({value: value, error: error});

    this.setState({
        touched: true,
        error: error,
        class: validClass,
        value: value
    })
}

render() {
    return (
        <div>
            <input type="text"
                value={this.props.value}
                onChange={this.onValueChanged}
                className={"form-control " + this.state.class}
                id="{this.props.id}"
                placeholder={this.props.placeholder} />
            {this.state.error ?
                <div className="invalid-feedback">
                    {this.state.error}
                </div> : null
            }
        </div>
    )
}

And then you can use such a component anywhere in your application:

constructor(props) {
    super(props);
    this.state = {
        user: {firstName: '', lastName: ''},
        formState: {
            firstName: { error: '' },
            lastName: { error: '' }
        }
    }
}

onFirstNameChange = (model) => {
    let user = this.state.user;
    user.firstName = model.value;

    this.setState({
        user: user,
        formState: {...this.state.formState, firstName: { error: model.error }}
    })
}

onLastNameChange = (model) => {
    let user = this.state.user;
    user.lastName = model.value;

    this.setState({
        user: user,
        formState: {...this.state.formState, lastName: { error: model.error }}
    })
}


onSubmit = (e) => {
   // submit logic
}


render() {
    return (
        <form onSubmit={this.onSubmit}>
            <TextInput id="input_firstName"
                value={this.state.user.firstName}
                onChange={this.onFirstNameChange}
                required = {true}
                placeholder="First name" />

            <TextInput id="input_lastName"
                value={this.state.user.lastName}
                onChange={this.onLastNameChange}
                required = {true}
                placeholder="Last name" />

            {this.state.formState.firstName.error || this.state.formState.lastName.error ?
                <button type="submit" disabled className="btn btn-primary margin-left disabled">Save</button>
                : <button type="submit" className="btn btn-primary margin-left">Save</button>
            }

        </form>
    )
}

Benefits:

  • You don't repeat your validation logic
  • Less code in your forms - it is more readable
  • Other common input logic can be kept in component
  • You follow React rule that component should be as dumb as possible

Ref. https://webfellas.tech/#/article/5

Screenshot sizes for publishing android app on Google Play

You can upload up to 8 screenshots. Those screenshots must be one of the dimensions (sizes) you listed; you can have multiple screenshots of the same dimensions.

How do I execute a stored procedure in a SQL Agent job?

As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.

Java character array initializer

char array[] = new String("Hi there").toCharArray();
for(char c : array)
    System.out.print(c + " ");

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

How do I add an image to a JButton

It looks like a location problem because that code is perfectly fine for adding the icon.

Since I don't know your folder structure, I suggest adding a simple check:

File imageCheck = new File("water.bmp");

if(imageCheck.exists()) 
    System.out.println("Image file found!")
else 
    System.out.println("Image file not found!");

This way if you ever get your path name wrong it will tell you instead of displaying nothing. Exception should be thrown if file would not exist, tho.

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c = inputstream.read();
        raw+=(char)c;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while

What is the meaning of the prefix N in T-SQL statements and when should I use it?

1. Performance:

Assume your where clause is like this:

WHERE NAME='JON'

If the NAME column is of any type other than nvarchar or nchar, then you should not specify the N prefix. However, if the NAME column is of type nvarchar or nchar, then if you do not specify the N prefix, then 'JON' is treated as non-unicode. This means the data type of NAME column and string 'JON' are different and so SQL Server implicitly converts one operand’s type to the other. If the SQL Server converts the literal’s type to the column’s type then there is no issue, but if it does the other way then performance will get hurt because the column's index (if available) wont be used.

2. Character set:

If the column is of type nvarchar or nchar, then always use the prefix N while specifying the character string in the WHERE criteria/UPDATE/INSERT clause. If you do not do this and one of the characters in your string is unicode (like international characters - example - a) then it will fail or suffer data corruption.

How to use the start command in a batch file?

An extra pair of rabbits' ears should do the trick.

start "" "C:\Program...

START regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START switches.

How to strip all non-alphabetic characters from string in SQL Server?

--First create one function

CREATE FUNCTION [dbo].[GetNumericonly]
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
     DECLARE @intAlpha INT
     SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
     WHILE @intAlpha > 0
   BEGIN
          SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
          SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
   END
END
RETURN ISNULL(@strAlphaNumeric,0)
END

Now call this function like

select [dbo].[GetNumericonly]('Abhi12shek23jaiswal')

Its result like

1223

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

One thing which is invariably true is that at this time, the device would be suffocating for some memory (which is usually the reason for GC to most likely get triggered).

As mentioned by almost all authors earlier, this issue surfaces when Android tries to run GC while the app is in background. In most of the cases where we observed it, user paused the app by locking their screen. This might also indicate memory leak somewhere in the application, or the device being too loaded already. So the only legitimate way to minimize it is:

  • to ensure there are no memory leaks, and
  • to reduce the memory footprint of the app in general.

How to efficiently remove duplicates from an array without using Set

  public static void main(String[] args) { 
            int input[] = { 1, 5, 1, 0, -3, 1, -3, 2, 1 }; 
            int j = 0; 
            int output[] = new int[100]; 
            Arrays.fill(a, 0); 
            for (int i = 0; i < 9; i++) { 
                    if (output[input[i]] == 0) {
                            input[j++] = input[i]; 
                            output[input[i]]++; 
                    } 
            } 
            for (int i = 0; i < j; i++) { 
                    System.out.print(input[i] + " "); 
            } 
    }

QR Code encoding and decoding using zxing

this is my working example Java code to encode QR code using ZXing with UTF-8 encoding, please note: you will need to change the path and utf8 data to your path and language characters

package com.mypackage.qr;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;

import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.*;

public class CreateQR {

public static void main(String[] args)
{
    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] b = null;
    try {
        // Convert a string to UTF-8 bytes in a ByteBuffer
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("utf 8 characters - i used hebrew, but you should write some of your own language characters"));
        b = bbuf.array();
    } catch (CharacterCodingException e) {
        System.out.println(e.getMessage());
    }

    String data;
    try {
        data = new String(b, "UTF-8");
        // get a byte matrix for the data
        BitMatrix matrix = null;
        int h = 100;
        int w = 100;
        com.google.zxing.Writer writer = new MultiFormatWriter();
        try {
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            matrix = writer.encode(data,
            com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints);
        } catch (com.google.zxing.WriterException e) {
            System.out.println(e.getMessage());
        }

        // change this path to match yours (this is my mac home folder, you can use: c:\\qr_png.png if you are on windows)
                String filePath = "/Users/shaybc/Desktop/OutlookQR/qr_png.png";
        File file = new File(filePath);
        try {
            MatrixToImageWriter.writeToFile(matrix, "PNG", file);
            System.out.println("printing to " + file.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    } catch (UnsupportedEncodingException e) {
        System.out.println(e.getMessage());
    }
}

}

How to import image (.svg, .png ) in a React Component

There are few steps if we dont use "create-react-app",([email protected]) first we should install file-loader as devDedepencie,next step is to add rule in webpack.config

_x000D_
_x000D_
{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
}
_x000D_
_x000D_
_x000D_

, then in our src directory we should make file called declarationFiles.d.ts(for example) and register modules inside

_x000D_
_x000D_
declare module '*.jpg';
declare module '*.png';
_x000D_
_x000D_
_x000D_

,then restart dev-server. After these steps we can import and use images like in code bellow

_x000D_
_x000D_
import React from 'react';
import image from './img1.png';
import './helloWorld.scss';

const HelloWorld = () => (
  <>
    <h1 className="main">React TypeScript Starter</h1>
        <img src={image} alt="some example image" />
  </>
);
export default HelloWorld;
_x000D_
_x000D_
_x000D_

Works in typescript and also in javacript,just change extension from .ts to .js

Cheers.

Python string to unicode

Decode it with the unicode-escape codec:

>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…

This is because for a non-unicode string the \u2026 is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'). You need to decode the escapes, and the unicode-escape codec can do that for you.

Note that you can get unicode to recognise it in the same way by specifying the codec argument:

>>> unicode(a, 'unicode-escape')
u'Hello\u2026'

But the a.decode() way is nicer.

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

Encode URL in JavaScript?

Encode URL String

    var url = $(location).attr('href'); //get current url
    //OR
    var url = 'folder/index.html?param=#23dd&noob=yes'; //or specify one

var encodedUrl = encodeURIComponent(url); console.log(encodedUrl); //outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes for more info go http://www.sitepoint.com/jquery-decode-url-string

How to set environment variables in Python?

Use setdefault function to set a new variable if the variable does not exist in the environment.

make sure you set the environment variable as a string, not int. Otherwise will throw TypeError.

import os

if not os.environ.get("DEBUSSY"):
    os.environ.setdefault("DEBUSSY","1")
else:
     os.environ["DEBUSSY"] = "1"

print(os.environ["DEBUSSY"])

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

Pandas: Return Hour from Datetime Column Directly

You can try this:

sales['time_hour'] = pd.to_datetime(sales['timestamp']).dt.hour

Step-by-step debugging with IPython

Running from inside Emacs' IPython-shell and breakpoint set via pdb.set_trace() should work.

Checked with python-mode.el, M-x ipython RET etc.

How to send data to COM PORT using JAVA?

An alternative to javax.comm is the rxtx library which supports more platforms than javax.comm.

Format Date/Time in XAML in Silverlight

In SL5 I found this to work:

<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat=dd-MMMM-yy hh:mm}">
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat='Justification Date: \{0:dd-MMMM-yy hh:mm\}'}">

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

The following code makes the window always stay on top as well as make it frameless.

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace StayOnTop
{
    public partial class Form1 : Form
    {
        private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        private const UInt32 SWP_NOSIZE = 0x0001;
        private const UInt32 SWP_NOMOVE = 0x0002;
        private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        public Form1()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
            TopMost = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetWindowPos(this.Handle, HWND_TOPMOST, 100, 100, 300, 300, TOPMOST_FLAGS);
        }

        protected override void WndProc(ref Message m)
        {
            const int RESIZE_HANDLE_SIZE = 10;

            switch (m.Msg)
            {
                case 0x0084/*NCHITTEST*/ :
                    base.WndProc(ref m);

                    if ((int)m.Result == 0x01/*HTCLIENT*/)
                    {
                        Point screenPoint = new Point(m.LParam.ToInt32());
                        Point clientPoint = this.PointToClient(screenPoint);
                        if (clientPoint.Y <= RESIZE_HANDLE_SIZE)
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)13/*HTTOPLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)12/*HTTOP*/ ;
                            else
                                m.Result = (IntPtr)14/*HTTOPRIGHT*/ ;
                        }
                        else if (clientPoint.Y <= (Size.Height - RESIZE_HANDLE_SIZE))
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)10/*HTLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)2/*HTCAPTION*/ ;
                            else
                                m.Result = (IntPtr)11/*HTRIGHT*/ ;
                        }
                        else
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)16/*HTBOTTOMLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)15/*HTBOTTOM*/ ;
                            else
                                m.Result = (IntPtr)17/*HTBOTTOMRIGHT*/ ;
                        }
                    }
                    return;
            }
            base.WndProc(ref m);
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style |= 0x20000; // <--- use 0x20000
                return cp;
            }
        }
    }
}

Finish an activity from another activity

First call startactivity() then use finish()

How to remove an unpushed outgoing commit in Visual Studio?

You have 2 options here to do that either to discard all your outgoing commits OR to undo specific commit ..

1- Discard all your outgoing commits:

To discard all your outgoing commits For example if you have local branch named master from remote branch, You can:

1- Rename your local branch from master to anything so you can remove it. 2- Remove the renamed branch. 3- create new branch from the master

So now you have a new branch without your commits ..

2- Undo specific commit: To undo specific commit you have to revert the unneeded by:

1- Double click on the unneeded commit. Double click on the unneeded commit 2- Click on revert Click on revert

But FYI the reverted commit will appear in the history of your commits with the revert commit ..

XSLT string replace

Note: In case you wish to use the already-mentioned algo for cases where you need to replace huge number of instances in the source string (e.g. new lines in long text) there is high probability you'll end up with StackOverflowException because of the recursive call.

I resolved this issue thanks to Xalan's (didn't look how to do it in Saxon) built-in Java type embedding:

<xsl:stylesheet version="1.0" exclude-result-prefixes="xalan str"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xalan="http://xml.apache.org/xalan"
                xmlns:str="xalan://java.lang.String"
        >
...
<xsl:value-of select="str:replaceAll(
    str:new(text()),
    $search_string,
    $replace_string)"/>
...
</xsl:stylesheet>

Scroll to bottom of div?

Just as a bonus snippet. I'm using angular and was trying to scroll a message thread to the bottom when a user selected different conversations with users. In order to make sure that the scroll works after the new data had been loaded into the div with the ng-repeat for messages, just wrap the scroll snippet in a timeout.

$timeout(function(){
    var messageThread = document.getElementById('message-thread-div-id');
    messageThread.scrollTop = messageThread.scrollHeight;
},0)

That will make sure that the scroll event is fired after the data has been inserted into the DOM.

Package doesn't exist error in intelliJ

In case you're facing very weird "unable to resolve java, sun packages problem", try the following:

  1. Open Project Structure and change Project SDK to another version, example: java 8 -> 9; 11->13, etc, and wait until it re-index all jdk's jars. Switch between jdks with same version may not work! (Ex: jetbrains jdk11 -> openjdk 11)
  2. Open a new project (or create a empty one); pause new project's indexing; close the old one; start indexing; open the old project and pause the new project's indexing and wait.

How do you remove the title text from the Android ActionBar?

You can change the style applied to each activity, or if you only want to change the behavior for a specific activity, you can try this:

setDisplayOptions(int options, int mask) --- Set selected display 
  or
setDisplayOptions(int options) --- Set display options.

To display title on actionbar, set display options in onCreate()

getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);

To hide title on actionbar.

getSupportActionBar().setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

Details here.

Take n rows from a spark dataframe and pass to toPandas()

You can use the limit(n) function:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()

Or:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()

How to change the Jupyter start-up folder

Open Anaconda Prompt and write to open a notebook folder in G drive jupyter notebook --notebook-dir 'G:' there is no "="

How to get the input from the Tkinter Text Widget?

I faced the problem of gettng entire text from Text widget and following solution worked for me :

txt.get(1.0,END)

Where 1.0 means first line, zeroth character (ie before the first!) is the starting position and END is the ending position.

Thanks to Alan Gauld in this link

How can I let a user download multiple files when a button is clicked?

Found the easiest way to do this. Works even with div!

<div onclick="downloadFiles()">
  <!--do not put any text in <a>, it should be invisible-->
  <a href="path/file1" id="a1" download></a>
  <a href="path/file2" id="a2" download></a>
  <a href="path/file3" id="a3" download></a>
  <script>
    function downloadFiles() {
      document.getElementById("a1").click();
      document.getElementById("a2").click();
      document.getElementById("a3").click();
    }
  </script>
  Download
</div>

That's all, hope it helps.

How to display loading message when an iFrame is loading?

<!DOCTYPE html>
<html>
<head>
<title>jQuery Demo - IFRAME Loader</title>
<style>
#frameWrap {
    position:relative;
    height: 360px;
    width: 640px;
    border: 1px solid #777777;
    background:#f0f0f0;
    box-shadow:0px 0px 10px #777777;
}

#iframe1 {
    height: 360px;
    width: 640px;
    margin:0;
    padding:0;
    border:0;
}

#loader1 {
    position:absolute;
    left:40%;
    top:35%;
    border-radius:20px;
    padding:25px;
    border:1px solid #777777;
    background:#ffffff;
    box-shadow:0px 0px 10px #777777;
}
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>

<div id="frameWrap">
<img id="loader1" src="loading.gif" width="36" height="36" alt="loading gif"/>
<iframe id="iframe1" src="https://bots.actcorp.in/ACTAppChat/[email protected]&authToken=69d1afc8d06fb97bdb5a9275edbc53b375c3c7662c88b78239ba0cd8a940d59e" ></iframe>
</div>
<script>
    $(document).ready(function () {
        $('#iframe1').on('load', function () {
            $('#loader1').hide();
        });
    });
</script>

</body>
</html>

SVN "Already Locked Error"

I had the same problem, It was solved when I checked the below checkbox

What is the best free SQL GUI for Linux for various DBMS systems

I tried many GUI's, and the best for me continue being "SQLyog-comunity" by using wine. Is complete, is nice, and is intuitive. (and in wine work perfect)

How to load an ImageView by URL in Android?

I have recently found a thread here, as I have to do a similar thing for a listview with images, but the principle is simple, as you can read in the first sample class shown there (by jleedev). You get the Input stream of the image (from web)

private InputStream fetch(String urlString) throws MalformedURLException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(urlString);
    HttpResponse response = httpClient.execute(request);
    return response.getEntity().getContent();
}

Then you store the image as Drawable and you can pass it to the ImageView (via setImageDrawable). Again from the upper code snippet take a look at the entire thread.

InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");

Regular expression for validating names and surnames?

It's a very difficult problem to validate something like a name due to all the corner cases possible.

Corner Cases

Sanitize the inputs and let them enter whatever they want for a name, because deciding what is a valid name and what is not is probably way outside the scope of whatever you're doing; given the range of potential strange - and legal names is nearly infinite.

If they want to call themselves Tricyclopltz^2-Glockenschpiel, that's their problem, not yours.

The difference in months between dates in MySQL

You can get years, months and days this way:

SELECT 
username
,date_of_birth
,DATE_FORMAT(CURDATE(), '%Y') - DATE_FORMAT(date_of_birth, '%Y') - (DATE_FORMAT(CURDATE(), '00-%m-%d') < DATE_FORMAT(date_of_birth, '00-%m-%d')) AS years
,PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(date_of_birth, '%Y%m') ) AS months
,DATEDIFF(CURDATE(),date_of_birth) AS days
FROM users

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

Use the zzz format specifier to get the timezone offset as hours and minutes. You also want to use the HH format specifier to get the hours in 24 hour format.

DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")

Result:

2011-08-09T23:49:58+02:00

Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:

DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")

Custom Date and Time Format Strings

"Unable to find remote helper for 'https'" during git clone

For those using git with Jenkins under a windows system, you need to configure the location of git.exe under: Manage Jenkins => Global Tool Configuration => Git => Path to Git executable and fill-in the path to git.exe, for example; C:\Program Files\Git\bin\git.exe

WPF Add a Border to a TextBlock

No, you need to wrap your TextBlock in a Border. Example:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />
</Border>

Of course, you can set these properties (BorderThickness, BorderBrush) through styles as well:

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />
</Border>

How can I properly handle 404 in ASP.NET MVC?

Posting an answer since my comment was too long...

It's both a comment and questions to the unicorn post/answer:

https://stackoverflow.com/a/7499406/687549

I prefer this answer over the others for it's simplicity and the fact that apparently some folks at Microsoft were consulted. I got three questions however and if they can be answered then I will call this answer the holy grail of all 404/500 error answers on the interwebs for an ASP.NET MVC (x) app.

@Pure.Krome

  1. Can you update your answer with the SEO stuff from the comments pointed out by GWB (there was never any mentioning of this in your answer) - <customErrors mode="On" redirectMode="ResponseRewrite"> and <httpErrors errorMode="Custom" existingResponse="Replace">?

  2. Can you ask your ASP.NET team friends if it is okay to do it like that - would be nice to have some confirmation - maybe it's a big no-no to change redirectMode and existingResponse in this way to be able to play nicely with SEO?!

  3. Can you add some clarification surrounding all that stuff (customErrors redirectMode="ResponseRewrite", customErrors redirectMode="ResponseRedirect", httpErrors errorMode="Custom" existingResponse="Replace", REMOVE customErrors COMPLETELY as someone suggested) after talking to your friends at Microsoft?

As I was saying; it would be supernice if we could make your answer more complete as this seem to be a fairly popular question with 54 000+ views.

Update: Unicorn answer does a 302 Found and a 200 OK and cannot be changed to only return 404 using a route. It has to be a physical file which is not very MVC:ish. So moving on to another solution. Too bad because this seemed to be the ultimate MVC:ish answer this far.

What is setBounds and how do I use it?

Actually, a Swing component does have multiple dimensions, as:

  • current size - setSize() and setBounds() sets this
  • minimum size - setMinimumSize() sets this
  • preferred size - setPerferredSize() sets this
  • maximum size - setMaximumSize() sets this.

SetBounds is a shortcut for setting current size plus location of the widget if you don't use any layout manager.

If you use a layout manager, it is the responsibility of the layout manager to lay out your components, taking into account the preferred size you set, and ensuring that the comonent never gets smaller than its minimumSize or bigger than its maximumSize.

In this case, the layoutManager will call setSize (or setBounds), and you can not really control the position or dimension of the component.

The whole point of using a layout manager is to have a platform and window-size independent way of laying out your components automatically, therefore you don't expect to call setSize from your code.

(Personal comment: There are buggy layout managers, I personally hate all of them and rolled my own, which offers the flexibility of MigLayout without the learning curve.)

Display Python datetime without time

You can usee the following code: week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]

Sending HTTP POST Request In Java

simplest way to send parameters with the post request:

String postURL = "http://www.example.com/page.php";

HttpPost post = new HttpPost(postURL);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "10"));

UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(ent);

HttpClient client = new DefaultHttpClient();
HttpResponse responsePOST = client.execute(post);

You have done. now you can use responsePOST. Get response content as string:

BufferedReader reader = new BufferedReader(new  InputStreamReader(responsePOST.getEntity().getContent()), 2048);

if (responsePOST != null) {
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(" line : " + line);
        sb.append(line);
    }
    String getResponseString = "";
    getResponseString = sb.toString();
//use server output getResponseString as string value.
}

Draw Circle using css alone

yup.. here's my code:

<style>
  .circle{
     width: 100px;
     height: 100px;
     border-radius: 50%;
     background-color: blue
  }
</style>
<div class="circle">
</div>

How to measure time elapsed on Javascript?

var seconds = 0;
setInterval(function () {
  seconds++;
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

dll missing in JDBC

For easy fix follow these steps:

  1. goto: https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url#Connectingintegrated
  2. Download the JDBC file and extract to your preferred location
  3. open the auth folder matching your OS x64 or x86
  4. copy sqljdbc_auth.dll file
  5. paste in: C:\Program Files\Java\jdk_version\bin

restart either eclipse or netbeans

minimum double value in C/C++

Is there a standard and/or portable way to represent the smallest negative value (e.g. to use negative infinity) in a C(++) program?

C approach.

Many implementations support +/- infinities, so the most negative double value is -INFINITY.

#include <math.h>
double most_negative = -INFINITY;

Is there a standard and/or portable way ....?

Now we need to also consider other cases:

  • No infinities

Simply -DBL_MAX.

  • Only an unsigned infinity.

I'd expect in this case, OP would prefer -DBL_MAX.

  • De-normal values greater in magnitude than DBL_MAX.

This is an unusual case, likely outside OP's concern. When double is encoded as a pair of a floating points to achieve desired range/precession, (see double-double) there exist a maximum normal double and perhaps a greater de-normal one. I have seen debate if DBL_MAX should refer to the greatest normal, of the greatest of both.

Fortunately this paired approach usually includes an -infinity, so the most negative value remains -INFINITY.


For more portability, code can go down the route

// HUGE_VAL is designed to be infinity or DBL_MAX (when infinites are not implemented)
// .. yet is problematic with unsigned infinity.
double most_negative1 = -HUGE_VAL;  

// Fairly portable, unless system does not understand "INF"
double most_negative2 = strtod("-INF", (char **) NULL);

// Pragmatic
double most_negative3 = strtod("-1.0e999999999", (char **) NULL);

// Somewhat time-consuming
double most_negative4 = pow(-DBL_MAX, 0xFFFF /* odd value */);

// My suggestion
double most_negative5 = (-DBL_MAX)*DBL_MAX;

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

Echoing the last command run in Bash?

There is a racecondition between the last command ($_) and last error ( $?) variables. If you try to store one of them in an own variable, both encountered new values already because of the set command. Actually, last command hasn't got any value at all in this case.

Here is what i did to store (nearly) both informations in own variables, so my bash script can determine if there was any error AND setting the title with the last run command:

   # This construct is needed, because of a racecondition when trying to obtain
   # both of last command and error. With this the information of last error is
   # implied by the corresponding case while command is retrieved.

   if   [[ "${?}" == 0 && "${_}" != "" ]] ; then
    # Last command MUST be retrieved first.
      LASTCOMMAND="${_}" ;
      RETURNSTATUS='?' ;
   elif [[ "${?}" == 0 && "${_}" == "" ]] ; then
      LASTCOMMAND='unknown' ;
      RETURNSTATUS='?' ;
   elif [[ "${?}" != 0 && "${_}" != "" ]] ; then
    # Last command MUST be retrieved first.
      LASTCOMMAND="${_}" ;
      RETURNSTATUS='?' ;
      # Fixme: "$?" not changing state until command executed.
   elif [[ "${?}" != 0 && "${_}" == "" ]] ; then
      LASTCOMMAND='unknown' ;
      RETURNSTATUS='?' ;
      # Fixme: "$?" not changing state until command executed.
   fi

This script will retain the information, if an error occured and will obtain the last run command. Because of the racecondition i can not store the actual value. Besides, most commands actually don't even care for error noumbers, they just return something different from '0'. You'll notice that, if you use the errono extention of bash.

It should be possible with something like a "intern" script for bash, like in bash extention, but i'm not familiar with something like that and it wouldn't be compatible as well.

CORRECTION

I didn't think, that it was possible to retrieve both variables at the same time. Although i like the style of the code, i assumed it would be interpreted as two commands. This was wrong, so my answer devides down to:

   # Because of a racecondition, both MUST be retrieved at the same time.
   declare RETURNSTATUS="${?}" LASTCOMMAND="${_}" ;

   if [[ "${RETURNSTATUS}" == 0 ]] ; then
      declare RETURNSYMBOL='?' ;
   else
      declare RETURNSYMBOL='?' ;
   fi

Although my post might not get any positive rating, i solved my problem myself, finally. And this seems appropriate regarding the intial post. :)

How to apply a CSS filter to a background image

In the .content tab in CSS change it to position:absolute. Otherwise, the page rendered won't be scrollable.

How to lose margin/padding in UITextView?

For me (iOS 11 & Xcode 9.4.1) what worked magically was setting up textView.font property to UIFont.preferred(forTextStyle:UIFontTextStyle) style and also the first answer as mentioned by @Fattie. But the @Fattie answer did not work till I set the textView.font property else UITextView keeps behaving erratically.

How to update an "array of objects" with Firestore?

Other than the answers mentioned above. This will do it. Using Angular 5 and AngularFire2. or use firebase.firestore() instead of this.afs

  // say you have have the following object and 
  // database structure as you mentioned in your post
  data = { who: "[email protected]", when: new Date() };

  ...othercode


  addSharedWith(data) {

    const postDocRef = this.afs.collection('posts').doc('docID');

    postDocRef.subscribe( post => {

      // Grab the existing sharedWith Array
      // If post.sharedWith doesn`t exsit initiated with empty array
      const foo = { 'sharedWith' : post.sharedWith || []};

      // Grab the existing sharedWith Array
      foo['sharedWith'].push(data);

      // pass updated to fireStore
      postsDocRef.update(foo);
      // using .set() will overwrite everything
      // .update will only update existing values, 
      // so we initiated sharedWith with empty array
    });
 }  

Is there a way to pass javascript variables in url?

Summary

With either string concatenation or string interpolation (via template literals).

Here with JavaScript template literal:

function geoPreview() {
    var lat = document.getElementById("lat").value;
    var long = document.getElementById("long").value;

    window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${lat}&lon=${long}&setLatLon=Set`;
}

Both parameters are unused and can be removed.

Remarks

String Concatenation

Join strings with the + operator:

window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=" + elemA + "&lon=" + elemB + "&setLatLon=Set";

String Interpolation

For more concise code, use JavaScript template literals to replace expressions with their string representations. Template literals are enclosed by `` and placeholders surrounded with ${}:

window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${elemA}&lon=${elemB}&setLatLon=Set`;

Template literals are available since ECMAScript 2015 (ES6).

jQuery textbox change event doesn't fire until textbox loses focus?

$(this).bind('input propertychange', function() {
        //your code here
    });

This is works for typing, paste, right click mouse paste etc.

How to get table list in database, using MS SQL 2008?

This should give you a list of all the tables in your database

SELECT Distinct TABLE_NAME FROM information_schema.TABLES

So you can use it similar to your database check.

If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
    --CREATE TABLE Your_Table
END
GO

How to convert minutes to Hours and minutes (hh:mm) in java

import java.util.Scanner;
public class Time{
    public static void main(String[]args){
        int totMins=0;
        int hours=0;
        int mins=0;
    Scanner sc= new Scanner(System.in);
    System.out.println("Enter the time in mins: ");
        totMins= sc.nextInt();
        hours=(int)(totMins/60);
        mins =(int)(totMins%60);
        System.out.printf("%d:%d",hours,mins);
    }
}

Get Substring between two characters using javascript

Get string between two substrings (contains more than 1 character)

function substrInBetween(whole_str, str1, str2){
   if (whole_str.indexOf(str1) === -1 || whole_str.indexOf(str2) === -1) {
       return undefined; // or ""
  }
  strlength1 = str1.length;
  return whole_str.substring(
                whole_str.indexOf(str1) + strlength1, 
                whole_str.indexOf(str2)
               );

   }

Note I use indexOf() instead of lastIndexOf() so it will check for first occurences of those strings

Extension exists but uuid_generate_v4 fails

If you've changed the search_path, specify the public schema in the function call:

public.uuid_generate_v4()

cannot make a static reference to the non-static field

the lines

account.withdraw(balance, 2500);
account.deposit(balance, 3000);

you might want to make withdraw and deposit non-static and let it modify the balance

public void withdraw(double withdrawAmount) {
    balance = balance - withdrawAmount;
}

public void deposit(double depositAmount) {
    balance = balance + depositAmount;
}   

and remove the balance parameter from the call

When do we need curly braces around shell variables?

The end of the variable name is usually signified by a space or newline. But what if we don't want a space or newline after printing the variable value? The curly braces tell the shell interpreter where the end of the variable name is.

Classic Example 1) - shell variable without trailing whitespace

TIME=10

# WRONG: no such variable called 'TIMEsecs'
echo "Time taken = $TIMEsecs"

# What we want is $TIME followed by "secs" with no whitespace between the two.
echo "Time taken = ${TIME}secs"

Example 2) Java classpath with versioned jars

# WRONG - no such variable LATESTVERSION_src
CLASSPATH=hibernate-$LATESTVERSION_src.zip:hibernate_$LATEST_VERSION.jar

# RIGHT
CLASSPATH=hibernate-${LATESTVERSION}_src.zip:hibernate_$LATEST_VERSION.jar

(Fred's answer already states this but his example is a bit too abstract)

How do I set response headers in Flask?

This work for me

from flask import Flask
from flask import Response

app = Flask(__name__)

@app.route("/")
def home():
    return Response(headers={'Access-Control-Allow-Origin':'*'})

if __name__ == "__main__":
    app.run()

Using Get-childitem to get a list of files modified in the last 3 days

Try this:

(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
  $_.LastWriteTime -gt (Get-Date).AddDays(-3) 
}).Count

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

create table employee
(
   empid int,
   empname varchar(40),
   designation varchar(30),
   hiredate datetime, 
   Bsalary int,
   depno constraint emp_m foreign key references department(depno)
)

We should have an primary key to create foreign key or relationship between two or more table .

how to reference a YAML "setting" from elsewhere in the same YAML file?

Yes, using custom tags. Example in Python, making the !join tag join strings in an array:

import yaml

## define custom tag handler
def join(loader, node):
    seq = loader.construct_sequence(node)
    return ''.join([str(i) for i in seq])

## register the tag handler
yaml.add_constructor('!join', join)

## using your sample data
yaml.load("""
paths:
    root: &BASE /path/to/root/
    patha: !join [*BASE, a]
    pathb: !join [*BASE, b]
    pathc: !join [*BASE, c]
""")

Which results in:

{
    'paths': {
        'patha': '/path/to/root/a',
        'pathb': '/path/to/root/b',
        'pathc': '/path/to/root/c',
        'root': '/path/to/root/'
     }
}

The array of arguments to !join can have any number of elements of any data type, as long as they can be converted to string, so !join [*a, "/", *b, "/", *c] does what you would expect.

How do I increase the capacity of the Eclipse output console?

Under Window > Preferences, go to the Run/Debug > Console section, then you should see an option "Limit console output." You can unchecked this or change the number in the "Console buffer size (characters)" text box below. Do Unchecked.

This is for the Eclipse like Galileo, Kepler, Juno, Luna, Mars and Helios.

inner join in linq to entities

var res = from s in Splitting 
          join c in Customer on s.CustomerId equals c.Id
         where c.Id == customrId
            && c.CompanyId == companyId
        select s;

Using Extension methods:

var res = Splitting.Join(Customer,
                 s => s.CustomerId,
                 c => c.Id,
                 (s, c) => new { s, c })
           .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
           .Select(sc => sc.s);

Reason: no suitable image found

enter image description here

I have a similar issue, which detail information as the first image.

My solution is that switch the certification always trust to use system defaults. just like: enter image description here enter image description here

How to truncate string using SQL server

     CASE
     WHEN col IS NULL
        THEN ''
     ELSE SUBSTRING(col,1,15)+ '...' 
     END AS Col

How can I handle the warning of file_get_contents() function in PHP?

try {
   $site="http://www.google.com";
   $content = file_get_content($site);
   echo $content;
} catch (ErrorException $e) {
    // fix the url

}

set_error_handler(function ($errorNumber, $errorText, $errorFile,$errorLine ) 
{
    throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});

Android Fragment no view found for ID?

I had this problem (when building my UI in code) and it was caused by my ViewPager (that showed Fragments) not having an ID set, so I simply used pager.setID(id) and then it worked.

This page helped me figure that out.

How to save a list to a file and read it as a list type?

I am using pandas.

import pandas as pd
x = pd.Series([1,2,3,4,5])
x.to_excel('temp.xlsx')
y = list(pd.read_excel('temp.xlsx')[0])
print(y)

Use this if you are anyway importing pandas for other computations.

Android: how do I check if activity is running?

I used MyActivity.class and getCanonicalName method and I got answer.

protected Boolean isActivityRunning(Class activityClass)
{
        ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

        for (ActivityManager.RunningTaskInfo task : tasks) {
            if (activityClass.getCanonicalName().equalsIgnoreCase(task.baseActivity.getClassName()))
                return true;
        }

        return false;
}

get dictionary value by key

if (Data_Array["XML_File"] != "") String xmlfile = Data_Array["XML_File"];

How to add buttons at top of map fragment API v2 layout

extending de Almeida's answer I am editing code little bit here. since previous code was hiding gps location icon I did following way which worked better.

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"

>

<RadioGroup 
    android:id="@+id/radio_group_list_selector"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:orientation="horizontal" 
    android:background="#80000000"
    android:padding="4dp" >

    <RadioButton
        android:id="@+id/radioPopular"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="@string/Popular"
        android:gravity="center_horizontal|center_vertical"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioAZ"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/AZ"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />

    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioCategory"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/Category"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioNearBy"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/NearBy"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton3"
        android:textColor="@drawable/textcolor_radiobutton" />
</RadioGroup>

<fragment
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:scrollbars="vertical" />

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

How to get the current logged in user Id in ASP.NET Core

you can get it in your controller:

using System.Security.Claims;
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

or write an extension method like before .Core v1.0

using System;
using System.Security.Claims;

namespace Shared.Web.MvcExtensions
{
    public static class ClaimsPrincipalExtensions
    {
        public static string GetUserId(this ClaimsPrincipal principal)
        {
            if (principal == null)
                throw new ArgumentNullException(nameof(principal));

            return principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        }
    }
}

and get wherever user ClaimsPrincipal is available :

using Microsoft.AspNetCore.Mvc;
using Shared.Web.MvcExtensions;

namespace Web.Site.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return Content(this.User.GetUserId());
        }
    }
}

Is there any way to call a function periodically in JavaScript?

The setInterval() method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().

var intervalId = setInterval(function() {
  alert("Interval reached every 5s")
}, 5000);

// You can clear a periodic function by uncommenting:
// clearInterval(intervalId);

See more @ setInterval() @ MDN Web Docs

Why is Java Vector (and Stack) class considered obsolete or deprecated?

java.util.Stack inherits the synchronization overhead of java.util.Vector, which is usually not justified.

It inherits a lot more than that, though. The fact that java.util.Stack extends java.util.Vector is a mistake in object-oriented design. Purists will note that it also offers a lot of methods beyond the operations traditionally associated with a stack (namely: push, pop, peek, size). It's also possible to do search, elementAt, setElementAt, remove, and many other random-access operations. It's basically up to the user to refrain from using the non-stack operations of Stack.

For these performance and OOP design reasons, the JavaDoc for java.util.Stack recommends ArrayDeque as the natural replacement. (A deque is more than a stack, but at least it's restricted to manipulating the two ends, rather than offering random access to everything.)

Disable copy constructor

You can make the copy constructor private and provide no implementation:

private:
    SymbolIndexer(const SymbolIndexer&);

Or in C++11, explicitly forbid it:

SymbolIndexer(const SymbolIndexer&) = delete;

non static method cannot be referenced from a static context

You are calling nextInt statically by using Random.nextInt.

Instead, create a variable, Random r = new Random(); and then call r.nextInt(10).

It would be definitely worth while to check out:

Update:

You really should replace this line,

Random Random = new Random(); 

with something like this,

Random r = new Random();

If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.

Sending email from Command-line via outlook without having to click send

Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:

$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")

You could then launch the script from the command line as per this example:

powershell.exe -noexit c:\scripts\test.ps1

Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage command, making things easier.

Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.

Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:

Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.Recipient
    Dim objOutlookAttach As Outlook.Attachment

    Set objOutlook = CreateObject("Outlook.Application")
    Set objOutlookMsg  = objOutlook.CreateItem(olMailItem)

    With objOutlookMsg
        Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
        objOutlookRecip.Type = olTo
        ' Set the Subject, Body, and Importance of the message.
        .Subject = "This is an Automation test with Microsoft Outlook"
        .Body = "This is the body of the message." &vbCrLf & vbCrLf
        .Importance = olImportanceHigh  'High importance

        If Not IsMissing(AttachmentPath) Then
            Set objOutlookAttach = .Attachments.Add(AttachmentPath)
        End If

        For Each ObjOutlookRecip In .Recipients
            objOutlookRecip.Resolve
        Next

        .Save
        .Send
    End With
    Set objOutlook = Nothing
End Sub

Then, launch Outlook from the command line with the /autorun parameter, as per this answer (alter path/macroname as necessary):

C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname

Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.

Disable a Button

Let's say in Swift 4 you have a button set up for a segue as an IBAction like this @IBAction func nextLevel(_ sender: UIButton) {} and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:

var appMode = 0

@IBAction func mySegue(_ sender: UIButton) {

    if appMode == 1 {  // avoid crash if button pressed during other app actions and/or conditions
        let conflictingAction = sender as UIButton
        conflictingAction.isEnabled = false
    }
}

Please note that you will likely have other conditions within if appMode == 0 and/or if appMode == 1 that will still occur and NOT conflict with the mySegue button. Thus, AVOIDING A CRASH.

How can VBA connect to MySQL database in Excel?

Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):

Public oConn As ADODB.Connection
Sub MySqlInit()
    If oConn Is Nothing Then
        Dim str As String
        str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
        Set oConn = New ADODB.Connection
        oConn.Open str
    End If
End Sub

The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\

How to add and remove classes in Javascript without jQuery

Try this:

  const element = document.querySelector('#elementId');
  if (element.classList.contains("classToBeRemoved")) {
    element.classList.remove("classToBeRemoved");

  }

Get unique values from arraylist in java

Here's straightforward way without resorting to custom comparators or stuff like that:

Set<String> gasNames = new HashSet<String>();
List<YourRecord> records = ...;

for(YourRecord record : records) {
  gasNames.add(record.getGasName());
}

// now gasNames is a set of unique gas names, which you could operate on:
List<String> sortedGasses = new ArrayList<String>(gasNames);
Collections.sort(sortedGasses);

Note: Using TreeSet instead of HashSet would give directly sorted arraylist and above Collections.sort could be skipped, but TreeSet is otherwise less efficent, so it's often better, and rarely worse, to use HashSet even when sorting is needed.

What is a monad?

[Disclaimer: I am still trying to fully grok monads. The following is just what I have understood so far. If it’s wrong, hopefully someone knowledgeable will call me on the carpet.]

Arnar wrote:

Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it.

That’s precisely it. The idea goes like this:

  1. You take some kind of value and wrap it with some additional information. Just like the value is of a certain kind (eg. an integer or a string), so the additional information is of a certain kind.

    E.g., that extra information might be a Maybe or an IO.

  2. Then you have some operators that allow you to operate on the wrapped data while carrying along that additional information. These operators use the additional information to decide how to change the behaviour of the operation on the wrapped value.

    E.g., a Maybe Int can be a Just Int or Nothing. Now, if you add a Maybe Int to a Maybe Int, the operator will check to see if they are both Just Ints inside, and if so, will unwrap the Ints, pass them the addition operator, re-wrap the resulting Int into a new Just Int (which is a valid Maybe Int), and thus return a Maybe Int. But if one of them was a Nothing inside, this operator will just immediately return Nothing, which again is a valid Maybe Int. That way, you can pretend that your Maybe Ints are just normal numbers and perform regular math on them. If you were to get a Nothing, your equations will still produce the right result – without you having to litter checks for Nothing everywhere.

But the example is just what happens for Maybe. If the extra information was an IO, then that special operator defined for IOs would be called instead, and it could do something totally different before performing the addition. (OK, adding two IO Ints together is probably nonsensical – I’m not sure yet.) (Also, if you paid attention to the Maybe example, you have noticed that “wrapping a value with extra stuff” is not always correct. But it’s hard to be exact, correct and precise without being inscrutable.)

Basically, “monad” roughly means “pattern”. But instead of a book full of informally explained and specifically named Patterns, you now have a language construct – syntax and all – that allows you to declare new patterns as things in your program. (The imprecision here is all the patterns have to follow a particular form, so a monad is not quite as generic as a pattern. But I think that’s the closest term that most people know and understand.)

And that is why people find monads so confusing: because they are such a generic concept. To ask what makes something a monad is similarly vague as to ask what makes something a pattern.

But think of the implications of having syntactic support in the language for the idea of a pattern: instead of having to read the Gang of Four book and memorise the construction of a particular pattern, you just write code that implements this pattern in an agnostic, generic way once and then you are done! You can then reuse this pattern, like Visitor or Strategy or Façade or whatever, just by decorating the operations in your code with it, without having to re-implement it over and over!

So that is why people who understand monads find them so useful: it’s not some ivory tower concept that intellectual snobs pride themselves on understanding (OK, that too of course, teehee), but actually makes code simpler.

How to output numbers with leading zeros in JavaScript?

From https://gist.github.com/1180489

function pad(a, b){
  return(1e15 + a + '').slice(-b);
}

With comments:

function pad(
  a, // the number to convert 
  b // number of resulting characters
){
  return (
    1e15 + a + // combine with large number
    "" // convert to string
  ).slice(-b) // cut leading "1"
}

How to make this Header/Content/Footer layout using CSS?

Try This

<!DOCTYPE html>

<html>

<head>

<title>Sticky Header and Footer</title>

<style type="text/css">

/* Reset body padding and margins */

body {
    margin:0;

    padding:0;
}

/* Make Header Sticky */

#header_container {

    background:#eee;

    border:1px solid #666;

    height:60px;

    left:0;

    position:fixed;

    width:100%;

    top:0;
}

#header {

    line-height:60px;

    margin:0 auto;

    width:940px;

    text-align:center;
}

/* CSS for the content of page. I am giving top and bottom padding of 80px to make sure the header and footer do not overlap the content.*/

#container {

    margin:0 auto;

    overflow:auto;

    padding:80px 0;

    width:940px;

}

#content {

}

/* Make Footer Sticky */

#footer_container {

    background:#eee;

    border:1px solid #666;

    bottom:0;

    height:60px;

    left:0;

    position:fixed;

    width:100%;
}

#footer {

    line-height:60px;

    margin:0 auto;

    width:940px;

    text-align:center;

}

</style>

</head>

<body>

<!-- BEGIN: Sticky Header -->
<div id="header_container">

    <div id="header">
        Header Content
    </div>

</div>
<!-- END: Sticky Header -->

<!-- BEGIN: Page Content -->
<div id="container">

    <div id="content">

            content
        <br /><br />
            blah blah blah..
        ...
    </div>

</div>
<!-- END: Page Content -->

<!-- BEGIN: Sticky Footer -->
<div id="footer_container">

    <div id="footer">

        Footer Content

    </div>

</div>

<!-- END: Sticky Footer -->

</body>

</html>

How to get JQuery.trigger('click'); to initiate a mouse click

You just need to put a small timeout event before doing .click() like this :

setTimeout(function(){ $('#btn').click()}, 100);

How to embed YouTube videos in PHP?

Here is some code I've wrote to automatically turn URL's into links and automatically embed any video urls from youtube. I made it for a chat room I'm working on and it works pretty well. I'm sure it will work just fine for any other purpose as well like a blog for instance.

All you have to do is call the function "autolink()" and pass it the string to be parsed.

For example include the function below and then echo this code.

`
echo '<div id="chat_message">'.autolink($string).'</div>';

/****************Function to include****************/

<?php

function autolink($string){
    // force http: on www.
    $string = str_ireplace( "www.", "http://www.", $string );
    // eliminate duplicates after force
    $string = str_ireplace( "http://http://www.", "http://www.", $string );
    $string = str_ireplace( "https://http://www.", "https://www.", $string );

    // The Regular Expression filter
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    // Check if there is a url in the text

$m = preg_match_all($reg_exUrl, $string, $match); 

if ($m) { 
$links=$match[0]; 
for ($j=0;$j<$m;$j++) { 

    if(substr($links[$j], 0, 18) == 'http://www.youtube'){

    $string=str_replace($links[$j],'<a href="'.$links[$j].'" rel="nofollow" target="_blank">'.$links[$j].'</a>',$string).'<br /><iframe title="YouTube video player" class="youtube-player" type="text/html" width="320" height="185" src="http://www.youtube.com/embed/'.substr($links[$j], -11).'" frameborder="0" allowFullScreen></iframe><br />';


    }else{

    $string=str_replace($links[$j],'<a href="'.$links[$j].'" rel="nofollow" target="_blank">'.$links[$j].'</a>',$string);

        } 

    } 
} 




               return ($string);
 }

?>

`

How to import existing Android project into Eclipse?

Updating @JamesWald's answer, and incorporating other comments. Assuming you want to create a cfesh copy from, say, a backup in your new workspace:

  1. Put the existing project in a directory not inside the destination workspace.
  2. In Eclipse: File->Import->Android->Existing Android Code into Workspace, Next
  3. Select root directory: /path/to/project/from/step/1
  4. Projects->Select All (or not, as the case may be)
  5. Make sure you set the new project name correctly - To change one click on the old project name (left column) and then click on the new project name (right column) and then edit. It will default to the class name of the Default Activity.
  6. Assuming you want a copy in the destination workspace, check "Copy projects into workspace"
  7. uncheck "Add project to working sets"
  8. Finish

Getting RAW Soap Data from a Web Reference Client running in ASP.net

Not sure why all the fuss with web.config or a serializer class. The below code worked for me:

XmlSerializer xmlSerializer = new XmlSerializer(myEnvelope.GetType());

using (StringWriter textWriter = new StringWriter())
{
    xmlSerializer.Serialize(textWriter, myEnvelope);
    return textWriter.ToString();
}

How to select and change value of table cell with jQuery?

$("td:contains('c')").html("new");

or, more precisely $("#table_headers td:contains('c')").html("new");

and maybe for reuse you could create a function to call

function ReplaceCellContent(find, replace)
{
    $("#table_headers td:contains('" + find + "')").html(replace);
}

Adding values to specific DataTable cells

I think you can't do that but atleast you can update it. In order to edit an existing row in a DataTable, you need to locate the DataRow you want to edit, and then assign the updated values to the desired columns.

Example,

DataSet1.Tables(0).Rows(4).Item(0) = "Updated Company Name"
DataSet1.Tables(0).Rows(4).Item(1) = "Seattle"

SOURCE HERE

Trigger change event <select> using jquery

Another working solution for those who were blocked with jQuery trigger handler, that dosent fire on native events will be like below (100% working) :

var sortBySelect = document.querySelector("select.your-class"); 
sortBySelect.value = "new value"; 
sortBySelect.dispatchEvent(new Event("change"));

how to add value to a tuple?

In Python, you can't. Tuples are immutable.

On the containing list, you could replace tuple ('1', '2', '3', '4') with a different ('1', '2', '3', '4', '1234') tuple though.

Python "string_escape" vs "unicode_escape"

Within the range 0 = c < 128, yes the ' is the only difference for CPython 2.6.

>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])

Outside of this range the two types are not exchangeable.

>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)

>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode

On Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.

How to debug heap corruption errors?

I'd like to add my experience. In the last few days, I solved an instance of this error in my application. In my particular case, the errors in the code were:

  • Removing elements from an STL collection while iterating over it (I believe there are debug flags in Visual Studio to catch these things; I caught it during code review)
  • This one is more complex, I'll divide it in steps:
    • From a native C++ thread, call back into managed code
    • In managed land, call Control.Invoke and dispose a managed object which wraps the native object to which the callback belongs.
    • Since the object is still alive inside the native thread (it will remain blocked in the callback call until Control.Invoke ends). I should clarify that I use boost::thread, so I use a member function as the thread function.
    • Solution: Use Control.BeginInvoke (my GUI is made with Winforms) instead so that the native thread can end before the object is destroyed (the callback's purpose is precisely notifying that the thread ended and the object can be destroyed).

How can I get Android Wifi Scan Results into a list?

Find a complete working example below:

The code by @Android is very good but has few issues, namely:

  1. Populating to ListView code needs to be moved to onReceive of BroadCastReceiver where only the result will be available. In the case result is obtained at 2nd attempt.
  2. BroadCastReceiver needs to be unregistered after the results are obtained.
  3. size = size -1 seems unnecessary.

Find below the modified code of @Android as a working example:

WifiScanner.java which is the Main Activity

package com.arjunandroid.wifiscanner;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class WifiScanner extends Activity implements View.OnClickListener{


    WifiManager wifi;
    ListView lv;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<String> arraylist = new ArrayList<>();
    ArrayAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getActionBar().setTitle("Widhwan Setup Wizard");

        setContentView(R.layout.activity_wifi_scanner);

        buttonScan = (Button) findViewById(R.id.scan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.wifilist);


        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }
        this.adapter =  new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arraylist);
        lv.setAdapter(this.adapter);

        scanWifiNetworks();
    }

    public void onClick(View view)
    {
        scanWifiNetworks();
    }

    private void scanWifiNetworks(){

        arraylist.clear();
        registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        wifi.startScan();

        Log.d("WifScanner", "scanWifiNetworks");

        Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();

    }

    BroadcastReceiver wifi_receiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context c, Intent intent)
        {
            Log.d("WifScanner", "onReceive");
            results = wifi.getScanResults();
            size = results.size();
            unregisterReceiver(this);

            try
            {
                while (size >= 0)
                {
                    size--;
                    arraylist.add(results.get(size).SSID);
                    adapter.notifyDataSetChanged();
                }
            }
            catch (Exception e)
            {
                Log.w("WifScanner", "Exception: "+e);

            }


        }
    };

}

activity_wifi_scanner.xml which is the layout file for the Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/wifilist"
        android:layout_width="match_parent"
        android:layout_height="312dp"
        android:layout_weight="0.97" />


    <Button
        android:id="@+id/scan"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="bottom"
        android:layout_margin="15dp"
        android:background="@android:color/holo_green_light"
        android:text="Scan Again" />
</LinearLayout>

Also as mentioned above, do not forget to add Wifi permissions in the AndroidManifest.xml

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

PHP - check if variable is undefined

JavaScript's 'strict not equal' operator (!==) on comparison with undefined does not result in false on null values.

var createTouch = null;
isTouch = createTouch !== undefined  // true

To achieve an equivalent behaviour in PHP, you can check whether the variable name exists in the keys of the result of get_defined_vars().

// just to simplify output format
const BR = '<br>' . PHP_EOL;

// set a global variable to test independence in local scope
$test = 1;

// test in local scope (what is working in global scope as well)
function test()
{
  // is global variable found?
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test does not exist.

  // is local variable found?
  $test = null;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // try same non-null variable value as globally defined as well
  $test = 1;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // repeat test after variable is unset
  unset($test);
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.') . BR;
  // $test does not exist.
}

test();

In most cases, isset($variable) is appropriate. That is aquivalent to array_key_exists('variable', get_defined_vars()) && null !== $variable. If you just use null !== $variable without prechecking for existence, you will mess up your logs with warnings because that is an attempt to read the value of an undefined variable.

However, you can apply an undefined variable to a reference without any warning:

// write our own isset() function
function my_isset(&$var)
{
  // here $var is defined
  // and initialized to null if the given argument was not defined
  return null === $var;
}

// passing an undefined variable by reference does not log any warning
$is_set = my_isset($undefined_variable);   // $is_set is false

Ajax request returns 200 OK, but an error event is fired instead of success

Use the following code to ensure the response is in JSON format (PHP version)...

header('Content-Type: application/json');
echo json_encode($return_vars);
exit;

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

How do I run a batch file from my Java Application?

Sometimes the thread execution process time is higher than JVM thread waiting process time, it use to happen when the process you're invoking takes some time to be processed, use the waitFor() command as follows:

try{    
    Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable");
    p.waitFor();

}catch( IOException ex ){
    //Validate the case the file can't be accesed (not enought permissions)

}catch( InterruptedException ex ){
    //Validate the case the process is being stopped by some external situation     

}

This way the JVM will stop until the process you're invoking is done before it continue with the thread execution stack.

Download file inside WebView

Have you tried?

mWebView.setDownloadListener(new DownloadListener() {
    public void onDownloadStart(String url, String userAgent,
                String contentDisposition, String mimetype,
                long contentLength) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
    }
});

Example Link: Webview File Download - Thanks @c49

How to extract file name from path?

Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.

sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "\") + 1)

sFolderName = Left(sPath, Len(sPath) - Len(sFileName))

You can test the output using this code:

'Visual Basic for Applications 
http = "https://www.server.com/docs/Letter.txt"
unix = "/home/user/docs/Letter.txt"
dos = "C:\user\docs\Letter.txt"
win = "\\Server01\user\docs\Letter.txt"
blank = ""

sPath = unix 
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "\") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))

Debug.print "Folder: " & sFolderName & " File: " & sFileName

Also see: Wikipedia - Path (computing)

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

python xlrd unsupported format, or corrupt file.

I just downloaded xlrd, created an excel document (excel 2007) for testing and got the same error (message says 'found PK\x03\x04\x14\x00\x06\x00'). Extension is a xlsx. Tried saving it to an older .xls format and error disappears .....

What causes the Broken Pipe Error?

When peer close, you just do not know whether it just stop sending or both sending and receiving.Because TCP allows this, btw, you should know the difference between close and shutdown. If peer both stop sending and receiving, first you send some bytes, it will succeed. But the peer kernel will send you RST. So subsequently you send some bytes, your kernel will send you SIGPIPE signal, if you catch or ignore this signal, when your send returns, you just get Broken pipe error, or if you don't , the default behavior of your program is crashing.

HTTP Request in Kotlin

Using only the standard library with minimal code!

thread {
    val jsonStr = try { URL(url).readText() } catch (ex: Exception) { return@thread }
    runOnUiThread { displayOrWhatever(jsonStr) }
}

This starts a GET request on a new thread, leaving the UI thread to respond to user input. However, we can only modify UI elements from the main/UI thread, so we actually need a runOnUiThread block to show the result to our user. This enqueues our display code to be run on the UI thread soon.

The try/catch is there so your app won't crash if you make a request with your phone's internet off. Add your own error handling (e.g. showing a Toast) as you please.

.readText() is not part of the java.net.URL class but a Kotlin extension method, Kotlin "glues" this method onto URL. This is enough for plain GET requests, but for more control and POST requests you need something like the Fuel library.

Graphviz's executables are not found (Python 3.4)

If you are on Win10, install Graphviz and then use following command to add the path.

import os
os.environ["PATH"] += os.pathsep + 'C:\Program Files (x86)\Graphviz2.38/bin/'

C pass int array pointer as parameter into a function

Make use of *(B) instead of *B[0]. Here, *(B+i) implies B[i] and *(B) implies B[0], that is
*(B+0)=*(B)=B[0].

#include <stdio.h>

int func(int *B){
    *B = 5;     
    // if you want to modify ith index element in the array just do *(B+i)=<value>
}

int main(void){

    int B[10] = {};
    printf("b[0] = %d\n\n", B[0]);
    func(B);
    printf("b[0] = %d\n\n", B[0]);
    return 0;
}

Simple way to create matrix of random numbers

A simple way of creating an array of random integers is:

matrix = np.random.randint(maxVal, size=(rows, columns))

The following outputs a 2 by 3 matrix of random integers from 0 to 10:

a = np.random.randint(10, size=(2,3))

Create a dictionary with list comprehension

Python version >= 2.7, do the below:

d = {i: True for i in [1,2,3]}

Python version < 2.7(RIP, 3 July 2010 - 31 December 2019), do the below:

d = dict((i,True) for i in [1,2,3])

How do you set EditText to only accept numeric values in Android?

In code, you could do

ed_ins.setInputType(InputType.TYPE_CLASS_NUMBER);

How to get Toolbar from fragment?

You need to cast your activity from getActivity() to AppCompatActivity first. Here's an example:

((AppCompatActivity) getActivity()).getSupportActionBar().setTitle();

The reason you have to cast it is because getActivity() returns a FragmentActivity and you need an AppCompatActivity

In Kotlin:

(activity as AppCompatActivity).supportActionBar?.title = "My Title"

How to delete a row from GridView?

Delete the row from the table dtPrf_Mstr rather than from the grid view.

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

Another alternative: for 'switch's' like statements, with a lot of conditions, I like to use maps:

return Card(
        elevation: 0,
        margin: EdgeInsets.all(1),
        child: conditions(widget.coupon)[widget.coupon.status] ??
            (throw ArgumentError('invalid status')));


conditions(Coupon coupon) => {
      Status.added_new: CheckableCouponTile(coupon.code),
      Status.redeemed: SimpleCouponTile(coupon.code),
      Status.invalid: SimpleCouponTile(coupon.code),
      Status.valid_not_redeemed: SimpleCouponTile(coupon.code),
    };

It's easier to add/remove elements to the condition list without touch the conditional statement.

Another example:

var condts = {
  0: Container(),
  1: Center(),
  2: Row(),
  3: Column(),
  4: Stack(),
};

class WidgetByCondition extends StatelessWidget {
  final int index;
  WidgetByCondition(this.index);
  @override
  Widget build(BuildContext context) {
    return condts[index];
  }
}

Disabling the button after once click

$("selectorbyclassorbyIDorbyName").click(function () {
  $("selectorbyclassorbyIDorbyName").attr("disabled", true).delay(2000).attr("disabled", false);
});

select the button and by its id or text or class ... it just disables after 1st click and enables after 20 Milli sec

Works very well for post backs n place it in Master page, applies to all buttons without calling implicitly like onclientClick

How does HTTP_USER_AGENT work?

The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.

Service Temporarily Unavailable Magento?

Simply delete the maintenance.flag file in root folder and then delete the files of cache folder and session folder inside var/ folder.

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

How to get text from EditText?

in Kotlin 1.3

 val readTextFromUser = (findViewById(R.id.inputedText) as EditText).text.toString()

This will read the current text that the user has typed on the UI screen

How to display a pdf in a modal window?

You can have an iframe inside the modal markup and give the src attribute of it as the link to your pdf. On click of the link you can show this modal markup.

How do I get a Cron like scheduler in Python?

More or less same as above but concurrent using gevent :)

"""Gevent based crontab implementation"""

from datetime import datetime, timedelta
import gevent

# Some utility classes / functions first
def conv_to_set(obj):
    """Converts to set allowing single integer to be provided"""

    if isinstance(obj, (int, long)):
        return set([obj])  # Single item
    if not isinstance(obj, set):
        obj = set(obj)
    return obj

class AllMatch(set):
    """Universal set - match everything"""
    def __contains__(self, item): 
        return True

allMatch = AllMatch()

class Event(object):
    """The Actual Event Class"""

    def __init__(self, action, minute=allMatch, hour=allMatch, 
                       day=allMatch, month=allMatch, daysofweek=allMatch, 
                       args=(), kwargs={}):
        self.mins = conv_to_set(minute)
        self.hours = conv_to_set(hour)
        self.days = conv_to_set(day)
        self.months = conv_to_set(month)
        self.daysofweek = conv_to_set(daysofweek)
        self.action = action
        self.args = args
        self.kwargs = kwargs

    def matchtime(self, t1):
        """Return True if this event should trigger at the specified datetime"""
        return ((t1.minute     in self.mins) and
                (t1.hour       in self.hours) and
                (t1.day        in self.days) and
                (t1.month      in self.months) and
                (t1.weekday()  in self.daysofweek))

    def check(self, t):
        """Check and run action if needed"""

        if self.matchtime(t):
            self.action(*self.args, **self.kwargs)

class CronTab(object):
    """The crontab implementation"""

    def __init__(self, *events):
        self.events = events

    def _check(self):
        """Check all events in separate greenlets"""

        t1 = datetime(*datetime.now().timetuple()[:5])
        for event in self.events:
            gevent.spawn(event.check, t1)

        t1 += timedelta(minutes=1)
        s1 = (t1 - datetime.now()).seconds + 1
        print "Checking again in %s seconds" % s1
        job = gevent.spawn_later(s1, self._check)

    def run(self):
        """Run the cron forever"""

        self._check()
        while True:
            gevent.sleep(60)

import os 
def test_task():
    """Just an example that sends a bell and asd to all terminals"""

    os.system('echo asd | wall')  

cron = CronTab(
  Event(test_task, 22, 1 ),
  Event(test_task, 0, range(9,18,2), daysofweek=range(0,5)),
)
cron.run()

How are environment variables used in Jenkins with Windows Batch Command?

I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.

If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE

echo %WORKSPACE%

If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &, &&, or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.

setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
  set WORKSPACE=AFTER
  echo Normal Expansion = %WORKSPACE%
  echo Delayed Expansion = !WORKSPACE!
)

The output of the above is

Normal Expansion = BEFORE
Delayed Expansion = AFTER

Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.

How to remove gaps between subplots in matplotlib?

Without resorting gridspec entirely, the following might also be used to remove the gaps by setting wspace and hspace to zero:

import matplotlib.pyplot as plt

plt.clf()
f, axarr = plt.subplots(4, 4, gridspec_kw = {'wspace':0, 'hspace':0})

for i, ax in enumerate(f.axes):
    ax.grid('on', linestyle='--')
    ax.set_xticklabels([])
    ax.set_yticklabels([])

plt.show()
plt.close()

Resulting in:

.

Deserialize from string instead TextReader

public static string XmlSerializeToString(this object objectInstance)
{
    var serializer = new XmlSerializer(objectInstance.GetType());
    var sb = new StringBuilder();

    using (TextWriter writer = new StringWriter(sb))
    {
        serializer.Serialize(writer, objectInstance);
    }

    return sb.ToString();
}

public static T XmlDeserializeFromString<T>(this string objectData)
{
    return (T)XmlDeserializeFromString(objectData, typeof(T));
}

public static object XmlDeserializeFromString(this string objectData, Type type)
{
    var serializer = new XmlSerializer(type);
    object result;

    using (TextReader reader = new StringReader(objectData))
    {
        result = serializer.Deserialize(reader);
    }

    return result;
}

To use it:

//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();

//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>(); 

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

The accepted answer explains already well why the warning occurs. If you simply want to control the warnings, one could use precision_recall_fscore_support. It offers a (semi-official) argument warn_for that could be used to mute the warnings.

(_, _, f1, _) = metrics.precision_recall_fscore_support(y_test, y_pred,
                                                        average='weighted', 
                                                        warn_for=tuple())

As mentioned already in some comments, use this with care.

What is the precise meaning of "ours" and "theirs" in git?

From git checkout's usage:

-2, --ours            checkout our version for unmerged files
-3, --theirs          checkout their version for unmerged files
-m, --merge           perform a 3-way merge with the new branch

When resolving merge conflicts, you can do git checkout --theirs some_file, and git checkout --ours some_file to reset the file to the current version and the incoming versions respectively.

If you've done git checkout --ours some_file or git checkout --theirs some_file and would like to reset the file to the 3-way merge version of the file, you can do git checkout --merge some_file.

How to sort a Collection<T>?

If your collections object is a list, I would use the sort method, as proposed in the other answers.

However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:

TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);

Get width in pixels from element with style set with %?

Not a single answer does what was asked in vanilla JS, and I want a vanilla answer so I made it myself.

clientWidth includes padding and offsetWidth includes everything else (jsfiddle link). What you want is to get the computed style (jsfiddle link).

function getInnerWidth(elem) {
    return parseFloat(window.getComputedStyle(elem).width);
}

EDIT: getComputedStyle is non-standard, and can return values in units other than pixels. Some browsers also return a value which takes the scrollbar into account if the element has one (which in turn gives a different value than the width set in CSS). If the element has a scrollbar, you would have to manually calculate the width by removing the margins and paddings from the offsetWidth.

function getInnerWidth(elem) {
    var style = window.getComputedStyle(elem);
    return elem.offsetWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight) - parseFloat(style.borderLeft) - parseFloat(style.borderRight) - parseFloat(style.marginLeft) - parseFloat(style.marginRight);
}

With all that said, this is probably not an answer I would recommend following with my current experience, and I would resort to using methods that don't rely on JavaScript as much.

Equivalent of varchar(max) in MySQL?

For Sql Server

alter table prg_ar_report_colors add Text_Color_Code VARCHAR(max);

For MySql

alter table prg_ar_report_colors add Text_Color_Code longtext;

For Oracle

alter table prg_ar_report_colors add Text_Color_Code CLOB;

Using malloc for allocation of multi-dimensional arrays with different row lengths

2-D Array Dynamic Memory Allocation

int **a,i;

// for any number of rows & columns this will work
a = (int **)malloc(rows*sizeof(int *));
for(i=0;i<rows;i++)
    *(a+i) = (int *)malloc(cols*sizeof(int));

MySQL "Or" Condition

Your question is about the operator precedences in mysql and Alex has shown you how to "override" the precedence with parentheses.

But on a side note, if your column date is of the type Date you can use MySQL's date and time functions to fetch the records of the last seven days, like e.g.

SELECT
  *
FROM
  Drinks
WHERE
  email='$Email'
  AND date >= Now()-Interval 7 day

(or maybe Curdate() instead of Now())

How to select top n rows from a datatable/dataview in ASP.NET

You could modify the query. If you are using SQL Server at the back, you can use Select top n query for such need. The current implements fetch the whole data from database. Selecting only the required number of rows will give you a performance boost as well.

How can I run another application within a panel of my C# program?

  • Adding some solution in Answer..**

This code has helped me to dock some executable in windows form. like NotePad, Excel, word, Acrobat reader n many more...

But it wont work for some applications. As sometimes when you start process of some application.... wait for idle time... and the try to get its mainWindowHandle.... till the time the main window handle becomes null.....

so I have done one trick to solve this

If you get main window handle as null... then search all the runnning processes on sytem and find you process ... then get the main hadle of the process and the set panel as its parent.

        ProcessStartInfo info = new ProcessStartInfo();
        info.FileName = "xxxxxxxxxxxx.exe";
        info.Arguments = "yyyyyyyyyy";
        info.UseShellExecute = true;
        info.CreateNoWindow = true;
        info.WindowStyle = ProcessWindowStyle.Maximized;
        info.RedirectStandardInput = false;
        info.RedirectStandardOutput = false;
        info.RedirectStandardError = false;

        System.Diagnostics.Process p = System.Diagnostics.Process.Start(info); 

        p.WaitForInputIdle();
        Thread.Sleep(3000);

        Process[] p1 ;
    if(p.MainWindowHandle == null)
    {
        List<String> arrString = new List<String>();
        foreach (Process p1 in Process.GetProcesses())
        {
            // Console.WriteLine(p1.MainWindowHandle);
            arrString.Add(Convert.ToString(p1.ProcessName));
        }
        p1 = Process.GetProcessesByName("xxxxxxxxxxxx");
        //p.WaitForInputIdle();
        Thread.Sleep(5000);
      SetParent(p1[0].MainWindowHandle, this.panel2.Handle);

    }
    else
    {
     SetParent(p.MainWindowHandle, this.panel2.Handle);
     }

Install IPA with iTunes 12

In my case Drag & Drop didn't work.

  1. I had to first Sync iTunes with the iOS device (Sync button on the bottom right)
  2. I had to add the IPA file through iTunes menu bar: File -> Add to Library...
  3. I had to press the "Install" button for my app in the "Apps" screen
  4. I had to press the "Apply" button on the bottom right

View content of H2 or HSQLDB in-memory database

You can run H2 web server within your application that will access the same in-memory database. You can also access the H2 running in server mode using any generic JDBC client like SquirrelSQL.

UPDATE:

Server webServer = Server.createWebServer("-web,-webAllowOthers,true,-webPort,8082").start();
Server server = Server.createTcpServer("-tcp,-tcpAllowOthers,true,-tcpPort,9092").start();

Now you can connect to your database via jdbc:h2:mem:foo_db URL within the same process or browse the foo_db database using localhost:8082. Remember to close both servers. See also: H2 database in memory mode cannot be accessed by Console.

You can also use Spring:

<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg value="-tcp,-tcpAllowOthers,true,-tcpPort,9092"/>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg value="-web,-webAllowOthers,true,-webPort,8082"/>
</bean>

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" depends-on="h2Server">
    <property name="driverClass" value="org.h2.Driver"/>
    <property name="jdbcUrl" value="jdbc:h2:mem:foo_db"/>
</bean>

BTW you should only depend on assertions and not on manual peeking the database contents. Use this only for troubleshooting.

N.B. if you use Spring test framework you won't see changes made by a running transaction and this transaction will be rolled back immediately after the test.

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

The only way that cleanly solved this issue for me (.NET 4.6.1) was to not only add a Nuget reference to System.Net.Http V4.3.4 for the project that actually used System.Net.Http, but also to the startup project (a test project in my case).

(Which is strange, because the correct System.Net.Http.dll existed in the bin directory of the test project and the .config assemblyBingings looked OK, too.)

jQuery Mobile - back button

try

$(document).ready(function(){
    $('mybutton').click(function(){
        parent.history.back();
        return false;
    });
});

or

$(document).ready(function(){
    $('mybutton').click(function(){
        parent.history.back();

    });
});

Printing Exception Message in java

try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}

What are good examples of genetic algorithms/genetic programming solutions?

Its often difficult to get an exact color combination when you are planning to paint your house. Often, you have some color in mind, but it is not one of the colors, the vendor shows you.

Yesterday, my Prof. who is a GA researcher mentioned about a true story in Germany (sorry, I have no further references, yes, I can find it out if any one requests to). This guy (let's call him the color guy) used to go from door-door to help people to find the exact color code (in RGB) that would be the closet to what the customer had in mind. Here is how he would do it:

The color guy used to carry with him a software program which used GA. He used to start with 4 different colors- each coded as a coded Chromosome (whose decoded value would be a RGB value). The consumer picks 1 of the 4 colors (Which is the closest to which he/she has in mind). The program would then assign the maximum fitness to that individual and move onto the next generation using mutation/crossover. The above steps would be repeated till the consumer had found the exact color and then color guy used to tell him the RGB combination!

By assigning maximum fitness to the color closes to what the consumer have in mind, the color guy's program is increasing the chances to converge to the color, the consumer has in mind exactly. I found it pretty fun!

Now that I have got a -1, if you are planning for more -1's, pls. elucidate the reason for doing so!

DbEntityValidationException - How can I easily tell what caused the error?

To quickly find a meaningful error message by inspecting the error during debugging:

  • Add a quick watch for:

    ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
    
  • Drill down into EntityValidationErrors like this:

    (collection item e.g. [0]) > ValidationErrors > (collection item e.g. [0]) > ErrorMessage

CMake: How to build external projects and include their targets

Edit: CMake now has builtin support for this. See new answer.

You can also force the build of the dependent target in a secondary make process

See my answer on a related topic.

Querying data by joining two tables in two database on different servers

While I was having trouble join those two tables, I got away with doing exactly what I wanted by opening both remote databases at the same time. MySQL 5.6 (php 7.1) and the other MySQL 5.1 (php 5.6)

//Open a new connection to the MySQL server
$mysqli1 = new mysqli('server1','user1','password1','database1');
$mysqli2 = new mysqli('server2','user2','password2','database2');

//Output any connection error
if ($mysqli1->connect_error) {
    die('Error : ('. $mysqli1->connect_errno .') '. $mysqli1->connect_error);
} else { 
echo "DB1 open OK<br>";
}
if ($mysqli2->connect_error) {
    die('Error : ('. $mysqli2->connect_errno .') '. $mysqli2->connect_error);
} else { 
echo "DB2 open OK<br><br>";
}

If you get those two OKs on screen, then both databases are open and ready. Then you can proceed to do your querys.

$results = $mysqli1->query("SELECT * FROM video where video_id_old is NULL");
    while($row = $results->fetch_array()) {
        $theID = $row[0];
        echo "Original ID : ".$theID." <br>";
        $doInsert = $mysqli2->query("INSERT INTO video (...) VALUES (...)");
        $doGetVideoID = $mysqli2->query("SELECT video_id, time_stamp from video where user_id = '".$row[13]."' and time_stamp = ".$row[28]." ");
            while($row = $doGetVideoID->fetch_assoc()) {
                echo "New video_id : ".$row["video_id"]." user_id : ".$row["user_id"]." time_stamp : ".$row["time_stamp"]."<br>";
                $sql = "UPDATE video SET video_id_old = video_id, video_id = ".$row["video_id"]." where user_id = '".$row["user_id"]."' and video_id = ".$theID.";";
                $sql .= "UPDATE video_audio SET video_id = ".$row["video_id"]." where video_id = ".$theID.";";
                // Execute multi query if you want
                if (mysqli_multi_query($mysqli1, $sql)) {
                    // Query successful do whatever...
                }
            }
    }
// close connection 
$mysqli1->close();
$mysqli2->close();

I was trying to do some joins but since I got those two DBs open, then I can go back and forth doing querys by just changing the connection $mysqli1 or $mysqli2

It worked for me, I hope it helps... Cheers

how can the textbox width be reduced?

<input type='text' 
       name='t1'
       id='t1'
       maxlength=10
       placeholder='typing some text' >
<p></p>

This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character

How to check if a service is running via batch file and start it, if it is not running?

Related with the answer by @DanielSerrano, I've been recently bit by localization of the sc.exe command, namely in Spanish. My proposal is to pin-point the line and token which holds numerical service state and interpret it, which should be much more robust:

@echo off

rem TODO: change to the desired service name
set TARGET_SERVICE=w32time

set SERVICE_STATE=
rem Surgically target third line, as some locales (such as Spanish) translated the utility's output
for /F "skip=3 tokens=3" %%i in ('""%windir%\system32\sc.exe" query "%TARGET_SERVICE%" 2>nul"') do (
  if not defined SERVICE_STATE set SERVICE_STATE=%%i
)
rem Process result
if not defined SERVICE_STATE (
  echo ERROR: could not obtain service state!
) else (
  rem NOTE: values correspond to "SERVICE_STATUS.dwCurrentState"
  rem https://msdn.microsoft.com/en-us/library/windows/desktop/ms685996(v=vs.85).aspx
  if not %SERVICE_STATE%==4 (
    echo WARNING: service is not running
    rem TODO: perform desired operation
    rem net start "%TARGET_SERVICE%"
  ) else (
    echo INFORMATION: service is running
  )
)

Tested with:

  • Windows XP (32-bit) English
  • Windows 10 (32-bit) Spanish
  • Windows 10 (64-bit) English

How to set a value of a variable inside a template code?

An alternative way that doesn't require that you put everything in the "with" block is to create a custom tag that adds a new variable to the context. As in:

class SetVarNode(template.Node):
    def __init__(self, new_val, var_name):
        self.new_val = new_val
        self.var_name = var_name
    def render(self, context):
        context[self.var_name] = self.new_val
        return ''

import re
@register.tag
def setvar(parser,token):
    # This version uses a regular expression to parse tag contents.
    try:
        # Splitting by None == splitting by spaces.
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
    m = re.search(r'(.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name
    new_val, var_name = m.groups()
    if not (new_val[0] == new_val[-1] and new_val[0] in ('"', "'")):
        raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
    return SetVarNode(new_val[1:-1], var_name)

This will allow you to write something like this in your template:

{% setvar "a string" as new_template_var %}

Note that most of this was taken from here

How to start an application using android ADB tools?

Or, you could use this:

adb shell am start -n com.package.name/.ActivityName

Get index of clicked element in collection with jQuery

if you are using .bind(this), try this:

let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);

$(this.pagination).find("a").on('click', function(evt) {
        let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);

        this.goTo(index);
    }.bind(this))

I want to declare an empty array in java and then I want do update it but the code is not working

You can't set a number in an arbitrary place in the array without telling the array how big it needs to be. For your example: int[] array = new int[4];

Checking Bash exit status of several commands efficiently

For fish shell users who stumble on this thread.

Let foo be a function that does not "return" (echo) a value, but it sets the exit code as usual.
To avoid checking $status after calling the function, you can do:

foo; and echo success; or echo failure

And if it's too long to fit on one line:

foo; and begin
  echo success
end; or begin
  echo failure
end

C: What is the difference between ++i and i++?

They both increment the number. ++i is equivalent to i = i + 1.

i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluated, whereas i++ increments the number after the expression is evaluated.

Example:

int i = 1;
int x = i++; //x is 1, i is 2
int y = ++i; //y is 3, i is 3