Programs & Examples On #Git p4

The git p4 command provides a way to interact with p4 repositories using git.

When is null or undefined used in JavaScript?

I might be missing something, but afaik, you get undefined only

Update: Ok, I missed a lot, trying to complete:

You get undefined...

... when you try to access properties of an object that don't exist:

var a = {}
a.foo // undefined

... when you have declared a variable but not initialized it:

var a;
// a is undefined

... when you access a parameter for which no value was passed:

function foo (a, b) {
    // something
}

foo(42); // b inside foo is undefined

... when a function does not return a value:

function foo() {};
var a = foo(); // a is undefined

It might be that some built-in functions return null on some error, but if so, then it is documented. null is a concrete value in JavaScript, undefined is not.


Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable) to test whether a value is set or not (both, null and undefined evaluate to false).

Also different browsers seem to be returning these differently.

Please give a concrete example.

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

<div>
<div style="float:left; width:101px; height:auto;">
    <div style="width:200px; float:left;">
        LabelText
    </div>
    <div style="width:200px; float:left;">
        <input type="text" name="textfield" id="textfield" />
    </div>
</div>
    <div style="float:left; width:101px; height:auto;">
    <div style="width:200px; float:left;">
        LabelText
    </div>
    <div style="width:200px; float:left;">
        <input type="text" name="textfield" id="textfield" />
    </div>
</div>



</div>

How to print star pattern in JavaScript in a very simple manner?

<!DOCTYPE html>
<html>
    <head>
    <script>
        //Declare Variable
        var i,j;

        //First Way
        for(i = 5; i >= 0; i--){
            for(j = 0; j <= i; j++){
                document.write('*');
            }
            document.write('<br>');
        }
        //Second Way
        for(i = 5; i >= 0; i--){
            document.write('*'.repeat(i).concat('<br>'))
        }
    </script>
    </head>
    <body>
    </body>
</html>

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

I was facing the same problem and non of the above solutions helped me. In my Web Api 2 project, I had actually updated my database and had placed a unique constraint on an SQL table column. That was actually causing the problem. Simply Checking the the duplicate column values before inserting helped me fix the problem!

How to check if $_GET is empty?

Easy.

if (empty($_GET)) {
    // $_GET is empty
}

jQuery Datepicker close datepicker after selected date

This is my edited version : you just need to add an extra argument "autoClose".

example :

 $('input[name="fieldName"]').datepicker({ autoClose: true});

also you can specify a close callback if you want. :)

replace datepicker.js with this:

!function( $ ) {

// Picker object

var Datepicker = function(element, options , closeCallBack){
    this.element = $(element);
    this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
    this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
    this.closeCallback = closeCallBack || function(){};
    this.picker = $(DPGlobal.template)
                        .appendTo('body')
                        .on({
                            click: $.proxy(this.click, this)//,
                            //mousedown: $.proxy(this.mousedown, this)
                        });
    this.isInput = this.element.is('input');
    this.component = this.element.is('.date') ? this.element.find('.add-on') : false;

    if (this.isInput) {
        this.element.on({
            focus: $.proxy(this.show, this),
            //blur: $.proxy(this.hide, this),
            keyup: $.proxy(this.update, this)
        });
    } else {
        if (this.component){
            this.component.on('click', $.proxy(this.show, this));
        } else {
            this.element.on('click', $.proxy(this.show, this));
        }
    }

    this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
    if (typeof this.minViewMode === 'string') {
        switch (this.minViewMode) {
            case 'months':
                this.minViewMode = 1;
                break;
            case 'years':
                this.minViewMode = 2;
                break;
            default:
                this.minViewMode = 0;
                break;
        }
    }
    this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
    if (typeof this.viewMode === 'string') {
        switch (this.viewMode) {
            case 'months':
                this.viewMode = 1;
                break;
            case 'years':
                this.viewMode = 2;
                break;
            default:
                this.viewMode = 0;
                break;
        }
    }
    this.startViewMode = this.viewMode;
    this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
    this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
    this.onRender = options.onRender;
    this.fillDow();
    this.fillMonths();
    this.update();
    this.showMode();
};

Datepicker.prototype = {
    constructor: Datepicker,

    show: function(e) {
        this.picker.show();
        this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
        this.place();
        $(window).on('resize', $.proxy(this.place, this));
        if (e ) {
            e.stopPropagation();
            e.preventDefault();
        }
        if (!this.isInput) {
        }
        var that = this;
        $(document).on('mousedown', function(ev){
            if ($(ev.target).closest('.datepicker').length == 0) {
                that.hide();
            }
        });
        this.element.trigger({
            type: 'show',
            date: this.date
        });
    },

    hide: function(){
        this.picker.hide();
        $(window).off('resize', this.place);
        this.viewMode = this.startViewMode;
        this.showMode();
        if (!this.isInput) {
            $(document).off('mousedown', this.hide);
        }
        //this.set();
        this.element.trigger({
            type: 'hide',
            date: this.date
        });
    },

    set: function() {
        var formated = DPGlobal.formatDate(this.date, this.format);
        if (!this.isInput) {
            if (this.component){
                this.element.find('input').prop('value', formated);
            }
            this.element.data('date', formated);
        } else {
            this.element.prop('value', formated);
        }
    },

    setValue: function(newDate) {
        if (typeof newDate === 'string') {
            this.date = DPGlobal.parseDate(newDate, this.format);
        } else {
            this.date = new Date(newDate);
        }
        this.set();
        this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
        this.fill();
    },

    place: function(){
        var offset = this.component ? this.component.offset() : this.element.offset();
        this.picker.css({
            top: offset.top + this.height,
            left: offset.left
        });
    },

    update: function(newDate){
        this.date = DPGlobal.parseDate(
            typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
            this.format
        );
        this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
        this.fill();
    },

    fillDow: function(){
        var dowCnt = this.weekStart;
        var html = '<tr>';
        while (dowCnt < this.weekStart + 7) {
            html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
        }
        html += '</tr>';
        this.picker.find('.datepicker-days thead').append(html);
    },

    fillMonths: function(){
        var html = '';
        var i = 0
        while (i < 12) {
            html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
        }
        this.picker.find('.datepicker-months td').append(html);
    },

    fill: function() {
        var d = new Date(this.viewDate),
            year = d.getFullYear(),
            month = d.getMonth(),
            currentDate = this.date.valueOf();
        this.picker.find('.datepicker-days th:eq(1)')
                    .text(DPGlobal.dates.months[month]+' '+year);
        var prevMonth = new Date(year, month-1, 28,0,0,0,0),
            day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
        prevMonth.setDate(day);
        prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
        var nextMonth = new Date(prevMonth);
        nextMonth.setDate(nextMonth.getDate() + 42);
        nextMonth = nextMonth.valueOf();
        var html = [];
        var clsName,
            prevY,
            prevM;
        while(prevMonth.valueOf() < nextMonth) {zs
            if (prevMonth.getDay() === this.weekStart) {
                html.push('<tr>');
            }
            clsName = this.onRender(prevMonth);
            prevY = prevMonth.getFullYear();
            prevM = prevMonth.getMonth();
            if ((prevM < month &&  prevY === year) ||  prevY < year) {
                clsName += ' old';
            } else if ((prevM > month && prevY === year) || prevY > year) {
                clsName += ' new';
            }
            if (prevMonth.valueOf() === currentDate) {
                clsName += ' active';
            }
            html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
            if (prevMonth.getDay() === this.weekEnd) {
                html.push('</tr>');
            }
            prevMonth.setDate(prevMonth.getDate()+1);
        }
        this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
        var currentYear = this.date.getFullYear();

        var months = this.picker.find('.datepicker-months')
                    .find('th:eq(1)')
                        .text(year)
                        .end()
                    .find('span').removeClass('active');
        if (currentYear === year) {
            months.eq(this.date.getMonth()).addClass('active');
        }

        html = '';
        year = parseInt(year/10, 10) * 10;
        var yearCont = this.picker.find('.datepicker-years')
                            .find('th:eq(1)')
                                .text(year + '-' + (year + 9))
                                .end()
                            .find('td');
        year -= 1;
        for (var i = -1; i < 11; i++) {
            html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
            year += 1;
        }
        yearCont.html(html);
    },

    click: function(e) {
        e.stopPropagation();
        e.preventDefault();
        var target = $(e.target).closest('span, td, th');
        if (target.length === 1) {
            switch(target[0].nodeName.toLowerCase()) {
                case 'th':
                    switch(target[0].className) {
                        case 'switch':
                            this.showMode(1);
                            break;
                        case 'prev':
                        case 'next':
                            this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
                                this.viewDate,
                                this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) + 
                                DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
                            );
                            this.fill();
                            this.set();
                            break;
                    }
                    break;
                case 'span':
                    if (target.is('.month')) {
                        var month = target.parent().find('span').index(target);
                        this.viewDate.setMonth(month);
                    } else {
                        var year = parseInt(target.text(), 10)||0;
                        this.viewDate.setFullYear(year);
                    }
                    if (this.viewMode !== 0) {
                        this.date = new Date(this.viewDate);
                        this.element.trigger({
                            type: 'changeDate',
                            date: this.date,
                            viewMode: DPGlobal.modes[this.viewMode].clsName
                        });
                    }
                    this.showMode(-1);
                    this.fill();
                    this.set();
                    break;
                case 'td':
                    if (target.is('.day') && !target.is('.disabled')){
                        var day = parseInt(target.text(), 10)||1;
                        var month = this.viewDate.getMonth();
                        if (target.is('.old')) {
                            month -= 1;
                        } else if (target.is('.new')) {
                            month += 1;
                        }
                        var year = this.viewDate.getFullYear();
                        this.date = new Date(year, month, day,0,0,0,0);
                        this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
                        this.fill();
                        this.set();
                        this.element.trigger({
                            type: 'changeDate',
                            date: this.date,
                            viewMode: DPGlobal.modes[this.viewMode].clsName
                        });
                        if(this.autoClose === true){
                            this.hide();
                            this.closeCallback();
                        }

                    }
                    break;
            }
        }
    },

    mousedown: function(e){
        e.stopPropagation();
        e.preventDefault();
    },

    showMode: function(dir) {
        if (dir) {
            this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
        }
        this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
    }
};

$.fn.datepicker = function ( option, val ) {
    return this.each(function () {
        var $this = $(this);
        var datePicker = $this.data('datepicker');
        var options = typeof option === 'object' && option;
        if (!datePicker) {
            if (typeof val === 'function')
                $this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
            else{
                $this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
            }
        }
        if (typeof option === 'string') datePicker[option](val);

    });
};

$.fn.datepicker.defaults = {
    onRender: function(date) {
        return '';
    }
};
$.fn.datepicker.Constructor = Datepicker;

var DPGlobal = {
    modes: [
        {
            clsName: 'days',
            navFnc: 'Month',
            navStep: 1
        },
        {
            clsName: 'months',
            navFnc: 'FullYear',
            navStep: 1
        },
        {
            clsName: 'years',
            navFnc: 'FullYear',
            navStep: 10
    }],
    dates:{
        days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
                    daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
                    daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
                    months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
                    monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
                    today: "Aujourd'hui",
                    clear: "Effacer",
                    weekStart: 1,
                    format: "dd/mm/yyyy"
    },
    isLeapYear: function (year) {
        return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
    },
    getDaysInMonth: function (year, month) {
        return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
    },
    parseFormat: function(format){
        var separator = format.match(/[.\/\-\s].*?/),
            parts = format.split(/\W+/);
        if (!separator || !parts || parts.length === 0){
            throw new Error("Invalid date format.");
        }
        return {separator: separator, parts: parts};
    },
    parseDate: function(date, format) {
        var parts = date.split(format.separator),
            date = new Date(),
            val;
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        if (parts.length === format.parts.length) {
            var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
            for (var i=0, cnt = format.parts.length; i < cnt; i++) {
                val = parseInt(parts[i], 10)||1;
                switch(format.parts[i]) {
                    case 'dd':
                    case 'd':
                        day = val;
                        date.setDate(val);
                        break;
                    case 'mm':
                    case 'm':
                        month = val - 1;
                        date.setMonth(val - 1);
                        break;
                    case 'yy':
                        year = 2000 + val;
                        date.setFullYear(2000 + val);
                        break;
                    case 'yyyy':
                        year = val;
                        date.setFullYear(val);
                        break;
                }
            }
            date = new Date(year, month, day, 0 ,0 ,0);
        }
        return date;
    },
    formatDate: function(date, format){
        var val = {
            d: date.getDate(),
            m: date.getMonth() + 1,
            yy: date.getFullYear().toString().substring(2),
            yyyy: date.getFullYear()
        };
        val.dd = (val.d < 10 ? '0' : '') + val.d;
        val.mm = (val.m < 10 ? '0' : '') + val.m;
        var date = [];
        for (var i=0, cnt = format.parts.length; i < cnt; i++) {
            date.push(val[format.parts[i]]);
        }
        return date.join(format.separator);
    },
    headTemplate: '<thead>'+
                        '<tr>'+
                            '<th class="prev">&lsaquo;</th>'+
                            '<th colspan="5" class="switch"></th>'+
                            '<th class="next">&rsaquo;</th>'+
                        '</tr>'+
                    '</thead>',
    contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
                        '<div class="datepicker-days">'+
                            '<table class=" table-condensed">'+
                                DPGlobal.headTemplate+
                                '<tbody></tbody>'+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-months">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-years">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                            '</table>'+
                        '</div>'+
                    '</div>';

}( window.jQuery );

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

A variable modified inside a while loop is not remembered

I use stderr to store within a loop, and read from it outside. Here var i is initially set and read inside the loop as 1.

# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value

f=/tmp/file1
g=/tmp/file2
i=1
cat $f $g | \
while read -r s;
do
  echo $s > /dev/null;  # some work
  echo $i > 2
  let i++
done;
read -r i < 2
echo $i

Or use the heredoc method to reduce the amount of code in a subshell. Note the iterative i value can be read outside the while loop.

i=1
while read -r s;
do
  echo $s > /dev/null
  let i++
done <<EOT
$(cat $f $g)
EOT
let i--
echo $i

Best way to restrict a text field to numbers only?

This is my plugin for that case:

 (function( $ ) {
    $.fn.numbers = function(options) {
      $(this).keypress(function(evt){
          var setting = $.extend( {
                'digits' : 8
              }, options);
          if($(this).val().length > (setting.digits - 1) && evt.which != 8){
              evt.preventDefault(); 
          }
          else{
              if(evt.which < 48 || evt.which > 57){
                if(evt.keyCode != 8){
                    evt.preventDefault();  
                }
              }
          }
      });
    };
  })( jQuery );

Use:

 $('#limin').numbers({digits:3});
 $('#limax').numbers();

an htop-like tool to display disk activity in linux

nmon shows a nice display of disk activity per device. It is available for linux.

? Disk I/O ?????(/proc/diskstats)????????all data is Kbytes per second???????????????????????????????????????????????????????????????
?DiskName Busy  Read WriteKB|0          |25         |50          |75       100|                                                      ?
?sda        0%    0.0  127.9|>                                                |                                                      ?
?sda1       1%    0.0  127.9|>                                                |                                                      ?
?sda2       0%    0.0    0.0|>                                                |                                                      ?
?sda5       0%    0.0    0.0|>                                                |                                                      ?
?sdb       61%  385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                 |                                                      ?
?sdb1      61%  385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                 |                                                      ?
?sdc       52%  353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR   >                  |                                                      ?
?sdc1      53%  353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR   >                  |                                                      ?
?sdd       56%  359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW>                    |                                                      ?
?sdd1      56%  359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW>                    |                                                      ?
?sde       57%  371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                   |                                                      ?
?sde1      57%  371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                   |                                                      ?
?sdf       53%  371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR    >                 |                                                      ?
?sdf1      53%  371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR    >                 |                                                      ?
?md0        0% 1726.0 2093.6|>disk busy not available                         |                                                      ?
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

Generating a Random Number between 1 and 10 Java

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.

Generally speaking, if you need to generate numbers from min to max (including both), you write

random.nextInt(max - min + 1) + min

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

Set default_url_options to use your action_mailer.default_url_options.

In each of your environment files (e.g. development.rb, production.rb, etc.) you can specify the default_url_options to use for action_mailer:

config.action_mailer.default_url_options = { host: 'lvh.me', port: '3000' }

However, these are not set for MyApp:Application.default_url_options:

$ MyApp::Application.config.action_mailer.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}

$ MyApp::Application.default_url_options
#=> {}

That's why you are getting that error in anything outside of ActionMailer.

You can set your Application's default_url_options to use what you defined for action_mailer in the appropriate environment file (development.rb, production.rb, etc.).

To keep things as DRY as possible, do this in your config/environment.rb file so you only have to do this once:

# Initialize the rails application
MyApp::Application.initialize!

# Set the default host and port to be the same as Action Mailer.
MyApp::Application.default_url_options = MyApp::Application.config.action_mailer.default_url_options

Now when you boot up your app, your entire Application's default_url_options will match your action_mailer.default_url_options:

$ MyApp::Application.config.action_mailer.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}

$ MyApp::Application.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}

Hat tip to @pduersteler for leading me down this path.

When to use Comparable and Comparator

Comparator does everything that comparable does, plus more.

| | Comparable | Comparator ._______________________________________________________________________________ Is used to allow Collections.sort to work | yes | yes Can compare multiple fields | yes | yes Lives inside the class you’re comparing and serves | | as a “default” way to compare | yes | yes Can live outside the class you’re comparing | no | yes Can have multiple instances with different method names | no | yes Input arguments can be a list of | just Object| Any type Can use enums | no | yes

I found the best approach to use comparators as anonymous classes as follows:

private static void sortAccountsByPriority(List<AccountRecord> accounts) {
    Collections.sort(accounts, new Comparator<AccountRecord>() {

        @Override
        public int compare(AccountRecord a1, AccountRecord a2) {
            return a1.getRank().compareTo(a2.getRank());
        }
    });
}

You can create multiple versions of such methods right inside the class you’re planning to sort. So you can have:

  • sortAccountsByPriority
  • sortAccountsByType
  • sortAccountsByPriorityAndType

    etc...

Now, you can use these sort methods anywhere and get code reuse. This gives me everything a comparable would, plus more ... so I don’t see any reason to use comparable at all.

How to install mongoDB on windows?

Mongo Installation Process in Windows

Are you ready for the installation … and use … Technically, it’s not an installation it’s just Downloading…

I. Download the zip file http://www.mongodb.org/downloads

II. Extract it and copy the files into your desired location.

III. Start the DB engine.

IV. Test the installation and use it.

That's it! So simple, right? Ok let’s start


1. Download the zip file

  1. Go to http://www.mongodb.org/downloads

  2. You will see a screen like this: The mongo download page I am using a windows 7 32 bit machine - that’s why I downloaded the package marked in red.

  3. Click download (It only takes a few seconds).
    Wow... I got that downloaded. It was a zipped file called mongodb-win32-i386-2.4.4.zip (The name of the folder will change according to the version you download, here I got version 2.4.4).

OK all set.


2. Extract

  1. Extract the zip
  2. Copy the files into a desired location in your machine.
    • I am going to copy the extracted files to my D drive, since I don’t have many files there.
    • Alright then where are you planning to paste the mongo files? In C: or in your Desktop itself?
    • Ok, no matter where you paste... In the snap shot below, you can see that I have navigated to the bin folder inside the Mongo folder. I count fifteen files inside bin. What about you?

The path to the bin folder

Finished! That’s all

What we have to do next?


3. Start the DB engine

Let’s go and start using our mongo db...

  1. Open up a command prompt, then navigate to bin in the mongo folder Navigating to mongo's bin folder

  2. Type mongo.exe (which is the command used to start mongo Db Power shell). Then see the below response.. Executing mongo.exe That was an awesome exception J LOL … What is that?

    Couldn’t connect to server.

    Why did the exception happen? I have no idea... Did I create a server in between?

    No.

    Right, then how come it connected to a server in between? Silly Machine …Jz.

    I got it! Like all other DBs - we have to start the DB engine before we use it.

    So, how can we start it?

  3. We have to start the mongo db by using the command mongod. Execute this from the bin folder of mongo.

    Let’s see what had happened.

    error message

    Again a wonderfully formatted exception J we got right? Did you notice what I have highlighted on top? Yeah it is the mongod command. The second one is the exception asking us to create a folder called data. And, inside the data folder, a folder called db.

    So we have to create these data\db folders.

    The next question is where to create these folders?

  4. We have to create the data\db folders in the C drive of our BOX in which we are installing mongo. Let’s go and create the folder structure in C drive.

    A question arises here: "Is it mandatory to create the data\db directories inside C?" Nooo, not really. Mongo looks in C by default for this folder, but you can create them wherever you want. However, if it's not in C, you have to tell mongo where it is.

    In other words, if you don't want the mongo databases to be on C:\, you have to set the db path for mongo.exe.

    Optional

    • Ok, I will create those folders in some other location besides C for better understanding of this option. I will create then in the D drive root, with the help of cmd.

      Why? Because it’s an opportunity for us to remember the old dos commands...

      md data

    • The next step is to set the Db path to mongo.exe.

      Navigate back to bin, and enter the command, mongod.exe --dbpath d:\data.

      I got the response below:

      --dbpath

      I Hope everything went well... Because I didn’t see any ERROR *** in the console J.

    Next, we can go and start the db using the command start mongo.exe

    start mongo.exe

    I didn't see any error or warning messages. But, we have to supply a command to make sure mongo is up and running, i.e. mongod will get a response:

    mongodb response

Hope everything went well.


4. Test the Mongo DB installation

Now we have to see our DB right? Yea very much, Otherwise how will we know it’s running?

For testing purpose MONGO has got a DB called test by default. Lets go query that.

But how without any management studios? Unlike SQL, we have to depend on the command prompt. Yes exactly the same command prompt… our good old command prompt… Heiiiii.. Don’t get afraid yes it’s our old command prompt only. Ok let’s go and see how we are going to use it…

Ohhh Nooo… don’t close the above Command prompt, leave it as it is…

  1. Open a new cmd window.

  2. Navigate to Bin as usual we do…

    I am sure you people may be remembering the old C programming which we have done on our college day’s right?

  3. In the command prompt, execute the command mongo or mongo.exe again and see what happens.

    You will get a screen as shown below:

    startup warning

  4. I mentioned before that Mongo has got a test db by default called test, try inserting a record into it.

    The next question here is "How will we insert?" Does mongo have SQL commands? No, mongo has got only commands to help with.

    The basic command to insert is
    db.test.save( { KodothTestField: ‘My name is Kodoth’ } )

    Where test is the DB and .save is the insert command. KodothTestField is the column or field name, and My name is Kodoth is the value.

  5. Before talking more let’s check whether it’s stored or not by performing another command: db.test.find()

    Mongo command to search for a document, similar to SELECT in SQL.

    Our Data got successfully inserted … Hurrayyyyyy..

    I know that you are thinking about the number which is displayed with every record right called ObjectId. It’s like a unique id field in SQL that auto-increments and all. Have a closer look you can see that the Object Id ends with 92, so it’s different for each and every record.

    At last we are successful in installing and verifying the MONGO right. Let’s have a party... So do you agree now MONGO is as Sweet as MANGO?

Also we have 3rd party tools to explore the MONGO. One is called MONGO VUE. Using this tool we can perform operations against the mongo DB like we use Management studio for SQL Server.

Can you just imagine an SQL server or Oracle Db with entirely different rows in same table? Is it possible in our relational DB table? This is how mongo works. I will show you how we can do that…


First I will show you how the data will look in a relational DB.

For example consider an Employee table and a Student table in relational way. The schemas would be entirely different right? Yes exactly…

results view

Let us now see how it will look in Mongo DB. The above two tables are combined into single Collection in Mongo…

MongoVUE

This is how Collections are stored in Mongo. I think now you can feel the difference really right? Every thing came under a single umbrella. This is not the right way but I just wanted to show you all how this happens that’s why I combined 2 entirely different tables in to one single Collection.

If you want to try out you can use below test scripts

*********************** 
TEST INSERT SCRIPT

*********EMPLOYEE****** 
db.test.save( { EmployeId: "1", EmployeFirstName: "Kodoth", EmployeLastName:"KodothLast", EmployeAge:"14" } )  
db.test.save( { EmployeId: "2", EmployeFirstName: "Kodoth 2", EmployeLastName:"Kodoth Last2", EmployeAge:"14" } )  
db.test.save( { EmployeId: "3", EmployeFirstName: "Kodoth 3", EmployeLastName:"Kodoth Last3", EmployeAge:"14" } ) 

******STUDENT****** 
db.test.save( { StudentId: "1", StudentName: "StudentName", StudentMark:"25" } )  
db.test.save( { StudentId: "2", StudentName: "StudentName 2", StudentMark:"26" } )  
db.test.save( {StudentId: "3", StudentName: "StudentName 3", StudentMark:"27"} )
************************

Thanks

Adding delay between execution of two following lines

You can use gcd to do this without having to create another method

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
  NSLog(@"Do some work");
});

You should still ask yourself "do I really need to add a delay" as it can often complicate code and cause race conditions

How to log as much information as possible for a Java Exception?

You can also use Apache's ExceptionUtils.

Example:

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;


public class Test {

    static Logger logger = Logger.getLogger(Test.class);

    public static void main(String[] args) {

        try{
            String[] avengers = null;
            System.out.println("Size: "+avengers.length);
        } catch (NullPointerException e){
            logger.info(ExceptionUtils.getFullStackTrace(e));
        }
    }

}

Console output:

java.lang.NullPointerException
    at com.aimlessfist.avengers.ironman.Test.main(Test.java:11)

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

Disable LESS-CSS Overwriting calc()

Example for escaped string with variable:

@some-variable-height: 10px;

...

div {
    height: ~"calc(100vh - "@some-variable-height~")";
}

compiles to

div {
    height: calc(100vh - 10px );
}

How to run stored procedures in Entity Framework Core?

To execute the stored procedures, use FromSql method which executes RAW SQL queries

e.g.

    var products= context.Products
        .FromSql("EXECUTE dbo.GetProducts")
        .ToList();

To use with parameters

    var productCategory= "Electronics";

    var product = context.Products
        .FromSql("EXECUTE dbo.GetProductByCategory {0}", productCategory)
        .ToList();

or

    var productCategory= new SqlParameter("productCategory", "Electronics");

    var product = context.Product
        .FromSql("EXECUTE dbo.GetProductByName  @productCategory", productCategory)
        .ToList();

There are certain limitations to execute RAW SQL queries or stored procedures. You can’t use it for INSERT/UPDATE/DELETE. if you want to execute INSERT, UPDATE, DELETE queries, use the ExecuteSqlCommand

    var categoryName = "Electronics";
    dataContext.Database
               .ExecuteSqlCommand("dbo.InsertCategory @p0", categoryName);

Remove characters except digits from string using Python?

You can easily do it using Regex

>>> import re
>>> re.sub("\D","","£70,000")
70000

How to check if bootstrap modal is open, so I can use jquery validate?

You can use

$('#myModal').hasClass('in');

Bootstrap adds the in class when the modal is open and removes it when closed

Display Two <div>s Side-by-Side

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}

How does a ArrayList's contains() method evaluate objects?

Shortcut from JavaDoc:

boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))

How do you find the sum of all the numbers in an array in Java?

 public class Num1
 {
     public static void main ()
     {
          //Declaration and Initialization
          int a[]={10,20,30,40,50}

          //To find the sum of array elements
          int sum=0;
          for(int i=0;i<a.length;i++)
          {
              sum=sum+i;
          }

          //To display the sum
          System.out.println("The sum is :"+sum);

     }
  } 

Python Matplotlib Y-Axis ticks on Right Side of Plot

joaquin's answer works, but has the side effect of removing ticks from the left side of the axes. To fix this, follow up tick_right() with a call to set_ticks_position('both'). A revised example:

from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')
plt.plot([2,3,4,5])
plt.show()

The result is a plot with ticks on both sides, but tick labels on the right.

enter image description here

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

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

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

jQuery get text as number

Always use parseInt with a radix (base) as the second parameter, or you will get unexpected results:

var number = parseInt($(this).find('.number').text(), 10);

A popular variation however is to use + as a unitary operator. This will always convert with base 10 and never throw an error, just return zero NaN which can be tested with the function isNaN() if it's an invalid number:

var number = +($(this).find('.number').text());

python: how to check if a line is an empty line

I use the following code to test the empty line with or without white spaces.

if len(line.strip()) == 0 :
    # do something with empty line

"unadd" a file to svn before commit

Full process (Unix svn package):

Check files are not in SVN:

> svn st -u folder 
? folder

Add all (including ignored files):

> svn add folder
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt
A   folder/folderToIgnore
A   folder/folderToIgnore/fileToIgnore1.txt
A   fileToIgnore2.txt

Remove "Add" Flag to All * Ignore * files:

> cd folder

> svn revert --recursive folderToIgnore
Reverted 'folderToIgnore'
Reverted 'folderToIgnore/fileToIgnore1.txt'


> svn revert fileToIgnore2.txt
Reverted 'fileToIgnore2.txt'

Edit svn ignore on folder

svn propedit svn:ignore .

Add two singles lines with just the following:

folderToIgnore
fileToIgnore2.txt

Check which files will be upload and commit:

> cd ..

> svn st -u
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt


> svn ci -m "Commit message here"

Ideal way to cancel an executing AsyncTask

Simple: don't use an AsyncTask. AsyncTask is designed for short operations that end quickly (tens of seconds) and therefore do not need to be canceled. "Audio file playback" does not qualify. You don't even need a background thread for ordinary audio file playback.

how to open a page in new tab on button click in asp.net?

Use JavaScript for the main form / Button click event. An example is:

Context.Response.Write("<script language='javascript'>window.open('AccountsStmt.aspx?showledger=" & sledgerGrp & "','_newtab');</script>")

How to list records with date from the last 10 days?

Just generalising the query if you want to work with any given date instead of current date:

SELECT Table.date
  FROM Table 
  WHERE Table.date > '2020-01-01'::date - interval '10 day'

Sending event when AngularJS finished loading

If you are using Angular UI Router, you can listen for the $viewContentLoadedevent.

"$viewContentLoaded - fired once the view is loaded, after the DOM is rendered. The '$scope' of the view emits the event." - Link

$scope.$on('$viewContentLoaded', 
function(event){ ... });

Changing the JFrame title

these methods can help setTitle("your new title"); or super("your new title");

How to switch text case in visual studio code

To have in Visual Studio Code what you can do in Sublime Text ( CTRL+K CTRL+U and CTRL+K CTRL+L ) you could do this:

  • Open "Keyboard Shortcuts" with click on "File -> Preferences -> Keyboard Shortcuts"
  • Click on "keybindings.json" link which appears under "Search keybindings" field
  • Between the [] brackets add:

    {
        "key": "ctrl+k ctrl+u",
        "command": "editor.action.transformToUppercase",
        "when": "editorTextFocus"
    },
    {
        "key": "ctrl+k ctrl+l",
        "command": "editor.action.transformToLowercase",
        "when": "editorTextFocus"
    }
    
  • Save and close "keybindings.json"


Another way:
Microsoft released "Sublime Text Keymap and Settings Importer", an extension which imports keybindings and settings from Sublime Text to VS Code. - https://marketplace.visualstudio.com/items?itemName=ms-vscode.sublime-keybindings

What is the best way to generate a unique and short file name in Java

This also works

String logFileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());

logFileName = "loggerFile_" + logFileName;

Python - add PYTHONPATH during command line module run

If you are running the command from a POSIX-compliant shell, like bash, you can set the environment variable like this:

PYTHONPATH="/path/to" python somescript.py somecommand

If it's all on one line, the PYTHONPATH environment value applies only to that one command.

$ echo $PYTHONPATH

$ python -c 'import sys;print("/tmp/pydir" in sys.path)'
False
$ PYTHONPATH=/tmp/pydir python -c 'import sys;print("/tmp/pydir" in sys.path)'
True
$ echo $PYTHONPATH

Best way to overlay an ESRI shapefile on google maps?

I like using (open source and gui friendly) Quantum GIS to convert the shapefile to kml.

Google Maps API supports only a subset of the KML standard. One limitation is file size.

To reduce your file size, you can Quantum GIS's "simplify geometries" function. This "smooths" polygons.

Then you can select your layer and do a "save as kml" on it.

If you need to process a bunch of files, the process can be batched with Quantum GIS's ogr2ogr command from osgeo4w shell.

Finally, I recommend zipping your kml (with your favorite compression program) for reduced file size and saving it as kmz.

Finding duplicate rows in SQL Server

select a.orgName,b.duplicate, a.id
from organizations a
inner join (
    SELECT orgName, COUNT(*) AS duplicate
    FROM organizations
    GROUP BY orgName
    HAVING COUNT(*) > 1
) b on o.orgName = oc.orgName
group by a.orgName,a.id

how to display full stored procedure code?

SELECT prosrc FROM pg_proc WHERE proname = 'function_name';

This tells the function handler how to invoke the function. It might be the actual source code of the function for interpreted languages, a link symbol, a file name, or just about anything else, depending on the implementation language/call convention

How to compare dates in c#

If you have date in DateTime variable then its a DateTime object and doesn't contain any format. Formatted date are expressed as string when you call DateTime.ToString method and provide format in it.

Lets say you have two DateTime variable, you can use the compare method for comparision,

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Code snippet taken from msdn.

Which HTML elements can receive focus?

Maybe this one can help:

_x000D_
_x000D_
function focus(el){_x000D_
 el.focus();_x000D_
 return el==document.activeElement;_x000D_
}
_x000D_
_x000D_
_x000D_

return value: true = success, false = failed

Reff: https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus

Naming Conventions: What to name a boolean variable?

isBeforeTheLastItem

isInFrontOfTheLastItem

isTowardsTheFrontOfTheList

Maybe too wordy but they may help give you ideas.

Failed to load resource: net::ERR_INSECURE_RESPONSE

Try this code to watch for, and report, a possible net::ERR_INSECURE_RESPONSE

I was having this issue as well, using a self-signed certificate, which I have chosen not to save into the Chrome Settings. After accessing the https domain and accepting the certificate, the ajax call works fine. But once that acceptance has timed-out or before it has first been accepted, the jQuery.ajax() call fails silently: the timeout parameter does not seem help and the error() function never gets called.

As such, my code never receives a success() or error() call and therefore hangs. I believe this is a bug in jquery's handling of this error. My solution is to force the error() call after a specified timeout.

This code does assume a jquery ajax call of the form jQuery.ajax({url: required, success: optional, error: optional, others_ajax_params: optional}).

Note: You will likely want to change the function within the setTimeout to integrate best with your UI: rather than calling alert().

const MS_FOR_HTTPS_FAILURE = 5000;
$.orig_ajax = $.ajax;
$.ajax = function(params)
{
  var complete = false;
  var success = params.success;
  var error = params.error;
  params.success = function() {
    if(!complete) {
      complete = true;
      if(success) success.apply(this,arguments);
    }
  }
  params.error = function() {
    if(!complete) {
      complete = true;
      if(error) error.apply(this,arguments);
    }
  }
  setTimeout(function() {
    if(!complete) {
      complete = true;
      alert("Please ensure your self-signed HTTPS certificate has been accepted. "
        + params.url);
      if(params.error)
        params.error( {},
          "Connection failure",
          "Timed out while waiting to connect to remote resource. " +
          "Possibly could not authenticate HTTPS certificate." );
    }
  }, MS_FOR_HTTPS_FAILURE);

  $.orig_ajax(params);
}

how to access master page control from content page

If you are trying to access an html element: this is an HTML Anchor...

My nav bar has items that are not list items (<li>) but rather html anchors (<a>)

See below: (This is the site master)

<nav class="mdl-navigation">
    <a class="mdl-navigation__link" href="" runat="server" id="liHome">Home</a>
    <a class="mdl-navigation__link" href="" runat="server" id="liDashboard">Dashboard</a>
</nav>

Now in your code behind for another page, for mine, it's the login page...

On PageLoad() define this:

HtmlAnchor lblMasterStatus = (HtmlAnchor)Master.FindControl("liHome");
lblMasterStatus.Visible =false;

HtmlAnchor lblMasterStatus1 = (HtmlAnchor)Master.FindControl("liDashboard");
lblMasterStatus1.Visible = false;

Now we have accessed the site masters controls, and have made them invisible on the login page.

android button selector

Best way to implement the selector is by using the xml instead of using programatic way as its more easy to implemnt with xml.

    <?xml version="1.0" encoding="utf-8"?>    
<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/button_bg_selected" android:state_selected="true"></item>
        <item android:drawable="@drawable/button_bg_pressed" android:state_pressed="true"></item>
        <item android:drawable="@drawable/button_bg_normal"></item>

    </selector>

For more information i implemented using this link http://www.blazin.in/2016/03/how-to-use-selectors-for-botton.html

Array of Matrices in MATLAB

if you know what unknown is,

you can do something like

myArray = zeros(2,2);
for i: 1:unknown
  myArray(:,i) = zeros(x,y);
end

However it has been a while since I last used matlab. so this page might shed some light on the matter :

http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/matlab_prog/f1-86528.html

How can I detect if a selector returns null?

I like to do something like this:

$.fn.exists = function(){
    return this.length > 0 ? this : false;
}

So then you can do something like this:

var firstExistingElement = 
    $('#iDontExist').exists() ||      //<-returns false;
    $('#iExist').exists() ||          //<-gets assigned to the variable 
    $('#iExistAsWell').exists();      //<-never runs

firstExistingElement.doSomething();   //<-executes on #iExist

http://jsfiddle.net/vhbSG/

Binning column with python pandas

Using numba module for speed up.

On big datasets (500k >) pd.cut can be quite slow for binning data.

I wrote my own function in numba with just in time compilation, which is roughly 16x faster:

from numba import njit

@njit
def cut(arr):
    bins = np.empty(arr.shape[0])
    for idx, x in enumerate(arr):
        if (x >= 0) & (x < 1):
            bins[idx] = 1
        elif (x >= 1) & (x < 5):
            bins[idx] = 2
        elif (x >= 5) & (x < 10):
            bins[idx] = 3
        elif (x >= 10) & (x < 25):
            bins[idx] = 4
        elif (x >= 25) & (x < 50):
            bins[idx] = 5
        elif (x >= 50) & (x < 100):
            bins[idx] = 6
        else:
            bins[idx] = 7

    return bins
cut(df['percentage'].to_numpy())

# array([5., 5., 7., 5.])

Optional: you can also map it to bins as strings:

a = cut(df['percentage'].to_numpy())

conversion_dict = {1: 'bin1',
                   2: 'bin2',
                   3: 'bin3',
                   4: 'bin4',
                   5: 'bin5',
                   6: 'bin6',
                   7: 'bin7'}

bins = list(map(conversion_dict.get, a))

# ['bin5', 'bin5', 'bin7', 'bin5']

Speed comparison:

# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)

dfbig.shape

# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())

# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)

# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

How to parse/read a YAML file into a Python object?

Here is one way to test which YAML implementation the user has selected on the virtualenv (or the system) and then define load_yaml_file appropriately:

load_yaml_file = None

if not load_yaml_file:
    try:
        import yaml
        load_yaml_file = lambda fn: yaml.load(open(fn))
    except:
        pass

if not load_yaml_file:
    import commands, json
    if commands.getstatusoutput('ruby --version')[0] == 0:
        def load_yaml_file(fn):
            ruby = "puts YAML.load_file('%s').to_json" % fn
            j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
            return json.loads(j[1])

if not load_yaml_file:
    import os, sys
    print """
ERROR: %s requires ruby or python-yaml  to be installed.

apt-get install ruby

  OR

apt-get install python-yaml

  OR

Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
   apt-get install epel-release
   apt-get install python-pip
   apt-get install libyaml-cpp-dev
   python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
  https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
  Pip might not play by all the rules.
  Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
  https://stackoverflow.com/questions/46326059/
  https://stackoverflow.com/questions/36410756/
  https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
  https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.

""" % sys.argv[0]
    os._exit(4)


# test
import sys
print load_yaml_file(sys.argv[1])

How to check the differences between local and github before the pull

If you're not interested in the details that git diff outputs you can just run git cherry which will output a list of commits your remote tracking branch has ahead of your local branch.

For example:

git fetch origin
git cherry master origin/master

Will output something like :

+ 2642039b1a4c4d4345a0d02f79ccc3690e19d9b1
+ a4870f9fbde61d2d657e97b72b61f46d1fd265a9

Indicates that there are two commits in my remote tracking branch that haven't been merged into my local branch.

This also works the other way :

    git cherry origin/master master

Will show you a list of local commits that you haven't pushed to your remote repository yet.

Where is Android Studio layout preview?

Got the same problem after importing my Eclipse ADT project to Android Studio. Text and Desing tabs where missing.

Found my Event Log windows reads "Frameworks detected: Android framework is detected in the project Configure"

I click the hyperlink provided and everything was fixed, Text and Desing tabs became visible and functional

Responsive table handling in Twitter Bootstrap

Bootstrap 3 now has Responsive tables out of the box. Hooray! :)

You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive

Add a <div class="table-responsive"> surrounding your table and you should be good to go:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

To make it work on all layouts you can do this:

.table-responsive
{
    overflow-x: auto;
}

Requested registry access is not allowed

You Could Do The same as abatishchev but without the UAC

<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
   <security>
    <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
    </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>

How do you get the path to the Laravel Storage folder?

use this artisan command for create shortcut in public folder

php artisan storage:link

Than you will able to access posted img or file

A valid provisioning profile for this executable was not found... (again)

+1 to banging my head against the wall for a day or two...

Also check this setting:

Build Settings -> Code Signing -> Provisioning Profile

After following the above steps, "Automatic" setting worked for me. ~kjm~

Git: copy all files in a directory from another branch

As you are not trying to move the files around in the tree, you should be able to just checkout the directory:

git checkout master -- dirname

How to use doxygen to create UML class diagrams from C++ source

I think you will need to edit the doxys file and set GENERATE_UML (something like that) to true. And you need to have dot/graphviz installed.

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

How to restore default perspective settings in Eclipse IDE

1) Go to "Window".

2) Then click on "Open Perspective",

3) Then click on "Other",

4) Select "Java(Default)" and click "OK"

Then again go to "Window" and click on "Reset Perspective"

How can I pass arguments to anonymous functions in JavaScript?

The following is a method for using closures to address the issue to which you refer. It also takes into account the fact that may which to change the message over time without affecting the binding. And it uses jQuery to be succinct.

var msg = (function(message){
  var _message = message;
  return {
    say:function(){alert(_message)},
    change:function(message){_message = message}
  };
})("My Message");
$("#myButton").click(msg.say);

What is the minimum length of a valid international phone number?

EDIT 2015-06-27: Minimum is actually 8, including country code. My bad.

Original post

The minimum phone number that I use is 10 digits. International users should always be putting their country code, and as far as I know there are no countries with fewer than ten digits if you count country code.

More info here: https://en.wikipedia.org/wiki/Telephone_numbering_plan

On - window.location.hash - Change?

You could easily implement an observer (the "watch" method) on the "hash" property of "window.location" object.

Firefox has its own implementation for watching changes of object, but if you use some other implementation (such as Watch for object properties changes in JavaScript) - for other browsers, that will do the trick.

The code will look like this:

window.location.watch(
    'hash',
    function(id,oldVal,newVal){
        console.log("the window's hash value has changed from "+oldval+" to "+newVal);
    }
);

Then you can test it:

var myHashLink = "home";
window.location = window.location + "#" + myHashLink;

And of course that will trigger your observer function.

Sql select rows containing part of string

SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2&region=0&page=1', LEN(URL))

Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx

How to deep watch an array in angularjs?

You can set the 3rd argument of $watch to true:

$scope.$watch('data', function (newVal, oldVal) { /*...*/ }, true);

See https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

Since Angular 1.1.x you can also use $watchCollection to watch shallow watch (just the "first level" of) the collection.

$scope.$watchCollection('data', function (newVal, oldVal) { /*...*/ });

See https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchCollection

How to select the last record of a table in SQL?

MS SQL Server has supported ANSI SQL FETCH FIRST for many years now:

SELECT * FROM TABLE
ORDER BY ID DESC 
OFFSET 0 ROWS FETCH FIRST 1 ROW ONLY

(Works with most modern databases.)

Perl - Multiple condition if statement without duplicating code?

Simple:

if ( $name eq 'tom' && $password eq '123!'
    || $name eq 'frank' && $password eq '321!'
) {

(use the high-precedence && and || in expressions, reserving and and or for flow control, to avoid common precedence errors)

Better:

my %password = (
    'tom' => '123!',
    'frank' => '321!',
);

if ( exists $password{$name} && $password eq $password{$name} ) {

How to convert an Stream into a byte[] in C#?

I use this extension class:

public static class StreamExtensions
{
    public static byte[] ReadAllBytes(this Stream instream)
    {
        if (instream is MemoryStream)
            return ((MemoryStream) instream).ToArray();

        using (var memoryStream = new MemoryStream())
        {
            instream.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }
    }
}

Just copy the class to your solution and you can use it on every stream:

byte[] bytes = myStream.ReadAllBytes()

Works great for all my streams and saves a lot of code! Of course you can modify this method to use some of the other approaches here to improve performance if needed, but I like to keep it simple.

href="javascript:" vs. href="javascript:void(0)"

javascript:void(0); --> this executes void function and returns undefined. This could have issues with IE. javascript:; --> this does nothing. safest to create dead links. '#' --> this means pointing to same DOM, it will reload the page on click.

Can I add background color only for padding?

the answers said all the possible solutions

I have another one with BOX-SHADOW

here it is JSFIDDLE

and the code

nav {
    margin:0px auto;
    width:100%;
    height:50px;
    background-color:grey;
    float:left;
    padding:10px;
    border:2px solid red;
    box-shadow: 0 0 0 10px blue inset;
}

it also support in IE9, so It's better than gradient solution, add proper prefixes for more support

IE8 dont support it, what a shame !

Find empty or NaN entry in Pandas Dataframe

Partial solution: for a single string column tmp = df['A1'].fillna(''); isEmpty = tmp=='' gives boolean Series of True where there are empty strings or NaN values.

Call a child class method from a parent class object

Many of the answers here are suggesting implementing variant types using "Classical Object-Oriented Decomposition". That is, anything which might be needed on one of the variants has to be declared at the base of the hierarchy. I submit that this is a type-safe, but often very bad, approach. You either end up exposing all internal properties of all the different variants (most of which are "invalid" for each particular variant) or you end up cluttering the API of the hierarchy with tons of procedural methods (which means you have to recompile every time a new procedure is dreamed up).

I hesitate to do this, but here is a shameless plug for a blog post I wrote that outlines about 8 ways to do variant types in Java. They all suck, because Java sucks at variant types. So far the only JVM language that gets it right is Scala.

http://jazzjuice.blogspot.com/2010/10/6-things-i-hate-about-java-or-scala-is.html

The Scala creators actually wrote a paper about three of the eight ways. If I can track it down, I'll update this answer with a link.

UPDATE: found it here.

How do I sort a dictionary by value?

Of course, remember, you need to use OrderedDict because regular Python dictionaries don't keep the original order.

from collections import OrderedDict
a = OrderedDict(sorted(originalDict.items(), key=lambda x: x[1]))

If you do not have Python 2.7 or higher, the best you can do is iterate over the values in a generator function. (There is an OrderedDict for 2.4 and 2.6 here, but

a) I don't know about how well it works

and

b) You have to download and install it of course. If you do not have administrative access, then I'm afraid the option's out.)


def gen(originalDict):
    for x, y in sorted(zip(originalDict.keys(), originalDict.values()), key=lambda z: z[1]):
        yield (x, y)
    #Yields as a tuple with (key, value). You can iterate with conditional clauses to get what you want. 

for bleh, meh in gen(myDict):
    if bleh == "foo":
        print(myDict[bleh])

You can also print out every value

for bleh, meh in gen(myDict):
    print(bleh, meh)

Please remember to remove the parentheses after print if not using Python 3.0 or above

ImportError: No module named sklearn.cross_validation

If you have code that needs to run various versions you could do something like this:

import sklearn
if sklearn.__version__ > '0.18':
    from sklearn.model_selection import train_test_split
else:
    from sklearn.cross_validation import train_test_split

This isn't ideal though because you're comparing package versions as strings, which usually works but doesn't always. If you're willing to install packaging, this is a much better approach:

from packaging.version import parse
import sklearn
if parse(sklearn.__version__) > parse('0.18'):
    from sklearn.model_selection import train_test_split
else:
    from sklearn.cross_validation import train_test_split

Why compile Python code?

There is a performance increase in running compiled python. However when you run a .py file as an imported module, python will compile and store it, and as long as the .py file does not change it will always use the compiled version.

With any interpeted language when the file is used the process looks something like this:
1. File is processed by the interpeter.
2. File is compiled
3. Compiled code is executed.

obviously by using pre-compiled code you can eliminate step 2, this applies python, PHP and others.

Heres an interesting blog post explaining the differences http://julipedia.blogspot.com/2004/07/compiled-vs-interpreted-languages.html
And here's an entry that explains the Python compile process http://effbot.org/zone/python-compile.htm

Bash: infinite sleep (infinite blocking)

Let me explain why sleep infinity works though it is not documented. jp48's answer is also useful.

The most important thing: By specifying inf or infinity (both case-insensitive), you can sleep for the longest time your implementation permits (i.e. the smaller value of HUGE_VAL and TYPE_MAXIMUM(time_t)).

Now let's dig into the details. The source code of sleep command can be read from coreutils/src/sleep.c. Essentially, the function does this:

double s; //seconds
xstrtod (argv[i], &p, &s, cl_strtod); //`p` is not essential (just used for error check).
xnanosleep (s);

Understanding xstrtod (argv[i], &p, &s, cl_strtod)

xstrtod()

According to gnulib/lib/xstrtod.c, the call of xstrtod() converts string argv[i] to a floating point value and stores it to *s, using a converting function cl_strtod().

cl_strtod()

As can be seen from coreutils/lib/cl-strtod.c, cl_strtod() converts a string to a floating point value, using strtod().

strtod()

According to man 3 strtod, strtod() converts a string to a value of type double. The manpage says

The expected form of the (initial portion of the) string is ... or (iii) an infinity, or ...

and an infinity is defined as

An infinity is either "INF" or "INFINITY", disregarding case.

Although the document tells

If the correct value would cause overflow, plus or minus HUGE_VAL (HUGE_VALF, HUGE_VALL) is returned

, it is not clear how an infinity is treated. So let's see the source code gnulib/lib/strtod.c. What we want to read is

else if (c_tolower (*s) == 'i'
         && c_tolower (s[1]) == 'n'
         && c_tolower (s[2]) == 'f')
  {
    s += 3;
    if (c_tolower (*s) == 'i'
        && c_tolower (s[1]) == 'n'
        && c_tolower (s[2]) == 'i'
        && c_tolower (s[3]) == 't'
        && c_tolower (s[4]) == 'y')
      s += 5;
    num = HUGE_VAL;
    errno = saved_errno;
  }

Thus, INF and INFINITY (both case-insensitive) are regarded as HUGE_VAL.

HUGE_VAL family

Let's use N1570 as the C standard. HUGE_VAL, HUGE_VALF and HUGE_VALL macros are defined in §7.12-3

The macro
    HUGE_VAL
expands to a positive double constant expression, not necessarily representable as a float. The macros
    HUGE_VALF
    HUGE_VALL
are respectively float and long double analogs of HUGE_VAL.

HUGE_VAL, HUGE_VALF, and HUGE_VALL can be positive infinities in an implementation that supports infinities.

and in §7.12.1-5

If a floating result overflows and default rounding is in effect, then the function returns the value of the macro HUGE_VAL, HUGE_VALF, or HUGE_VALL according to the return type

Understanding xnanosleep (s)

Now we understand all essence of xstrtod(). From the explanations above, it is crystal-clear that xnanosleep(s) we've seen first actually means xnanosleep(HUGE_VALL).

xnanosleep()

According to the source code gnulib/lib/xnanosleep.c, xnanosleep(s) essentially does this:

struct timespec ts_sleep = dtotimespec (s);
nanosleep (&ts_sleep, NULL);

dtotimespec()

This function converts an argument of type double to an object of type struct timespec. Since it is very simple, let me cite the source code gnulib/lib/dtotimespec.c. All of the comments are added by me.

struct timespec
dtotimespec (double sec)
{
  if (! (TYPE_MINIMUM (time_t) < sec)) //underflow case
    return make_timespec (TYPE_MINIMUM (time_t), 0);
  else if (! (sec < 1.0 + TYPE_MAXIMUM (time_t))) //overflow case
    return make_timespec (TYPE_MAXIMUM (time_t), TIMESPEC_HZ - 1);
  else //normal case (looks complex but does nothing technical)
    {
      time_t s = sec;
      double frac = TIMESPEC_HZ * (sec - s);
      long ns = frac;
      ns += ns < frac;
      s += ns / TIMESPEC_HZ;
      ns %= TIMESPEC_HZ;

      if (ns < 0)
        {
          s--;
          ns += TIMESPEC_HZ;
        }

      return make_timespec (s, ns);
    }
}

Since time_t is defined as an integral type (see §7.27.1-3), it is natural we assume the maximum value of type time_t is smaller than HUGE_VAL (of type double), which means we enter the overflow case. (Actually this assumption is not needed since, in all cases, the procedure is essentially the same.)

make_timespec()

The last wall we have to climb up is make_timespec(). Very fortunately, it is so simple that citing the source code gnulib/lib/timespec.h is enough.

_GL_TIMESPEC_INLINE struct timespec
make_timespec (time_t s, long int ns)
{
  struct timespec r;
  r.tv_sec = s;
  r.tv_nsec = ns;
  return r;
}

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

Define global constants

Below changes works for me on Angular 2 final version:

export class AppSettings {
   public static API_ENDPOINT='http://127.0.0.1:6666/api/';
}

And then in the service:

import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';

@Injectable()
export class MessageService {

    constructor(private http: Http) { }

    getMessages(): Observable<Message[]> {
        return this.http.get(AppSettings.API_ENDPOINT+'/messages')
            .map(response => response.json())
            .map((messages: Object[]) => {
                return messages.map(message => this.parseData(message));
            });
    }

    private parseData(data): Message {
        return new Message(data);
    }
}

Returning binary file from controller in ASP.NET Web API

You can try the following code snippet

httpResponseMessage.Content.Headers.Add("Content-Type", "application/octet-stream");

Hope it will work for you.

Generating random whole numbers in JavaScript in a specific range?

/* Write a function called randUpTo that accepts a number and returns a random whole number between 0 and that number? */

var randUpTo = function(num) {
    return Math.floor(Math.random() * (num - 1) + 0);
};

/* Write a function called randBetween that accepts two numbers representing a range and returns a random whole number between those two numbers. */

var randBetween = function (min, max) {
    return Math.floor(Math.random() * (max - min - 1)) + min;
};

/* Write a function called randFromTill that accepts two numbers representing a range and returns a random number between min (inclusive) and max (exclusive). */

var randFromTill = function (min, max) {
    return Math.random() * (max - min) + min;
};

/* Write a function called randFromTo that accepts two numbers representing a range and returns a random integer between min (inclusive) and max (inclusive) */

var randFromTo = function (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
};

What do "branch", "tag" and "trunk" mean in Subversion repositories?

Now that's the thing about software development, there's no consistent knowledge about anything, everybody seems to have it their own way, but that's because it is a relatively young discipline anyway.

Here's my plain simple way,

trunk - The trunk directory contains the most current, approved, and merged body of work. Contrary to what many have confessed, my trunk is only for clean, neat, approved work, and not a development area, but rather a release area.

At some given point in time when the trunk seems all ready to release, then it is tagged and released.

branches - The branches directory contains experiments and ongoing work. Work under a branch stays there until is approved to be merged into the trunk. For me, this is the area where all the work is done.

For example: I can have an iteration-5 branch for a fifth round of development on the product, maybe a prototype-9 branch for a ninth round of experimenting, and so on.

tags - The tags directory contains snapshots of approved branches and trunk releases. Whenever a branch is approved to merge into the trunk, or a release is made of the trunk, a snapshot of the approved branch or trunk release is made under tags.

I suppose with tags I can jump back and forth through time to points interest quite easily.

Simple working Example of json.net in VB.net

Your class JSON_result does not match your JSON string. Note how the object JSON_result is going to represent is wrapped in another property named "Venue".

So either create a class for that, e.g.:

Public Class Container
    Public Venue As JSON_result
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
End Class

Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)

or change your JSON string to

{
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}

or use e.g. a ContractResolver to parse the JSON string.

Adding Jar files to IntellijIdea classpath

On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.

EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .

How can I call controller/view helper methods from the console in Ruby on Rails?

In Ruby on Rails 3, try this:

session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(url)
body = session.response.body

The body will contain the HTML of the URL.

How to route and render (dispatch) from a model in Ruby on Rails 3

Java 8: Difference between two LocalDateTime in multiple units

It should be simpler!

Duration.between(startLocalDateTime, endLocalDateTime).toMillis();

You can convert millis to whatever unit you like:

String.format("%d minutes %d seconds", 
  TimeUnit.MILLISECONDS.toMinutes(millis),
  TimeUnit.MILLISECONDS.toSeconds(millis) - 
  TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

How to get your Netbeans project into Eclipse

Sharing my experience, how to import simple Netbeans java project into Eclipse workspace. Please follow the following steps:

  1. Copy the Netbeans project folder into Eclipse workspace.
  2. Create .project file, inside the project folder at root level. Below code is the sample reference. Change your project name appropriately.

    <?xml version="1.0" encoding="UTF-8"?>
    <projectDescription>
        <name>PROJECT_NAME</name>
        <comment></comment>
        <projects>
        </projects>
        <buildSpec>
            <buildCommand>
                <name>org.eclipse.jdt.core.javabuilder</name>
                <arguments>
                </arguments>
            </buildCommand>
        </buildSpec>
        <natures>
            <nature>org.eclipse.jdt.core.javanature</nature>
        </natures>
    </projectDescription>
    
  3. Now open Eclipse and follow the steps,

    File > import > Existing Projects into Workspace > Select root directory > Finish

  4. Now we need to correct the build path for proper compilation of src, by following these steps:

    Right Click on project folder > Properties > Java Build Path > Click Source tab > Add Folder

(Add the correct src path from project and remove the incorrect ones). Find the image ref link how it looks.

  1. You are done. Let me know for any queries. Thanks.

Python Decimals format

Just use Python's standard string formatting methods:

>>> "{0:.2}".format(1.234232)
'1.2'
>>> "{0:.3}".format(1.234232)
'1.23'

If you are using a Python version under 2.6, use

>>> "%f" % 1.32423
'1.324230'
>>> "%.2f" % 1.32423
'1.32'
>>> "%d" % 1.32423
'1'

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

use maven dependency

<dependency> 
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-io</artifactId> 
  <version>1.3.2</version> 
</dependency> 

or download commons-io.1.3.2.jar to your lib folder

Getting a map() to return a list in Python 3.x

You can try getting a list from the map object by just iterating each item in the object and store it in a different variable.

a = map(chr, [66, 53, 0, 94])
b = [item for item in a]
print(b)
>>>['B', '5', '\x00', '^']

How to redraw DataTable with new data

The accepted answer calls the draw function twice. I can't see why that would be needed. In fact, if your new data has the same columns as the old data, you can accomplish this in one line:

datatable.clear().rows.add(newData).draw();

Counting number of occurrences in column?

=arrayformula(if(isblank(B2:B),iferror(1/0),mmult(sign(B2:B=TRANSPOSE(A2:A)),A2:A)))

I got this from a good tutorial - can't remember the title - probably about using MMult

How to split a string into an array in Bash?

Use this:

countries='Paris, France, Europe'
OIFS="$IFS"
IFS=', ' array=($countries)
IFS="$OIFS"

#${array[1]} == Paris
#${array[2]} == France
#${array[3]} == Europe

What is a None value?

Martijn's answer explains what None is in Python, and correctly states that the book is misleading. Since Python programmers as a rule would never say

Assigning a value of None to a variable is one way to reset it to its original, empty state.

it's hard to explain what Briggs means in a way which makes sense and explains why no one here seems happy with it. One analogy which may help:

In Python, variable names are like stickers put on objects. Every sticker has a unique name written on it, and it can only be on one object at a time, but you could put more than one sticker on the same object, if you wanted to. When you write

F = "fork"

you put the sticker "F" on a string object "fork". If you then write

F = None

you move the sticker to the None object.

What Briggs is asking you to imagine is that you didn't write the sticker "F", there was already an F sticker on the None, and all you did was move it, from None to "fork". So when you type F = None, you're "reset[ting] it to its original, empty state", if we decided to treat None as meaning empty state.

I can see what he's getting at, but that's a bad way to look at it. If you start Python and type print(F), you see

>>> print(F)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'F' is not defined

and that NameError means Python doesn't recognize the name F, because there is no such sticker. If Briggs were right and F = None resets F to its original state, then it should be there now, and we should see

>>> print(F)
None

like we do after we type F = None and put the sticker on None.


So that's all that's going on. In reality, Python comes with some stickers already attached to objects (built-in names), but others you have to write yourself with lines like F = "fork" and A = 2 and c17 = 3.14, and then you can stick them on other objects later (like F = 10 or F = None; it's all the same.)

Briggs is pretending that all possible stickers you might want to write were already stuck to the None object.

Delete specific line number(s) from a text file using sed?

If you want to delete lines 5 through 10 and 12:

sed -e '5,10d;12d' file

This will print the results to the screen. If you want to save the results to the same file:

sed -i.bak -e '5,10d;12d' file

This will back the file up to file.bak, and delete the given lines.

Note: Line numbers start at 1. The first line of the file is 1, not 0.

How to send a model in jQuery $.ajax() post request to MVC controller method

If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.

In our app, we do this with an extension method:

public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

On the view, we use it to render the model:

<script type="javascript">
  var model = <%= Model.ToJson() %>
</script>

You can then pass the model variable into your $.ajax call.

This application has no explicit mapping for /error

If all configurations are done correctly (as described in first two-three answers of this question) and still you are getting "Whitelabel Error Page" This application has no explicit mapping for /error, then this solution may help you

Sometimes beside configuration, issue can also be from your code side as well. You might have missed something very basic.
To identify issue you need to check the trace ,for that follow below steps

Open terminal.
1)cd project_location, to get the project location.
e.g. eclipse->project(right click)->properties->resource(tab)->copy path against location field.
2)then run script ./mvnw spring-boot:run

then go to http://localhost:8080/ , http://localhost:8080/xyz whichever url you expecting data.As soon as you hit the link ,trace would have got updated .

I was getting error like
2020-05-23 06:52:42.405 ERROR 3512 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: No default constructor for entity: : com.ibsplc.com.payroll.model.Employee; nested exception is org.hibernate.InstantiationException: No default constructor for entity: : com.ibsplc.com.payroll.model.Employee] with root cause

So, i added a default constructor for Employee model. run project as maven-build then then run script ./mvnw spring-boot:run,
it worked for me

Where is a log file with logs from a container?

To directly view the logfile in less, I use:

docker inspect $1 | grep 'LogPath' | sed -n "s/^.*\(\/var.*\)\",$/\1/p" | xargs sudo less

run as ./viewLogs.sh CONTAINERNAME

Spring Data JPA Update @Query not updating?

I struggled with the same problem where I was trying to execute an update query like the same as you did-

@Modifying
@Transactional
@Query(value = "UPDATE SAMPLE_TABLE st SET st.status=:flag WHERE se.referenceNo in :ids")
public int updateStatus(@Param("flag")String flag, @Param("ids")List<String> references);

This will work if you have put @EnableTransactionManagement annotation on the main class. Spring 3.1 introduces the @EnableTransactionManagement annotation to be used in on @Configuration classes and enable transactional support.

C - Convert an uppercase letter to lowercase

You can convert a character from lower case to upper case and vice-versa using bit manipulation as shown below:

#include<stdio.h>
int main(){
  char c;
  printf("Enter a character in uppercase\n");
  scanf("%c",&c);
  c|=' '; // perform or operation on c and ' '
  printf("The lower case of %c is \n",c);
  c&='_'; // perform 'and' operation with '_' to get upper case letter. 
  printf("Back to upper case %c\n",c);   
  return 0;
}

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

If you want to solve this issue using async/await:

(async function(){    
    try {        
        const response1, response2, response3
        response1 = await promise1()

        if(response1){
            response2 = await promise2()
        }
        if(response2){
            response3 = await promise3()
        }
        return [response1, response2, response3]
    } catch (error) {
        return []
    }

})()

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.

More details here.

CSS vertical-align: text-bottom;

Vertical align only works in some select cases. The easiest way to make it function is to set display: table in the parent element's CSS and display: table-cell; to the child element and then apply your vertical align attribute.

Python SQLite: database is locked

I also had this problem. I was trying to enter data into the database without saving changes I had made in it. after i saved the changes worked

Read a file line by line with VB.NET

Replaced the reader declaration with this one and now it works!

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Encoding.Default represents the ANSI code page that is set under Windows Control Panel.

Turning off auto indent when pasting text into vim

I just put set clipboard=unnamed in my .vimrc. That makes the default paste buffer map to X's clipboard.

So, if I mark a bit of text in a terminal, I can simply press p to paste it in vim. Similarly, I can yank things in vim (e.g. YY to yank the current line into the buffer) and middle click in any window to paste it.

I don't know. I find it super convenient.

SQL INSERT INTO from multiple tables

Here is an short extension for 3 or more tables to the answer of D Stanley:

INSERT INTO other_table (name, age, sex, city, id, number, nationality)
SELECT name, age, sex, city, p.id, number, n.nationality
FROM table_1 p
INNER JOIN table_2 a ON a.id = p.id
INNER JOIN table_3 b ON b.id = p.id
...
INNER JOIN table_n x ON x.id = p.id

Callback to a Fragment from a DialogFragment

You should define an interface in your fragment class and implement that interface in its parent activity. The details are outlined here http://developer.android.com/guide/components/fragments.html#EventCallbacks . The code would look similar to:

Fragment:

public static class FragmentA extends DialogFragment {

    OnArticleSelectedListener mListener;

    // Container Activity must implement this interface
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnArticleSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
        }
    }
}

Activity:

public class MyActivity extends Activity implements OnArticleSelectedListener{

    ...
    @Override
    public void onArticleSelected(Uri articleUri){

    }
    ...
}

Detect iPad users using jQuery?

Although the accepted solution is correct for iPhones, it will incorrectly declare both isiPhone and isiPad to be true for users visiting your site on their iPad from the Facebook app.

The conventional wisdom is that iOS devices have a user agent for Safari and a user agent for the UIWebView. This assumption is incorrect as iOS apps can and do customize their user agent. The main offender here is Facebook.

Compare these user agent strings from iOS devices:

# iOS Safari
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3
iPhone: Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

# UIWebView
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/98176
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/8B117

# Facebook UIWebView
iPad: Mozilla/5.0 (iPad; U; CPU iPhone OS 5_1_1 like Mac OS X; en_US) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1.1;FBBV/4110.0;FBDV/iPad2,1;FBMD/iPad;FBSN/iPhone OS;FBSV/5.1.1;FBSS/1; FBCR/;FBID/tablet;FBLC/en_US;FBSF/1.0]
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; ru_RU) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1;FBBV/4100.0;FBDV/iPhone3,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/5.1.1;FBSS/2; tablet;FBLC/en_US]

Note that on the iPad, the Facebook UIWebView's user agent string includes 'iPhone'.

The old way to identify iPhone / iPad in JavaScript:

IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);

If you were to go with this approach for detecting iPhone and iPad, you would end up with IS_IPHONE and IS_IPAD both being true if a user comes from Facebook on an iPad. That could create some odd behavior!

The correct way to identify iPhone / iPad in JavaScript:

IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);
if (IS_IPAD) {
  IS_IPHONE = false;
}

We declare IS_IPHONE to be false on iPads to cover for the bizarre Facebook UIWebView iPad user agent. This is one example of how user agent sniffing is unreliable. The more iOS apps that customize their user agent, the more issues user agent sniffing will have. If you can avoid user agent sniffing (hint: CSS Media Queries), DO IT.

How do you get the string length in a batch file?

I prefer jeb's accepted answer - it is the fastest known solution and the one I use in my own scripts. (Actually there are a few additional optimizations bandied about on DosTips, but I don't think they are worth it)

But it is fun to come up with new efficient algorithms. Here is a new algorithm that uses the FINDSTR /O option:

@echo off
setlocal
set "test=Hello world!"

:: Echo the length of TEST
call :strLen test

:: Store the length of TEST in LEN
call :strLen test len
echo len=%len%
exit /b

:strLen  strVar  [rtnVar]
setlocal disableDelayedExpansion
set len=0
if defined %~1 for /f "delims=:" %%N in (
  '"(cmd /v:on /c echo(!%~1!&echo()|findstr /o ^^"'
) do set /a "len=%%N-3"
endlocal & if "%~2" neq "" (set %~2=%len%) else echo %len%
exit /b

The code subtracts 3 because the parser juggles the command and adds a space before CMD /V /C executes it. It can be prevented by using (echo(!%~1!^^^).


For those that want the absolute fastest performance possible, jeb's answer can be adopted for use as a batch "macro" with arguments. This is an advanced batch technique devloped over at DosTips that eliminates the inherently slow process of CALLing a :subroutine. You can get more background on the concepts behind batch macros here, but that link uses a more primitive, less desirable syntax.

Below is an optimized @strLen macro, with examples showing differences between the macro and :subroutine usage, as well as differences in performance.

@echo off
setlocal disableDelayedExpansion

:: -------- Begin macro definitions ----------
set ^"LF=^
%= This creates a variable containing a single linefeed (0x0A) character =%
^"
:: Define %\n% to effectively issue a newline with line continuation
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

:: @strLen  StrVar  [RtnVar]
::
::   Computes the length of string in variable StrVar
::   and stores the result in variable RtnVar.
::   If RtnVar is is not specified, then prints the length to stdout.
::
set @strLen=for %%. in (1 2) do if %%.==2 (%\n%
  for /f "tokens=1,2 delims=, " %%1 in ("!argv!") do ( endlocal%\n%
    set "s=A!%%~1!"%\n%
    set "len=0"%\n%
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (%\n%
      if "!s:~%%P,1!" neq "" (%\n%
        set /a "len+=%%P"%\n%
        set "s=!s:~%%P!"%\n%
      )%\n%
    )%\n%
    for %%V in (!len!) do endlocal^&if "%%~2" neq "" (set "%%~2=%%V") else echo %%V%\n%
  )%\n%
) else setlocal enableDelayedExpansion^&setlocal^&set argv=,

:: -------- End macro definitions ----------

:: Print out definition of macro
set @strLen

:: Demonstrate usage

set "testString=this has a length of 23"

echo(
echo Testing %%@strLen%% testString
%@strLen% testString

echo(
echo Testing call :strLen testString
call :strLen testString

echo(
echo Testing %%@strLen%% testString rtn
set "rtn="
%@strLen% testString rtn
echo rtn=%rtn%

echo(
echo Testing call :strLen testString rtn
set "rtn="
call :strLen testString rtn
echo rtn=%rtn%

echo(
echo Measuring %%@strLen%% time:
set "t0=%time%"
for /l %%N in (1 1 1000) do %@strlen% testString testLength
set "t1=%time%"
call :printTime

echo(
echo Measuring CALL :strLen time:
set "t0=%time%"
for /l %%N in (1 1 1000) do call :strLen testString testLength
set "t1=%time%"
call :printTime
exit /b


:strlen  StrVar  [RtnVar]
::
:: Computes the length of string in variable StrVar
:: and stores the result in variable RtnVar.
:: If RtnVar is is not specified, then prints the length to stdout.
::
(
  setlocal EnableDelayedExpansion
  set "s=A!%~1!"
  set "len=0"
  for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
    if "!s:~%%P,1!" neq "" (
      set /a "len+=%%P"
      set "s=!s:~%%P!"
    )
  )
)
(
  endlocal
  if "%~2" equ "" (echo %len%) else set "%~2=%len%"
  exit /b
)

:printTime
setlocal
for /f "tokens=1-4 delims=:.," %%a in ("%t0: =0%") do set /a "t0=(((1%%a*60)+1%%b)*60+1%%c)*100+1%%d-36610100
for /f "tokens=1-4 delims=:.," %%a in ("%t1: =0%") do set /a "t1=(((1%%a*60)+1%%b)*60+1%%c)*100+1%%d-36610100
set /a tm=t1-t0
if %tm% lss 0 set /a tm+=24*60*60*100
echo %tm:~0,-2%.%tm:~-2% msec
exit /b

-- Sample Output --

@strLen=for %. in (1 2) do if %.==2 (
  for /f "tokens=1,2 delims=, " %1 in ("!argv!") do ( endlocal
    set "s=A!%~1!"
    set "len=0"
    for %P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
      if "!s:~%P,1!" neq "" (
        set /a "len+=%P"
        set "s=!s:~%P!"
      )
    )
    for %V in (!len!) do endlocal&if "%~2" neq "" (set "%~2=%V") else echo %V
  )
) else setlocal enableDelayedExpansion&setlocal&set argv=,

Testing %@strLen% testString
23

Testing call :strLen testString
23

Testing %@strLen% testString rtn
rtn=23

Testing call :strLen testString rtn
rtn=23

Measuring %@strLen% time:
1.93 msec

Measuring CALL :strLen time:
7.08 msec

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect

    <?php

$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion        = $_POST['seccion'];
$precio         = $_POST['precio'];
$fecha          = $_POST['fecha'];
$importado      = $_POST['importado'];
$paisdeorigen   = $_POST['paisdeorigen'];
try {

  $server = 'mysql: host=localhost; dbname=usuarios';
  $user   = 'root';
  $pass   = '';
  $base   = new PDO($server, $user, $pass);

  $base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $base->query("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $base->exec("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $sql = "
  INSERT INTO productos
  (CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
  VALUES
  (:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
  $result = $base->prepare($sql);
//  se pasan por parametros aqui
  $result->bindParam(':c_art', $codigoarticulo);
  $result->bindParam(':n_art', $nombrearticulo);
  $result->bindParam(':sec', $seccion);
  $result->bindParam(':pre', $precio);
  $result->bindParam(':fecha_art', $fecha);
  $result->bindParam(':import', $importado);
  $result->bindParam(':p_orig', $paisdeorigen);
  $result->execute();
  echo 'Articulo agregado';
} catch (Exception $e) {

  echo 'Error';
  echo $e->getMessage();
} finally {

}

?>

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

Error including image in Latex

I use MacTex, and my editor is TexShop. It probably has to do with what compiler you are using. When I use pdftex, the command:

\includegraphics[height=60mm, width=100mm]{number2.png}

works fine, but when I use "Tex and Ghostscript", I get the same error as you, about not being able to get the size information. Use pdftex.

Incidentally, you can change this in TexShop from the "Typeset" menu.

Hope this helps.

How to load a model from an HDF5 file in Keras?

I done in this way

from keras.models import Sequential
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy

# To save model
model.save('my_model_01.hdf5')

# To load the model
custom_objects={'CRF': CRF,'crf_loss': crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}

# To load a persisted model that uses the CRF layer 
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)

Converting ArrayList to Array in java

import java.util.*;
public class arrayList {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        ArrayList<String > x=new ArrayList<>();
        //inserting element
        x.add(sc.next());
        x.add(sc.next());
        x.add(sc.next());
        x.add(sc.next());
        x.add(sc.next());
         //to show element
         System.out.println(x);
        //converting arraylist to stringarray
         String[]a=x.toArray(new String[x.size()]);
          for(String s:a)
           System.out.print(s+" ");
  }

}

Random record from MongoDB

I'd suggest adding a random int field to each object. Then you can just do a

findOne({random_field: {$gte: rand()}}) 

to pick a random document. Just make sure you ensureIndex({random_field:1})

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

You can compare files from the explorer either from the working files section or the folder section. You can also trigger the global compare action from the command palette.

Regex - how to match everything except a particular pattern

You could use a look-ahead assertion:

(?!999)\d{3}

This example matches three digits other than 999.


But if you happen not to have a regular expression implementation with this feature (see Comparison of Regular Expression Flavors), you probably have to build a regular expression with the basic features on your own.

A compatible regular expression with basic syntax only would be:

[0-8]\d\d|\d[0-8]\d|\d\d[0-8]

This does also match any three digits sequence that is not 999.

How to modify list entries during for loop?

The answer given by Jemshit Iskenderov and Ignacio Vazquez-Abrams is really good. It can be further illustrated with this example: imagine that

a) A list with two vectors is given to you;

b) you would like to traverse the list and reverse the order of each one of the arrays

Let's say you have

v = np.array([1, 2,3,4])
b = np.array([3,4,6])

for i in [v, b]:
    i = i[::-1]   # this command does not reverse the string

print([v,b])

You will get

[array([1, 2, 3, 4]), array([3, 4, 6])]

On the other hand, if you do

v = np.array([1, 2,3,4])
b = np.array([3,4,6])

for i in [v, b]:
   i[:] = i[::-1]   # this command reverses the string

print([v,b])

The result is

[array([4, 3, 2, 1]), array([6, 4, 3])]

How to generate range of numbers from 0 to n in ES2015 only?

A lot of these solutions build on instantiating real Array objects, which can get the job done for a lot of cases but can't support cases like range(Infinity). You could use a simple generator to avoid these problems and support infinite sequences:

function* range( start, end, step = 1 ){
  if( end === undefined ) [end, start] = [start, 0];
  for( let n = start; n < end; n += step ) yield n;
}

Examples:

Array.from(range(10));     // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Array.from(range(10, 20)); // [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]

i = range(10, Infinity);
i.next(); // { value: 10, done: false }
i.next(); // { value: 11, done: false }
i.next(); // { value: 12, done: false }
i.next(); // { value: 13, done: false }
i.next(); // { value: 14, done: false }

Correct mime type for .mp4

When uploading .mp4 file into Perl script, using CGI.pm I see it as video/mp when printing out Content-type for the uploaded file. I hope it will help someone.

Makefile, header dependencies

The following works for me:

DEPS := $(OBJS:.o=.d)

-include $(DEPS)

%.o: %.cpp
    $(CXX) $(CFLAGS) -MMD -c -o $@ $<

Multi-select dropdown list in ASP.NET

I've used the open source control at http://dropdowncheckboxes.codeplex.com/ and been very happy with it. My addition was to allow a list of checked files to use just file names instead of full paths if the 'selected' caption gets too long. My addition is called instead of UpdateSelection in your postback handler:

// Update the caption assuming that the items are files<br/> 
// If the caption is too long, eliminate paths from file names<br/> 
public void UpdateSelectionFiles(int maxChars) {
  StringBuilder full = new StringBuilder(); 
  StringBuilder shorter = new StringBuilder();
  foreach (ListItem item in Items) { 
    if (item.Selected) { 
      full.AppendFormat("{0}; ", item.Text);
      shorter.AppendFormat("{0}; ", new FileInfo(item.Text).Name);
    } 
  } 
  if (full.Length == 0) Texts.SelectBoxCaption = "Select...";
  else if (full.Length <= maxChars) Texts.SelectBoxCaption = full.ToString(); 
  else Texts.SelectBoxCaption = shorter.ToString();
} 

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

This error occurs because of referenced jars are not checked in our project's order and export tab.

Choose Project ->ALT+Enter->Java Build Path ->Order and Export->check necessary jar files into your project.

Finally clean your project and run.It will run successfully.

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

Convert to date format dd/mm/yyyy

You can use a regular expression or some manual string fiddling, but I think I prefer:

date("d/m/Y", strtotime($str));

How can I get the current date and time in UTC or GMT in Java?

public class CurrentUtcDate 
{
    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println("UTC Time is: " + dateFormat.format(date));
    }
}

Output:

UTC Time is: 22-01-2018 13:14:35

You can change the date format as needed.

What's the proper way to "go get" a private repository?

The proper way is to manually put the repository in the right place. Once the repository is there, you can use go get -u to update the package and go install to install it. A package named

github.com/secmask/awserver-go

goes into

$GOPATH/src/github.com/secmask/awserver-go

The commands you type are:

cd $GOPATH/src/github.com/secmask
git clone [email protected]:secmask/awserver-go.git

UITableView - change section header color

 -(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view
  forSection:(NSInteger)section
  {
        if ([view isKindOfClass: [UITableViewHeaderFooterView class]])
        {
             UITableViewHeaderFooterView *castView = (UITableViewHeaderFooterView *) view;
             UIView *content = castView.contentView;
             UIColor *color = [UIColor whiteColor]; // substitute your color here
             content.backgroundColor = color;
             [castView.textLabel setTextColor:[UIColor blackColor]];
        }
 }

What does "Git push non-fast-forward updates were rejected" mean?

you might want to use force with push operation in this case

git push origin master --force

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

I ran into this when updating an entity with a JSON post request. The error occurred when I updated the entity without data about the children, even when there were none. Adding

"children": [],

to the request body solved the problem.

Detect if page has finished loading

var pageLoaded=0;

$(document).ready(function(){
   pageLoaded=1;
});

Using jquery: https://learn.jquery.com/using-jquery-core/document-ready/

VS2010 command prompt gives error: Cannot determine the location of the VS Common Tools folder

The issue in my case was a typo in the PATH variable. Since vsvars32.bat uses the "reg" tool to query the registry, it was failing because the tool was not found (just typing reg on a command prompt was failing for me).

Object Required Error in excel VBA

In order to set the value of integer variable we simply assign the value to it. eg g1val = 0 where as set keyword is used to assign value to object.

Sub test()

Dim g1val, g2val As Integer

  g1val = 0
  g2val = 0

    For i = 3 To 18

     If g1val > Cells(33, i).Value Then
        g1val = g1val
    Else
       g1val = Cells(33, i).Value
     End If

    Next i

    For j = 32 To 57
        If g2val > Cells(31, j).Value Then
           g2val = g2val
        Else
          g2val = Cells(31, j).Value
        End If
    Next j

End Sub

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

Bulk package updates using Conda

the Conda Package Manager is almost ready for beta testing, but it will not be fully integrated until the release of Spyder 2.4 (https://github.com/spyder-ide/spyder/wiki/Roadmap). As soon as we have it ready for testing we will post something on the mailing list (https://groups.google.com/forum/#!forum/spyderlib). Be sure to subscribe

Cheers!

Batch file to copy files from one folder to another folder

If you want to copy file not using absolute path, relative path in other words:

Don't forget to write backslash in the path AND NOT slash

Example:

copy children-folder\file.something .\other-children-folder

PS: absolute path can be retrieved using these wildcards called "batch parameters"

@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"

Check documentation here about copy: https://technet.microsoft.com/en-us/library/bb490886.aspx

And also here for batch parameters documentation: https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true

Auto Increment after delete in MySQL

I got a very simple but tricky method.

While deleting a row, you can preserve the IDs into another temporary table. After that, when you will insert new data into the main table then you can search and pick IDs from the temporary table. So use a checking here. If the temporary table has no IDs then calculate maximum ID into the main table and set the new ID as: new_ID = old_max_ID+1.

NB: You can not use auto-increment feature here.

shell init issue when click tab, what's wrong with getcwd?

This usually occurs when your current directory does not exist anymore. Most likely, from another terminal you remove that directory (from within a script or whatever). To get rid of this, in case your current directory was recreated in the meantime, just cd to another (existing) directory and then cd back; the simplest would be: cd; cd -.

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

Neither code is always better. They do different things, so they are good at different things.

InvariantCultureIgnoreCase uses comparison rules based on english, but without any regional variations. This is good for a neutral comparison that still takes into account some linguistic aspects.

OrdinalIgnoreCase compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é or ö. This is also faster because there are no extra rules to apply before comparing.

How can I completely uninstall nodejs, npm and node in Ubuntu

I was crazy to delete node and npm and nodejs from my Ubuntu 14.04 but with this steps you will remove it:

sudo apt-get uninstall nodejs npm node
sudo apt-get remove nodejs npm node

If you uninstall correctly and it is still there, check these links:

You can also try using find:

find / -name "node"

Although since that is likely to take a long time and return a lot of confusing false positives, you may want to search only PATH locations:

find $(echo $PATH | sed 's/:/ /g') -name "node"

It would probably be in /usr/bin/node or /usr/local/bin. After finding it, you can delete it using the correct path, eg:

sudo rm /usr/bin/node

how to remove the bold from a headline?

You can use font-weight:100 or lighter: this is working with i.e. Opera 16 and older, but I do not know why the h1 tags in Firefox are bolder, sorry.

Unescape HTML entities in Javascript?

You can use Lodash unescape / escape function https://lodash.com/docs/4.17.5#unescape

import unescape from 'lodash/unescape';

const str = unescape('fred, barney, &amp; pebbles');

str will become 'fred, barney, & pebbles'

How do I generate a stream from a string?

public Stream GenerateStreamFromString(string s)
{
    return new MemoryStream(Encoding.UTF8.GetBytes(s));
}

Difference between margin and padding?

Try putting a background color on a block div with width and height. You'll see that padding increases the size of the element, whereas margin just moves it within the flow of the document.

Margin is specifically for shifting the element around.

React - Display loading screen while DOM is rendering?

I had to deal with that problem recently and came up with a solution, which works just fine for me. However, I've tried @Ori Drori solution above and unfortunately it didn't work just right (had some delays + I don't like the usage of setTimeout function there).

This is what I came up with:

index.html file

Inside head tag - styles for the indicator:

<style media="screen" type="text/css">

.loading {
  -webkit-animation: sk-scaleout 1.0s infinite ease-in-out;
  animation: sk-scaleout 1.0s infinite ease-in-out;
  background-color: black;
  border-radius: 100%;
  height: 6em;
  width: 6em;
}

.container {
  align-items: center;
  background-color: white;
  display: flex;
  height: 100vh;
  justify-content: center;
  width: 100vw;
}

@keyframes sk-scaleout {
  0% {
    -webkit-transform: scale(0);
    transform: scale(0);
  }
  100% {
    -webkit-transform: scale(1.0);
    opacity: 0;
    transform: scale(1.0);
  }
}

</style>

Now the body tag:

<div id="spinner" class="container">
  <div class="loading"></div>
</div>

<div id="app"></div>

And then comes a very simple logic, inside app.js file (in the render function):

const spinner = document.getElementById('spinner');

if (spinner && !spinner.hasAttribute('hidden')) {
  spinner.setAttribute('hidden', 'true');
}

How does it work?

When the first component (in my app it's app.js aswell in most cases) mounts correctly, the spinner is being hidden with applying hidden attribute to it.

What's more important to add - !spinner.hasAttribute('hidden') condition prevents to add hidden attribute to the spinner with every component mount, so actually it will be added only one time, when whole app loads.

Converting BigDecimal to Integer

Following should do the trick:

BigDecimal d = new BigDecimal(10);
int i = d.intValue();

Jquery open popup on button click for bootstrap

Below mentioned link gives the clear explanation with example.

http://www.aspsnippets.com/Articles/Open-Show-jQuery-UI-Dialog-Modal-Popup-on-Button-Click.aspx

Code from the same link

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
    rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        $("#dialog").dialog({
            modal: true,
            autoOpen: false,
            title: "jQuery Dialog",
            width: 300,
            height: 150
        });
        $("#btnShow").click(function () {
            $('#dialog').dialog('open');
        });
    });
</script>
<input type="button" id="btnShow" value="Show Popup" />
<div id="dialog" style="display: none" align = "center">
    This is a jQuery Dialog.
</div>

How to set default font family for entire Android app

The answer is no, you can't. See Is it possible to set a custom font for entire of application? for more information.

There are workarounds, but nothing in the lines of "one single line of code here and all my fonts will be this instead of that".

(I kind of thank Google -and Apple- for that). Custom fonts have a place, but making them easy to replace app wide, would have created an entire world of Comic Sans applications)

Hibernate vs JPA vs JDO - pros and cons of each?

Some notes:

  • JDO and JPA are both specifications, not implementations.
  • The idea is you can swap JPA implementations, if you restrict your code to use standard JPA only. (Ditto for JDO.)
  • Hibernate can be used as one such implementation of JPA.
  • However, Hibernate provides a native API, with features above and beyond that of JPA.

IMO, I would recommend Hibernate.


There have been some comments / questions about what you should do if you need to use Hibernate-specific features. There are many ways to look at this, but my advice would be:

  • If you are not worried by the prospect of vendor tie-in, then make your choice between Hibernate, and other JPA and JDO implementations including the various vendor specific extensions in your decision making.

  • If you are worried by the prospect of vendor tie-in, and you can't use JPA without resorting to vendor specific extensions, then don't use JPA. (Ditto for JDO).

In reality, you will probably need to trade-off how much you are worried by vendor tie-in versus how much you need those vendor specific extensions.

And there are other factors too, like how well you / your staff know the respective technologies, how much the products will cost in licensing, and whose story you believe about what is going to happen in the future for JDO and JPA.

How to try convert a string to a Guid

This will get you pretty close, and I use it in production and have never had a collision. However, if you look at the constructor for a guid in reflector, you will see all of the checks it makes.

 public static bool GuidTryParse(string s, out Guid result)
    {
        if (!String.IsNullOrEmpty(s) && guidRegEx.IsMatch(s))
        {
            result = new Guid(s);
            return true;
        }

        result = default(Guid);
        return false;
    }

    static Regex guidRegEx = new Regex("^[A-Fa-f0-9]{32}$|" +
                          "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
                          "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$", RegexOptions.Compiled);

Error TF30063: You are not authorized to access ... \DefaultCollection

For me the error came after changing my password for my AD account.

I had to remove the line from credential manager (which contained the previous password.)

Then it worked again.

Call child component method from parent class - Angular

This Worked for me ! For Angular 2 , Call child component method in parent component

Parent.component.ts

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { ChildComponent } from '../child/child'; 
    @Component({ 
               selector: 'parent-app', 
               template: `<child-cmp></child-cmp>` 
              }) 
    export class parentComponent implements OnInit{ 
        @ViewChild(ChildComponent ) child: ChildComponent ; 

        ngOnInit() { 
           this.child.ChildTestCmp(); } 
}

Child.component.ts

import { Component } from '@angular/core';
@Component({ 
  selector: 'child-cmp', 
  template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> ` 
})
export class ChildComponent {
  test: string;
  ChildTestCmp() 
  { 
    this.test = "I am child component!"; 
  }
 }

Why do you create a View in a database?

Views also break down very complex configuration and tables into managable chunks that are easily queried against. In our database, our entire table managment system is broken down into views from one large table.

Pandas split column of lists into multiple columns

Much simpler solution:

pd.DataFrame(df2["teams"].to_list(), columns=['team1', 'team2'])

Yields,

  team1 team2
-------------
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG
7    SF   NYG

If you wanted to split a column of delimited strings rather than lists, you could similarly do:

pd.DataFrame(df["teams"].str.split('<delim>', expand=True).values,
             columns=['team1', 'team2'])

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 
});

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

Java method to swap primitives

You can't create a method swap, so that after calling swap(x,y) the values of x and y will be swapped. You could create such a method for mutable classes by swapping their contents¹, but this would not change their object identity and you could not define a general method for this.

You can however write a method that swaps two items in an array or list if that's what you want.

¹ For example you could create a swap method that takes two lists and after executing the method, list x will have the previous contents of list y and list y will have the previous contents of list x.

close vs shutdown socket?

linux: shutdown() causes listener thread select() to awake and produce error. shutdown(); close(); will lead to endless wait.

winsock: vice versa - shutdown() has no effect, while close() is successfully catched.

How do you embed binary data in XML?

You could encode the binary data using base64 and put it into a Base64 element; the below article is a pretty good one on the subject.

Handling Binary Data in XML Documents

How to use querySelectorAll only for elements that have a specific attribute set?

You can use querySelectorAll() like this:

var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');

This translates to:

get all inputs with the attribute "value" and has the attribute "value" that is not blank.

In this demo, it disables the checkbox with a non-blank value.

How to get raw text from pdf file using java

Extracting all keywords from PDF(from a web page) file on your local machine or Base64 encoded string:

import org.apache.commons.codec.binary.Base64;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WebPagePdfExtractor {

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();

        System.out.println("From file:   " + webPagePdfExtractor.processRecord(createByteArray()).get("text"));

        System.out.println("From string: " + webPagePdfExtractor.processRecord(getArrayFromBase64EncodedString()).get("text"));
    }

    public Map<String, Object> processRecord(byte[] byteArray) {
        Map<String, Object> map = new HashMap<>();
        try {
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(false);
            stripper.setShouldSeparateByBeads(true);

            PDDocument document = PDDocument.load(byteArray);
            String text = stripper.getText(document);
            map.put("text", text.replaceAll("\n|\r|\t", " "));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    private static byte[] getArrayFromBase64EncodedString() {
        String encodedContent = "data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0aCA1IDAgUiAvRmlsdGVyIC9GbGF0ZURlY29kZSA+PgpzdHJlYW0KeAGF0E0OgjAQBeA9p3hL3UCHlha2Gg9A0sS1AepPxIDl/rFFErVESDddvPlm8nqU6EFpzARjBCVkLHNkipBzPBsc8UCyt4TKgmCr/9HI+GDqg2x8Luzk8UtfYwX5DVWLnQaLmd+qHTsF3V5QEekWidZuDNpgc7L1FvqGg35fOzPlqslFYJrzZdnkq6YI77TXtrs3GBo7oKvNss9mfhT0IAV+e6CUL5pSTWb0t1tVBKbI5McsXxNmciYKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjE4NQplbmRvYmoKMiAwIG9iago8PCAvVHlwZSAvUGFnZSAvUGFyZW50IDMgMCBSIC9SZXNvdXJjZXMgNiAwIFIgL0NvbnRlbnRzIDQgMCBSIC9NZWRpYUJveCBbMCAwIDU5NSA4NDJdC" +
                "j4+CmVuZG9iago2IDAgb2JqCjw8IC9Qcm9jU2V0IFsgL1BERiAvVGV4dCBdIC9Db2xvclNwYWNlIDw8IC9DczEgNyAwIFIgL0NzMiA4IDAgUiA+PiAvRm9udCA8PAovVFQxIDkgMCBSID4+ID4+CmVuZG9iagoxMCAwIG9iago8PCAvTGVuZ3RoIDExIDAgUiAvTiAxIC9BbHRlcm5hdGUgL0RldmljZUdyYXkgL0ZpbHRlciAvRmxhdGVEZWNvZGUgPj4Kc3RyZWFtCngBhVVdaBxVFD67c2cDEgcftA0ttIM/bQnpMolWE4u12026SRO362ZTmyrKdHY2O81kZpyZ3SahT6XgmxYE6augPsaCCLYqNi/2paXFkko1DwoRWowgKH1S8Dsz22R2QTLDnfnuueeee8537rmXqOtv3f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rJYsPTtK5l6W5daN+qqWDHh+6oicYqKpyD9kyocpRTtSXcR8Em1J7muwlW1LexrtSs5JZLuScwa5pXgGyx/hdZxIeA" +
                "JTPMvxBMSaYoSmQ+nHtDywiJbzyzTe7xcfDmR5vTBcyPsKv7yBPEyXopGDxCAHOoUoppRILPQiribnP/IqOjlLka3XEo5eIbu8bCTCqRmej6+99ib/lF6im3/13ItnD8OtF4LyxN+YxQq0iwTyqjsx0mwIFVUkLkZSWbX1dmiLORxlVBGTIWSC" +
                "NNE0wTAxNnJCdIHTeHOcTzt1nM80dUbxARJ9r/0+T2BoAA0leOYPHXrlpnIwoYmg8NPdo9LFdJYupavSQ9JD09Xpmtzw3IjcyNyo3OjcmNzY3LhcWzVUi9WsWqpWVYdUh1arqzXecG+EN9Ib5Y32xnhjvXFem5POpPLJEh5Ff6LMf2vVqgwKOx" +
                "IeHbu64vXswkn3v54zdkzOzp2Oubnjy6B7dMEZfqlnubDymyWVX/SsEFbeWCy3YknJ0NxCWddt/CFxKspCjmFZ7tgfY1ibvokegcNxGL9GKZGsUI5imYqJoV/8GMZcsm0pXJhNRtkbfuofdPmBA3IYu/rV+/Oa6I3VNatqa1fVrF7Xc1xSe4um" +
                "8Xf5df53fnwavfXR+Qud5y5iFJPtvRPjmIQ8JZJlbrdOK+g1EfG2kFBBpY6wxdvy4myRao0tXrSSOtouWuqs7ZH1JrHe1WZqSopTa+JjVOSBGEk/RiVZEgqSgu58RXZfObDIh6OR3+o23uo2RyjHipKn6ZU8Tak9CcETUz5L4pVkSPq3k2cPTBMGYPo2CFUCJx9oLqqqfPitsWvXdX1YtP+x+YemPrvqVkjBy789//70FjFn34ABk4vGjXXqo7dVtbQ6nW3Z2XM91RmCPn7jilf+4FD2incAMYS9hLExwx2pZyEG2E9M9HDIfnWIJhTzYclo1v88MnbdHNohp0Cyg8sx8Wdmb8Lr7nY+a9ayU5dP7ZZDI3uJH/b2NP9qzsaWE0KJlw5HnSvPvefwlwRZ2r988CqMnmzBUySc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MDAwMDMxMTEgMDAwMDAgbiAKMDAwMDAwMzU0NCAwMDAwMCB" +
                "uIAowMDAwMDAzNzk2IDAwMDAwIG4gCjAwMDAwMDg2ODcgMDAwMDAgbiAKMDAwMDAwODcwOCAwMDAwMCBuIAowMDAwMDA4NzI3IDAwMDAwIG4gCjAwMDAwMDg3ODAgMDAwMDAgbiAKMDAwMDAwODc5OSAwMDAwMCBuIAowMDAwMDA4ODE4IDAwMDAwIG4gCjAwMDAwMDg4NDUgMDAwMDAgbiAKMDAwMDAwODg4NyAwMDAwMCBuIAowMDAwMDA4OTA2IDAwMDAwIG4gCnRyYWlsZXIKPDwgL1NpemUgMjYgL1Jvb3QgMTQgMCBSIC9JbmZvIDEgMCBSIC9JRCBbIDxkYjc4M2NhNDM2Mzg4YzI5ZDc5MDQ2NzY3NjUxNjE3OT4KPGRiNzgzY2E0MzYzODhjMjlkNzkwNDY3Njc2NTE2MTc5PiBdID4+CnN0YXJ0eHJlZgo5MTA0CiUlRU9GCg==";
        String content = encodedContent.substring("data:application/pdf;base64," .length());
        return Base64.decodeBase64(content);
    }

    public static byte[] createByteArray() {
        String pathToBinaryData = "/bla-bla/src/main/resources/small.pdf";

        File file = new File(pathToBinaryData);
        if (!file.exists()) {
            System.out.println(" could not be found in folder " + pathToBinaryData);
            return null;
        }

        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        byte fileContent[] = new byte[(int) file.length()];

        try {
            fin.read(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileContent;
    }
}

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

Is it possible to deserialize XML into List<T>?

Yes, it will serialize and deserialize a List<>. Just make sure you use the [XmlArray] attribute if in doubt.

[Serializable]
public class A
{
    [XmlArray]
    public List<string> strings;
}

This works with both Serialize() and Deserialize().

Want custom title / image / description in facebook share link from a flash app

2016 Update

Use the Sharing Debugger to figure out what your problems are.

Make sure you're following the Facebook Sharing Best Practices.

Make sure you're using the Open Graph Markup correctly.

Original Answer

I agree with what has already been said here, but per documentation on the Facebook developer site, you might want to use the following meta tags.

<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />

If you are not able to accomplish your goal with meta tags and you need a URL embedded version, see @Lelis718's answer below.

How to enable CORS in ASP.net Core WebAPI

For me it started working when i have set explicitly the headers that I was sending. I was adding the content-type header, and then it worked.

.net

.WithHeaders("Authorization","Content-Type")

javascript:

this.fetchoptions = {
        method: 'GET', 
        cache: 'no-cache', 
        credentials: 'include', 
        headers: {
            'Content-Type': 'application/json',
        },
        redirect: 'follow', 
    }; 

What is the correct JSON content type?

Not everything works for content type application/json.

If you are using Ext JS form submit to upload file, be aware that the server response is parsed by the browser to create the document for the <iframe>.

If the server is using JSON to send the return object, then the Content-Type header must be set to text/html in order to tell the browser to insert the text unchanged into the document body.

See the Ext JS 3.4.0 API documentation.

Get String in YYYYMMDD format from JS date object?

new Date('Jun 5 2016').
  toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
  replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');

// => '2016-06-05'

Using CookieContainer with WebClient class

 WebClient wb = new WebClient();
 wb.Headers.Add(HttpRequestHeader.Cookie, "somecookie");

From Comments

How do you format the name and value of the cookie in place of "somecookie" ?

wb.Headers.Add(HttpRequestHeader.Cookie, "cookiename=cookievalue"); 

For multiple cookies:

wb.Headers.Add(HttpRequestHeader.Cookie, 
              "cookiename1=cookievalue1;" +
              "cookiename2=cookievalue2");

Calling remove in foreach loop in Java

You don't want to do that. It can cause undefined behavior depending on the collection. You want to use an Iterator directly. Although the for each construct is syntactic sugar and is really using an iterator, it hides it from your code so you can't access it to call Iterator.remove.

The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

Instead write your code:

List<String> names = ....
Iterator<String> it = names.iterator();
while (it.hasNext()) {

    String name = it.next();
    // Do something
    it.remove();
}

Note that the code calls Iterator.remove, not List.remove.

Addendum:

Even if you are removing an element that has not been iterated over yet, you still don't want to modify the collection and then use the Iterator. It might modify the collection in a way that is surprising and affects future operations on the Iterator.

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

How to determine the current shell I'm working on

If you just want to check that you are running (a particular version of) Bash, the best way to do so is to use the $BASH_VERSINFO array variable. As a (read-only) array variable it cannot be set in the environment, so you can be sure it is coming (if at all) from the current shell.

However, since Bash has a different behavior when invoked as sh, you do also need to check the $BASH environment variable ends with /bash.

In a script I wrote that uses function names with - (not underscore), and depends on associative arrays (added in Bash 4), I have the following sanity check (with helpful user error message):

case `eval 'echo $BASH@${BASH_VERSINFO[0]}' 2>/dev/null` in
    */bash@[456789])
        # Claims bash version 4+, check for func-names and associative arrays
        if ! eval "declare -A _ARRAY && func-name() { :; }" 2>/dev/null; then
            echo >&2 "bash $BASH_VERSION is not supported (not really bash?)"
            exit 1
        fi
        ;;
    */bash@[123])
        echo >&2 "bash $BASH_VERSION is not supported (version 4+ required)"
        exit 1
        ;;
    *)
        echo >&2 "This script requires BASH (version 4+) - not regular sh"
        echo >&2 "Re-run as \"bash $CMD\" for proper operation"
        exit 1
        ;;
esac

You could omit the somewhat paranoid functional check for features in the first case, and just assume that future Bash versions would be compatible.

Set value of textbox using JQuery

You are logging sup directly which is a string

console.log('sup')

Also you are using the wrong id

The template says #main_search but you are using #searchBar

I suppose you are trying this out

$(function() {
   var sup = $('#main_search').val('hi')
   console.log(sup);  // sup is a variable here
});

Hiding button using jQuery

jQuery offers the .hide() method for this purpose. Simply select the element of your choice and call this method afterward. For example:

$('#comanda').hide();

One can also determine how fast the transition runs by providing a duration parameter in miliseconds or string (possible values being 'fast', and 'slow'):

$('#comanda').hide('fast');

In case you want to do something just after the element hid, you must provide a callback as a parameter too:

$('#comanda').hide('fast', function() {
  alert('It is hidden now!');
});

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Need to make sure you have the numeric keypad and the tab key working too

 // Allow only backspace and delete
            if (event.keyCode == 46 || event.keyCode == 8  || event.keyCode == 9) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {

                }
                else {
                    event.preventDefault();
                }
            }

sklearn plot confusion matrix with labels

    from sklearn.metrics import confusion_matrix
    import seaborn as sns
    import matplotlib.pyplot as plt
    model.fit(train_x, train_y,validation_split = 0.1, epochs=50, batch_size=4)
    y_pred=model.predict(test_x,batch_size=15)
    cm =confusion_matrix(test_y.argmax(axis=1), y_pred.argmax(axis=1))  
    index = ['neutral','happy','sad']  
    columns = ['neutral','happy','sad']  
    cm_df = pd.DataFrame(cm,columns,index)                      
    plt.figure(figsize=(10,6))  
    sns.heatmap(cm_df, annot=True)

Confusion matrix

How do I register a .NET DLL file in the GAC?

As ando said, just drag and drop the assembly to the C:\windows\assembly folder. It works.

How to specify an alternate location for the .m2 folder or settings.xml permanently?

You need to add this line into your settings.xml (or uncomment if it's already there).

<localRepository>C:\Users\me\.m2\repo</localRepository>

Also it's possible to run your commands with mvn clean install -gs C:\Users\me\.m2\settings.xml - this parameter will force maven to use different settings.xml then the default one (which is in $HOME/.m2/settings.xml)

Virtual member call in a constructor

I think that ignoring the warning might be legitimate if you want to give the child class the ability to set or override a property that the parent constructor will use right away:

internal class Parent
{
    public Parent()
    {
        Console.WriteLine("Parent ctor");
        Console.WriteLine(Something);
    }

    protected virtual string Something { get; } = "Parent";
}

internal class Child : Parent
{
    public Child()
    {
        Console.WriteLine("Child ctor");
        Console.WriteLine(Something);
    }

    protected override string Something { get; } = "Child";
}

The risk here would be for the child class to set the property from its constructor in which case the change in the value would occur after the base class constructor has been called.

My use case is that I want the child class to provide a specific value or a utility class such as a converter and I don't want to have to call an initialization method on the base.

The output of the above when instantiating the child class is:

Parent ctor
Child
Child ctor
Child

How to set a fixed width column with CSS flexbox

In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

flex-basis: 25%;

This will be a lot smoother when testing.

// VARIABLES
$screen-xs:                                         480px;
$screen-sm:                                         768px;
$screen-md:                                         992px;
$screen-lg:                                         1200px;
$screen-xl:                                         1400px;
$screen-xxl:                                        1600px;

// QUERIES
@media screen (max-width: $screen-lg) {
    flex-basis: 25%;
}

@media screen (max-width: $screen-md) {
    flex-basis: 33.33%;
}

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Convert seconds to Hour:Minute:Second

The gmtdate() function didn't work for me as I was tracking hours worked on a project and if it's over 24 hours, you get amount left over after 24 hours is subtracted. In other words 37 hours becomes 13 hours. (all as stated above by Glavic - thanks for your examples!) This one worked well:

Convert seconds to format by 'foot' no limit :
$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05

How to clear the interpreter console?

Magic strings are mentioned above - I believe they come from the terminfo database:

http://www.google.com/?q=x#q=terminfo

http://www.google.com/?q=x#q=tput+command+in+unix

$ tput clear| od -t x1z 0000000 1b 5b 48 1b 5b 32 4a >.[H.[2J< 0000007

Explain the "setUp" and "tearDown" Python methods used in test cases

You can use these to factor out code common to all tests in the test suite.

If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.

You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.

If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.

For example:

class TurretTest(unittest.TestCase):

    def setUp(self):
        self.turret_factory = TurretFactory()
        self.turret = self.turret_factory.CreateTurret()

    def test_turret_is_on_by_default(self):
        self.assertEquals(True, self.turret.is_on())

    def test_turret_turns_can_be_turned_off(self):
        self.turret.turn_off()
        self.assertEquals(False, self.turret.is_on())

SQL select statements with multiple tables

select P.*,
A.Street,
A.City,
A.State
from Preson P
inner join Address A on P.id=A.Person_id
where A.Zip=97229
Order by A.Street,A.City,A.State

Retina displays, high-res background images

If you are planing to use the same image for retina and non-retina screen then here is the solution. Say that you have a image of 200x200 and have two icons in top row and two icon in bottom row. So, it's four quadrants.

.sprite-of-icons {
  background: url("../images/icons-in-four-quad-of-200by200.png") no-repeat;
  background-size: 100px 100px /* Scale it down to 50% rather using 200x200 */
}

.sp-logo-1 { background-position: 0 0; }

/* Reduce positioning of the icons down to 50% rather using -50px */
.sp-logo-2 { background-position: -25px 0 }
.sp-logo-3 { background-position: 0 -25px }
.sp-logo-3 { background-position: -25px -25px }

Scaling and positioning of the sprite icons to 50% than actual value, you can get the expected result.


Another handy SCSS mixin solution by Ryan Benhase.

/****************************
 HIGH PPI DISPLAY BACKGROUNDS
*****************************/

@mixin background-2x($path, $ext: "png", $w: auto, $h: auto, $pos: left top, $repeat: no-repeat) {

  $at1x_path: "#{$path}.#{$ext}";
  $at2x_path: "#{$path}@2x.#{$ext}";

  background-image: url("#{$at1x_path}");
  background-size: $w $h;
  background-position: $pos;
  background-repeat: $repeat;

  @media all and (-webkit-min-device-pixel-ratio : 1.5),
  all and (-o-min-device-pixel-ratio: 3/2),
  all and (min--moz-device-pixel-ratio: 1.5),
  all and (min-device-pixel-ratio: 1.5) {
    background-image: url("#{$at2x_path}"); 
  }
}

div.background {
  @include background-2x( 'path/to/image', 'jpg', 100px, 100px, center center, repeat-x );
}

For more info about above mixin READ HERE.

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

This is the way I updated the master branch

This kind of error occurs commonly after deleting the initial code on your project

So, go ahead, first of all, verify the actual remote version, then remove the origin add the comment, and copy the repo URL into the project files.

$ git remote -v
$ git remote rm origin
$ git commit -m "your commit"
$ git remote add origin https://github.com/user/repo.git
$ git push -f origin master

Gson library in Android Studio

If you are going to use it with Retrofit library, I suggest you to use Square's gson library as:

implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

How to view query error in PDO PHP

You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.
And since you expect the exception to be thrown by the prepare() method you should disable the PDO::ATTR_EMULATE_PREPARES* feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


    $pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');
}
catch(Exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

prints (in my case)

Exception -> string(91) "SQLSTATE[42S02]: Base table or view not found: 
1146 Table 'test.doesnotexist' doesn't exist"

see http://wezfurlong.org/blog/2006/apr/using-pdo-mysql/
EMULATE_PREPARES=true seems to be the default setting for the pdo_mysql driver right now. The query cache thing has been fixed/change since then and with the mysqlnd driver I hadn't problems with EMULATE_PREPARES=false (though I'm only a php hobbyist, don't take my word on it...)

*) and then there's PDO::MYSQL_ATTR_DIRECT_QUERY - I must admit that I don't understand the interaction of those two attributes (yet?), so I set them both, like

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));

Android ImageView Fixing Image Size

Try this

ImageView img
    Bitmap bmp;
    int width=100;
    int height=100;
    img=(ImageView)findViewById(R.id.imgView);
    bmp=BitmapFactory.decodeResource(getResources(),R.drawable.image);//image is your image                                                            
    bmp=Bitmap.createScaledBitmap(bmp, width,height, true);
    img.setImageBitmap(bmp);

Or If you want to load complete image size in memory then you can use

<ImageView
    android:id="@+id/img"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@drawable/image" 
    android:scaleType="fitXY"/>

text flowing out of div

You need to apply the following CSS property to the container block (div):

overflow-wrap: break-word;

According to the specifications (source CSS | MDN):

The overflow-wrap CSS property specifies whether or not the browser should insert line breaks within words to prevent text from overflowing its content box.

With the value set to break-word

To prevent overflow, normally unbreakable words may be broken at arbitrary points if there are no otherwise acceptable break points in the line.

Worth mentioning...

The property was originally a nonstandard and unprefixed Microsoft extension called word-wrap, and was implemented by most browsers with the same name. It has since been renamed to overflow-wrap, with word-wrap being an alias.


If you care about legacy browsers support it's worth specifying both:

word-wrap    : break-word;
overflow-wrap: break-word;

Ex. IE9 does not recognize overflow-wrap but works fine with word-wrap

How to check if running as root in a bash script

Check for root:

ROOT_UID=0   # Root has $UID 0.

if [ "$UID" -eq "$ROOT_UID" ]
then
  echo "You are root."
else
  echo "You are just an ordinary user."
fi

exit 0

Tested and running in root.

How to get df linux command output always in GB

You can use the -B option.

Man page of df:

-B, --block-size=SIZE use SIZE-byte blocks

All together,

df -BG

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

Print a string as hex bytes?

Using map and lambda function can produce a list of hex values, which can be printed (or used for other purposes)

>>> s = 'Hello 1 2 3 \x01\x02\x03 :)'

>>> map(lambda c: hex(ord(c)), s)
['0x48', '0x65', '0x6c', '0x6c', '0x6f', '0x20', '0x31', '0x20', '0x32', '0x20', '0x33', '0x20', '0x1', '0x2', '0x3', '0x20', '0x3a', '0x29']

Getting around the Max String size in a vba function?

Are you sure? This forum thread suggests it might be your watch window. Try outputting the string to a MsgBox, which can display a maximum of 1024 characters:

MsgBox RunMacros

Load image from resources

You can always use System.Resources.ResourceManager which returns the cached ResourceManager used by this class. Since chan1 and chan2 represent two different images, you may use System.Resources.ResourceManager.GetObject(string name) which returns an object matching your input with the project resources

Example

object O = Resources.ResourceManager.GetObject("chan1"); //Return an object from the image chan1.png in the project
channelPic.Image = (Image)O; //Set the Image property of channelPic to the returned object as Image

Notice: Resources.ResourceManager.GetObject(string name) may return null if the string specified was not found in the project resources.

Thanks,
I hope you find this helpful :)

javascript: detect scroll end

if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight)
{
//your code here
}

I too searched it and even after checking all comments here and more, this is the solution to check if reached the bottom or not.