Programs & Examples On #Multi agent

A Multi-Agent System (MAS) is a system composed of multiple interacting intelligent agents within a given environment based on the new paradigm for conceptualizing, designing, and implementing software systems.

How can I convert an HTML element to a canvas element?

function convert() {
                    dom = document.getElementById('divname');
                    var script,
                    $this = this,
                    options = this.options,
                    runH2c = function(){
                        try {
                            var canvas =     window.html2canvas([ document.getElementById('divname') ], {
                                onrendered: function( canvas ) {


                        } catch( e ) {
                            $this.h2cDone = true;
                            log("Error in html2canvas: " + e.message);

                    if ( window.html2canvas === undefined && script === undefined ) {
                    } else {.
                        // html2canvas already loaded, just run it then

How to solve maven 2.6 resource plugin dependency?

If a download fails for some reason Maven will not try to download it within a certain time frame (it leaves a file with a timestamp).

To fix this you can either

  • Clear (parts of) your .m2 repo
  • Run maven with -U to force an update

Adjust plot title (main) position

We can use title() function with negative line value to bring down the title.

See this example:

plot(1, 1)
title("Title", line = -2)

enter image description here

How to add data to DataGridView

first you need to add 2 columns to datagrid. you may do it at design time. see Columns property. then add rows as much as you need.

this.dataGridView1.Rows.Add("1", "XX");

Capture Video of Android's Screen

Android 4.3 has a new MediaCodec API that can be used to record from a surface. See: (scroll down to the section "Video encoding from a Surface")

Java - What does "\n" mean?

(as per

The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and { matches a left brace.

Other examples of usage :

\\ The backslash character<br>
\t The tab character ('\u0009')<br>
\n The newline (line feed) character ('\u000A')<br>
\r The carriage-return character ('\u000D')<br>
\f The form-feed character ('\u000C')<br>
\a The alert (bell) character ('\u0007')<br>
\e The escape character ('\u001B')<br>
\cx The control character corresponding to x <br>

Ignore outliers in ggplot2 boxplot

One idea would be to winsorize the data in a two-pass procedure:

  1. run a first pass, learn what the bounds are, e.g. cut of at given percentile, or N standard deviation above the mean, or ...

  2. in a second pass, set the values beyond the given bound to the value of that bound

I should stress that this is an old-fashioned method which ought to be dominated by more modern robust techniques but you still come across it a lot.

What is the best way to merge mp3 files?

As Thomas Owens pointed out, simply concatenating the files will leave multiple ID3 headers scattered throughout the resulting concatenated file - so the time/bitrate info will be wildly wrong.

You're going to need to use a tool which can combine the audio data for you.

mp3wrap would be ideal for this - it's designed to join together MP3 files, without needing to decode + re-encode the data (which would result in a loss of audio quality) and will also deal with the ID3 tags intelligently.

The resulting file can also be split back into its component parts using the mp3splt tool - mp3wrap adds information to the IDv3 comment to allow this.

Select every Nth element in CSS

Try this


Getting the array length of a 2D array in Java

.length = number of rows / column length

[0].length = number of columns / row length

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

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

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

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

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

jQuery 'input' event

Occurs when the text content of an element is changed through the user interface.

It's not quite an alias for keyup because keyup will fire even if the key does nothing (for example: pressing and then releasing the Control key will trigger a keyup event).

A good way to think about it is like this: it's an event that triggers whenever the input changes. This includes -- but is not limited to -- pressing keys which modify the input (so, for example, Ctrl by itself will not trigger the event, but Ctrl-V to paste some text will), selecting an auto-completion option, Linux-style middle-click paste, drag-and-drop, and lots of other things.

See this page and the comments on this answer for more details.

Chrome desktop notification example

See also ServiceWorkerRegistration.showNotification

It appears that window.webkitNotifications has already been deprecated and removed. However, there's a new API, and it appears to work in the latest version of Firefox as well.

function notifyMe() {
  // Let's check if the browser supports notifications
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");

  // Let's check if the user is okay to get some notification
  else if (Notification.permission === "granted") {
    // If it's okay let's create a notification
    var notification = new Notification("Hi there!");

  // Otherwise, we need to ask the user for permission
  // Note, Chrome does not implement the permission static property
  // So we have to check for NOT 'denied' instead of 'default'
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {

      // Whatever the user answers, we make sure we store the information
      if(!('permission' in Notification)) {
        Notification.permission = permission;

      // If the user is okay, let's create a notification
      if (permission === "granted") {
        var notification = new Notification("Hi there!");
  } else {
    alert(`Permission is ${Notification.permission}`);


Percentage width in a RelativeLayout

This does not quite answer the original question, which was for a 70/30 split, but in the special case of a 50/50 split between the components there is a way: place an invisible strut at the center and use it to position the two components of interest.

    <View android:id="@+id/strut"

As this is a pretty common case, this solution is more than a curiosity. It is a bit of a hack but an efficient one because the empty, zero-sized strut should cost very little.

In general, though, it's best not to expect too much from the stock Android layouts...

How to validate a form with multiple checkboxes to have atleast one checked

This script below should put you on the right track perhaps?

You can keep this html the same (though I changed the method to POST):

<form method="POST" id="subscribeForm">
    <fieldset id="cbgroup">
        <div><input name="list" id="list0" type="checkbox"  value="newsletter0" >zero</div>
        <div><input name="list" id="list1" type="checkbox"  value="newsletter1" >one</div>
        <div><input name="list" id="list2" type="checkbox"  value="newsletter2" >two</div>
    <input name="submit" type="submit"  value="submit">

and this javascript validates

function onSubmit() 
    var fields = $("input[name='list']").serializeArray(); 
    if (fields.length === 0) 
        alert('nothing selected'); 
        // cancel submit
        return false;
        alert(fields.length + " items selected"); 

// register event on form, not submit button

and you can find a working example of it here

UPDATE (Oct 2012)
Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.

UPDATE (May 2013)
Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)

UPDATE (June 2016)
Changes == to ===

How do I give text or an image a transparent background using CSS?

Almost all these answers assume the designer wants a solid color background. If the designer actually wants a photo as the background the only real solution at the moment is JavaScript like the jQuery Transify plugin mentioned elsewhere.

What we need to do is join the CSS working group discussion and make them give us a background-opacity attribute! It should work hand in hand with the multiple-backgrounds feature.

How to convert jsonString to JSONObject in Java

No need to use any external library.

You can use this class instead :) (handles even lists , nested lists and json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        return null ;

   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        return retMap;

    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key =;
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            map.put(key, value);
        return map;

    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
        return list;

To convert your JSON string to hashmap use this :

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(

Unioning two tables with different number of columns

if only 1 row, you can use join

Select t1.Col1, t1.Col2, t1.Col3, t2.Col4, t2.Col5 from Table1 t1 join Table2 t2;

Compiling a C++ program with gcc

If I recall correctly, gcc determines the filetype from the suffix. So, make it and it should work.

And, to answer your other question, that is the difference between "gcc" and "g++". gcc is a frontend that chooses the correct compiler.

Set initially selected item in Select list in Angular2

Update to angular 4.X.X, there is a new way to mark an option selected:

<select [compareWith]="byId" [(ngModel)]="selectedItem">
  <option *ngFor="let item of items" [ngValue]="item">{{}}

byId(item1: ItemModel, item2: ItemModel) {
  return ===;

Some tutorial here

Visual Studio : short cut Key : Duplicate Line

In Visual Studio 2010 you copy the entire line the cursor is on with CTRL + INSERT then you can use Ctrl + V or SHIFT + INSERT to paste it.

How to make image hover in css?

You're setting the background of the image to another image. Which is fine, but the foreground (SRC attribute of the IMG) still overlays everything else.

.nkhome a {
    display:block; /* Necessary, since A is not a block element */
.nkhome a:hover {

<div class="nkhome">
    <a href="Home.html"></a>

What is the Java ?: operator called and what does it do?

condition ? truth : false;

If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.

It is called the Conditional Operator and it is a type of Ternary Operation.

How can I change my Cygwin home folder after installation?

I happen to use cwRsync (Cygwin + Rsync for Windows) where cygwin comes bundled, and I couldn't find /etc/passwd.

And it kept saying

Could not create directory '/home/username/.ssh'.
Failed to add the host to the list of known hosts (/home/username/.ssh/known_hosts).

So I wrote a batch file which changed the HOME variable before running rsync. Something like:

set HOME=.
rsync /path1 user@host:/path2

And voila! The .ssh folder appeared in the current working dir, and rsync stopped annoying with rsa fingerprints.

It's a quick hotfix, but later you should change HOME to a more secure location.

How to position one element relative to another with jQuery?

NOTE: This requires jQuery UI (not just jQuery).

You can now use:

    my:        "left top",
    at:        "left bottom",
    of:        this, // or $("#otherdiv")
    collision: "fit"

For fast positioning (jQuery UI/Position).

You can download jQuery UI here.

How to install MySQLdb package? (ImportError: No module named setuptools)


$ su
$ yum install MySQL-python

and it will be installed (MySQLdb).

How to check whether mod_rewrite is enable on server?


<VirtualHost *:80>
    <Directory ...>
        AllowOverride All

sudo a2enmod rewrite
sudo service apache2 restart

How can I make visible an invisible control with jquery? (hide and show not work)

Here's some code I use to deal with this.

First we show the element, which will typically set the display type to "block" via .show() function, and then set the CSS rule to "visible":

jQuery( '.element' ).show().css( 'visibility', 'visible' );

Or, assuming that the class that is hiding the element is called hidden, such as in Twitter Bootstrap, toggleClass() can be useful:

jQuery( '.element' ).toggleClass( 'hidden' );

Lastly, if you want to chain functions, perhaps with fancy with a fading effect, you can do it like so:

jQuery( '.element' ).css( 'visibility', 'visible' ).fadeIn( 5000 );

VBA array sort function?

This is what I use to sort in memory - it can easily be expanded to sort an array.

Sub sortlist()

    Dim xarr As Variant
    Dim yarr As Variant
    Dim zarr As Variant

    xarr = Sheets("sheet").Range("sing col range")
    ReDim yarr(1 To UBound(xarr), 1 To 1)
    ReDim zarr(1 To UBound(xarr), 1 To 1)

    For n = 1 To UBound(xarr)
        zarr(n, 1) = 1
    Next n

    For n = 1 To UBound(xarr) - 1
        y = zarr(n, 1)
        For a = n + 1 To UBound(xarr)
            If xarr(n, 1) > xarr(a, 1) Then
                y = y + 1
                zarr(a, 1) = zarr(a, 1) + 1
            End If
        Next a
        yarr(y, 1) = xarr(n, 1)
    Next n

    y = zarr(UBound(xarr), 1)
    yarr(y, 1) = xarr(UBound(xarr), 1)

    yrng = "A1:A" & UBound(yarr)
    Sheets("sheet").Range(yrng) = yarr

End Sub

For Loop on Lua

By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:


names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end


names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end

Way1 uses the table index/key , on your table names each element has a key starting from 1, for example:

names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John

So you just make i go from 1 to 3.

On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:

names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end

prints the following:

1   John
2   Joe
myKey   myValue

How to pass an ArrayList to a varargs method parameter?

You can do:

getMap(locations.toArray(new WorldLocation[locations.size()]));


getMap(locations.toArray(new WorldLocation[0]));


getMap(new WorldLocation[locations.size()]);

@SuppressWarnings("unchecked") is needed to remove the ide warning.

Why is 22 the default port number for SFTP?

From Wikipedia:

Applications implementing common services often use specifically reserved, well-known port numbers for receiving service requests from client hosts. This process is known as listening and involves the receipt of a request on the well-known port and reestablishing one-to-one server-client communications on another private port, so that other clients may also contact the well-known service port. The well-known ports are defined by convention overseen by the Internet Assigned Numbers Authority (IANA).


So as others mentioned, it's a convention.

Execute php file from another php

exec is shelling to the operating system, and unless the OS has some special way of knowing how to execute a file, then it's going to default to treating it as a shell script or similar. In this case, it has no idea how to run your php file. If this script absolutely has to be executed from a shell, then either execute php passing the filename as a parameter, e.g

exec ('/usr/local/bin/php -f /opt/lampp/htdocs/.../name.php)') ;

or use the punct at the top of your php script

<?php ... ?>

Eclipse C++: Symbol 'std' could not be resolved

What allowed me to fix the problem was going to: Project -> Properties -> C/C++ General -> Preprocessor Include Paths, Macros, etc. -> Providers -> CDT GCC built-in compiler settings, enabling that and disabling the CDT Cross GCC Built-in Compiler Settings

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

You don't need to specify the module path per se. CMake ships with its own set of built-in find_package scripts, and their location is in the default CMAKE_MODULE_PATH.

The more normal use case for dependent projects that have been CMakeified would be to use CMake's external_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE_MODULE_PATH in order to find the subproject at the system level.

How to activate a specific worksheet in Excel?

An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link. You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab 'Place in this document' and select the tab you want to activate. If you would click the text (that is now a link) the configured sheet will become active/selected.

Change input value onclick button - pure javascript or jQuery

using html5 data attribute...

try this


Product price: $<span id="product_price">500</span>

<br>Total price: $500
<input type="button" data-quantity="2" value="2&#x00A;Qty">
<input type="button" data-quantity="4" class="mnozstvi_sleva" value="4&#x00A;Qty">
<input type="text" id="count" value="1">


$('input:button').click(function () {
  $('#count').val($(this).data('quantity') * $('#product_price').text());

fiddle here

Is there a built-in function to print all the current properties and values of an object?

def dump(obj):
  for attr in dir(obj):
    print("obj.%s = %r" % (attr, getattr(obj, attr)))

There are many 3rd-party functions out there that add things like exception handling, national/special character printing, recursing into nested objects etc. according to their authors' preferences. But they all basically boil down to this.

Twitter Bootstrap carousel different height images cause bouncing arrows

This jQuery function worked best for me. I'm using bootstrap 4 within a WordPress theme and I've used the full jQuery instead of jQuery slim.

// Set all carousel items to the same height
function carouselNormalization() {

    window.heights = [], //create empty array to store height values
    window.tallest; //create variable to make note of the tallest slide

    function normalizeHeights() {
        jQuery('#latest-blog-posts .carousel-item').each(function() { //add heights to array
        window.tallest = Math.max.apply(null, window.heights); //cache largest value
        jQuery('#latest-blog-posts .carousel-item').each(function() {
            jQuery(this).css('min-height',tallest + 'px');

    jQuery(window).on('resize orientationchange', function () {

        window.tallest = 0, window.heights.length = 0; //reset vars
        jQuery('.sc_slides .item').each(function() {
            jQuery(this).css('min-height','0'); //reset min-height

        normalizeHeights(); //run it again 



jQuery( document ).ready(function() {


Grep regex NOT containing string

patterns[1]="1\.2\.3\.4.*Has exploded"
patterns[2]="5\.6\.7\.8.*Has died"
patterns[3]="\!9\.10\.11\.12.*Has exploded"

for i in {1..3}
grep "${patterns[$i]}" logfile.log

should be the the same as

egrep "(1\.2\.3\.4.*Has exploded|5\.6\.7\.8.*Has died)" logfile.log | egrep -v "9\.10\.11\.12.*Has exploded"    

Why don’t my SVG images scale using the CSS "width" property?

The transform CSS property lets you rotate, scale, skew, or translate an element.

So you can easily use the transform: scale(2.5); option to scale 2.5 times for example.

how to convert binary string to decimal?

        var num = 10;

        alert("Binary " + num.toString(2));   //1010
        alert("Octal " + num.toString(8));    //12
        alert("Hex " + num.toString(16));     //a

        alert("Binary to Decimal "+ parseInt("1010", 2));  //10
        alert("Octal to Decimal " + parseInt("12", 8));    //10
        alert("Hex to Decimal " + parseInt("a", 16));      //10

javascript scroll event for iPhone/iPad?

Since iOS 8 came out, this problem does not exist any more. The scroll event is now fired smoothly in iOS Safari as well.

So, if you register the scroll event handler and check window.pageYOffset inside that event handler, everything works just fine.

How to manually install a pypi module without pip/easy_install?

Even though Sheena's answer does the job, pip doesn't stop just there.

From Sheena's answer:

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing
  4. If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
  5. type in python install

At the end of this, you'll end up with a .egg file in site-packages. As a user, this shouldn't bother you. You can import and uninstall the package normally. However, if you want to do it the pip way, you can continue the following steps.

In the site-packages directory,

  1. unzip <.egg file>
  2. rename the EGG-INFO directory as <pkg>-<version>.dist-info
  3. Now you'll see a separate directory with the package name, <pkg-directory>
  4. find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
  5. find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD. The >> is to prevent overwrite.

Now, looking at the site-packages directory, you'll never realize you installed without pip. To uninstall, just do the usual pip uninstall <pkg>.

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Well there's the Network Connections preference page; you can add proxies there. I don't know much about it; I don't know if the Maven integration plugins will use the proxies defined there.

You can find it at Window...Preferences, then General...Network Connections.

How to use MD5 in javascript to transmit a password

I would suggest you to use CryptoJS in this case.

Basically CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.

So In case you want calculate hash(MD5) of your password string then do as follows :

<script src=""></script>
    var passhash = CryptoJS.MD5(password).toString();

      { user: username, pass: passhash },
      'json' );

So this script will post hash of your password string to the server.

For further info and support on other hash calculating algorithms you can visit at:

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

SQL Server 2005 Using DateAdd to add a day to a date

The following query i have used in sql-server 2008, it may be help you.

For add day  DATEADD(DAY,20,GETDATE())

*20 is the day quantity

In STL maps, is it better to use map::insert than []?

Now in c++11 I think that the best way to insert a pair in a STL map is:

typedef std::map<int, std::string> MyMap;
MyMap map;

auto& result = map.emplace(3,"Hello");

The result will be a pair with:

  • First element (result.first), points to the pair inserted or point to the pair with this key if the key already exist.

  • Second element (result.second), true if the insertion was correct or false it something went wrong.

PS: If you don´t case about the order you can use std::unordered_map ;)


how to set radio option checked onload with jQuery

I liked the answer by @Amc. I found the expression could be condensed further to not use a filter() call (@chaiko apparently also noticed this). Also, prop() is the way to go vs attr() for jQuery v1.6+, see the jQuery documentation for prop() for the official best practices on the subject.

Consider the same input tags from @Paolo Bergantino's answer.

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

The updated one-liner might read something like:

$('input:radio[name="gender"][value="Male"]').prop('checked', true);

Magento: get a static block as html in a phtml file

In the layout (app/design/frontend/your_theme/layout/default.xml):

    <cms_page> <!-- need to be redefined for your needs -->
        <reference name="content">
            <block type="cms/block" name="cms_newest_product" as="cms_newest_product">
                <action method="setBlockId"><block_id>newest_product</block_id></action>

In your phtml template:

<?php echo $this->getChildHtml('newest_product'); ?>

Don't forget about cache cleaning.

I think it help.

How can I get the average (mean) of selected columns

Try using rowMeans:

z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)

  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

How to get names of enum entries?

I found this question by searching "TypeScript iterate over enum keys". So I just want to post solution which works for me in my case. Maybe it'll help to someone too.

My case is the following: I want to iterate over each enum key, then filter some keys, then access some object which has keys as computed values from enum. So this is how I do it without having any TS error.

    enum MyEnum = { ONE = 'ONE', TWO = 'TWO' }
    const LABELS = {
       [MyEnum.ONE]: 'Label one',
       [MyEnum.TWO]: 'Label two'

    // to declare type is important - otherwise TS complains on LABELS[type]
    // also, if replace Object.values with Object.keys - 
    // - TS blames wrong types here: "string[] is not assignable to MyEnum[]"
    const allKeys: Array<MyEnum> = Object.values(MyEnum)

    const allowedKeys = allKeys.filter(
      (type) => type !== MyEnum.ONE

    const allowedLabels = => ({
      label: LABELS[type]

CSS way to horizontally align table

This should work:

<div style="text-align:center;">
  <table style="margin: 0 auto;">
    <!-- table markup here. -->

Angular ng-click with call to a controller function not working

Use alias when defining Controller in your angular configuration. For example: NOTE: I'm using TypeScript here

Just take note of the Controller, it has an alias of homeCtrl.

module MongoAngular {
    var app = angular.module('mongoAngular', ['ngResource', 'ngRoute','restangular']);

        '$routeProvider', ($routeProvider: ng.route.IRouteProvider) => {
                .when('/Home', {
                    templateUrl: '/PartialViews/Home/home.html',
                    controller: 'HomeController as homeCtrl'
                .otherwise({ redirectTo: '/Home' });
        .config(['RestangularProvider', (restangularProvider: restangular.IProvider) => {

And here's the way to use it...


Try it.. It might work for you as it worked for me... ;)

Add a column to existing table and uniquely number them on MS SQL Server

This will depend on the database but for SQL Server, this could be achieved as follows:

alter table Example
add NewColumn int identity(1,1)

Finding the second highest number in array

This java program help to find second highest number in any given array. First we have to get highest value and then we have to go second one.

class Demo{
    public static void main(String args[]){
        int arr[]={321,321,321,43,65,234,56,-1,4,45,-67};
        int max=arr[0];
        int len=arr.length;
        for(int i=0;i<len;i++){

        System.out.println("Max value is "+max);

        int secMax=arr[0];
        for(int j=0;j<len;j++){
                else if(secMax>arr[j]){

            else if(max==arr[j]){

                System.out.println("Sec Max value is "+secMax);


'mat-form-field' is not a known element - Angular 5 & Material2

Check the namespace from where we are importing

import { MatDialogModule } from **"@angular/material/dialog";**
import { MatCardModule } from **"@angular/material/card";**
import { MatButtonModule } from **"@angular/material/button";**

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

How to execute the start script with Nodemon

I have a TypeScript file called "server.ts", The following npm scripts configures Nodemon and npm to start my app and monitor for any changes on TypeScript files:

"start": "nodemon -e ts  --exec \"npm run myapp\"",
"myapp": "tsc -p . && node server.js",

I already have Nodemon on dependencies. When I run npm start, it will ask Nodemon to monitor its files using the -e switch and then it calls the myapp npm script which is a simple combination of transpiling the typescript files and then starting the resulting server.js. When I change the TypeScript file, because of -e switch the same cycle happens and new .js files will be generated and executed.

How to dynamically insert a <script> tag via jQuery after page load?

Try the following:

<script type="text/javascript">
// Use any event to append the code
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "http://scriptlocation/das.js";
    // Use any selector

How to print all information from an HTTP request to the screen, in PHP

in addition, you can use get_headers(). it doesn't depend on apache..


How to find current transaction level?

DECLARE   @UserOptions TABLE(SetOption varchar(100), Value varchar(100))
DECLARE   @IsolationLevel varchar(100)

INSERT    @UserOptions

SELECT    @IsolationLevel = Value
FROM      @UserOptions
WHERE     SetOption = 'isolation level'

-- Do whatever you want with the variable here...  
PRINT     @IsolationLevel

How do I concatenate strings and variables in PowerShell?

I just want to bring another way to do this using .NET String.Format:

$name = "Slim Shady"
Write-Host ([string]::Format("My name is {0}", $name))

How do I remove documents using Node.js Mongoose?

You can always use Mongoose built-in function:

var id = req.params.friendId; //here you pass the id
   .then(function(doc) {
       return doc;
    }).catch(function(error) {
       throw error;

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   '',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):


header('Content-type: application/xml');
echo file_get_contents("");


Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:


$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('');
  file_put_contents($cacheName, $contents);

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;


Caching code take from here.

Python dict how to create key or append an element to key?

Use dict.setdefault():



        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

Woocommerce get products

Always use tax_query to get posts/products from a particular category or any other taxonomy. You can also get the products using ID/slug of particular taxonomy...

$the_query = new WP_Query( array(
    'post_type' => 'product',
    'tax_query' => array(
        array (
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => 'accessories',
) );

while ( $the_query->have_posts() ) :
    the_title(); echo "<br>";


Check if a varchar is a number (TSQL)

ISNUMERIC will not do - it tells you that the string can be converted to any of the numeric types, which is almost always a pointless piece of information to know. For example, all of the following are numeric, according to ISNUMERIC:

£, $, 0d0

If you want to check for digits and only digits, a negative LIKE expression is what you want:

not Value like '%[^0-9]%'

The type arguments for method cannot be inferred from the usage

I wanted to make a simple and understandable example

if you call a method like this, your client will not know return type

var interestPoints = Mediator.Handle(new InterestPointTypeRequest
                LanguageCode = request.LanguageCode,
                AgentId = request.AgentId,
                InterestPointId = request.InterestPointId,

Then you should say to compiler i know the return type is List<InterestPointTypeMap>

var interestPoints  = Mediator.Handle<List<InterestPointTypeMap>>(new InterestPointTypeRequest
                LanguageCode = request.LanguageCode,
                AgentId = request.AgentId,
                InterestPointId = request.InterestPointId,
                InterestPointTypeId = request.InterestPointTypeId

the compiler will no longer be mad at you for knowing the return type

What is an unsigned char?

Some googling found this, where people had a discussion about this.

An unsigned char is basically a single byte. So, you would use this if you need one byte of data (for example, maybe you want to use it to set flags on and off to be passed to a function, as is often done in the Windows API).

ExecuteNonQuery: Connection property has not been initialized.

A couple of things wrong here.

  1. Do you really want to open and close the connection for every single log entry?

  2. Shouldn't you be using SqlCommand instead of SqlDataAdapter?

  3. The data adapter (or SqlCommand) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).

I highly recommend a C# / SQL Server tutorial.

Add a new line to the end of a JtextArea

Are you using JTextArea's append(String) method to add additional text?

JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");

select2 onchange event only works once

This is due because of the items id being the same. On change fires only if a different item id is detected on select.

So you have 2 options: First is to make sure that each items have a unique id when retrieving datas from ajax.

Second is to trigger a rand number at formatSelection for the selected item.

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;


formatSelection: function(item) { =getRandomInt(1,200)}

Changing element style attribute dynamically using JavaScript

I change css style in Javascript function.

But Uncaught TypeError: bild is null .

If I run it in a normal html file it work.


  var text = document.getElementById("text");
var bild = document.getElementById("bild");
var container = document.getElementById("container");["background-image"] = "url('stock-bild-portrait-of-confident-senior-business-woman-standing-in-office-with-her-arms-crossed-mature-female-1156978234.jpg')";
// = "url('stock-bild-portrait-of-confident-senior-business-woman-standing-in-office-with-her-arms-crossed-mature-female-1156978234.jpg')";

 //["background-image"] =  "url('" +  defaultpic + "')";
 alert (["background-image"]) ;["background-size"] = "300px";["background-repeat"] = "no-repeat";["background-position"] = "center";["border-radius"] = "50%";["background-clip"] = "border-box";["transition"] = "background-size 0.2s";["transition-timing-function"] = "cubic-bezier(.07,1.41,.82,1.41)";["display"] = "block";["width"] = "100px";["height"] = "100px";["text-decoration"] = "none";["cursor"] = "pointer";["overflow"] = "hidden";["text-indent"] = "100%";["white-space"] = "nowrap";["position"] = "relative";["font-family"] = "Arial";["position"] = "center";["bottom"] = "5px";["left"] = "1px";["color"] = "white";

APT command line interface-like yes/no input?

As a programming noob, I found a bunch of the above answers overly complex, especially if the goal is to have a simple function that you can pass various yes/no questions to, forcing the user to select yes or no. After scouring this page and several others, and borrowing all of the various good ideas, I ended up with the following:

def yes_no(question_to_be_answered):
    while True:
        choice = input(question_to_be_answered).lower()
        if choice[:1] == 'y': 
            return True
        elif choice[:1] == 'n':
            return False
            print("Please respond with 'Yes' or 'No'\n")

#See it in Practice below 

musical_taste = yes_no('Do you like Pine Coladas?')
if musical_taste == True:
    print('and getting caught in the rain')
elif musical_taste == False:
    print('You clearly have no taste in music')

Node.js console.log() not logging anything

Using modern --inspect with node the console.log is captured and relayed to the browser.

node --inspect myApp.js

or to capture early logging --inspect-brk can be used to stop the program on the first line of the first module...

node --inspect-brk myApp.js

CentOS: Copy directory to another directory

To copy all files, including hidden files use:

cp -r /home/server/folder/test/. /home/server/

document.getElementById("test").style.display="hidden" not working

It should be either

document.getElementById("test").style.display = "none";


document.getElementById("test").style.visibility = "hidden";

Second option will display some blank space where the form was initially present , where as the first option doesn't

How do you generate a random double uniformly distributed between 0 and 1 from C++?

An old school solution like:

double X=((double)rand()/(double)RAND_MAX);

Should meet all your criteria (portable, standard and fast). obviously the random number generated has to be seeded the standard procedure is something like:


Open Source Javascript PDF viewer

There is an open source HTML5/javascript reader available called Trapeze though its still in its early stages.

Demo site:

Github page:

Disclaimer: I'm the author.

jquery clone div and append it after specific div

You can use clone, and then since each div has a class of car_well you can use insertAfter to insert after the last div.


How to compare two NSDates: Which is more recent?

I have encounter almost same situation, but in my case I'm checking if number of days difference

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *compDate = [cal components:NSDayCalendarUnit fromDate:fDate toDate:tDate options:0];
int numbersOfDaysDiff = [compDate day]+1; // do what ever comparison logic with this int.

Useful when you need to compare NSDate in Days/Month/Year unit

Import MySQL database into a MS SQL Server

I suggest you to use mysqldump like so:

mysqldump --compatible=mssql

phpMyAdmin is still a web-app and could potentially have some limitations for large databases (script execution time, allocatable memory and so on).

how to pass command line arguments to main method dynamically

Run ---> Debug Configuration ---> YourConfiguration ---> Arguments tab

enter image description here

Call removeView() on the child's parent first

You can also do it by checking if View's indexOfView method if indexOfView method returns -1 then we can use.

ViewGroup's detachViewFromParent(v); followed by ViewGroup's removeDetachedView(v, true/false);

Create a temporary table in a SELECT statement without a separate CREATE TABLE


From the manual found at

You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.) To create temporary tables, you must have the CREATE TEMPORARY TABLES privilege.

How do you implement a Stack and a Queue in JavaScript?

There are quite a few ways in which you can implement Stacks and Queues in Javascript. Most of the answers above are quite shallow implementations and I would try to implement something more readable (using new syntax features of es6) and robust.

Here's the stack implementation:

class Stack {
    this._items = []

      items.forEach(item => this._items.push(item) )


    //push item to the stack
     items.forEach(item => this._items.push(item) )
     return this._items;


    //pull out the topmost item (last item) from stack
      return this._items.pop()
       return this._items.splice( -count, count )

    // see what's the last item in stack
    return this._items[this._items.length-1]

    //no. of items in stack
    return this._items.length

    // return whether the stack is empty or not
    return this._items.length==0

    return this._items;

And this is how you can use the stack :

let my_stack = new Stack(1,24,4);
// [1, 24, 4]
//[1, 24, 4, 23]
//[1, 24, 4, 23, 1, 2, 342]
//[1, 24, 4, 23, 1, 2]
//[1, 24, 4]
// false

If you would like to see the detailed description about this implementation and how it can be further improved, you can read here :

Here's the code for queue implementation in es6 :

class Queue{
   //initialize the items in queue
   this._items = []
   // enqueuing the items passed to the constructor

    //push items into the queue
    items.forEach( item => this._items.push(item) )
    return this._items;

    //pull out the first item from the queue
    return this._items;

    //peek at the first item from the queue
    return this._items[0]

    //get the length of queue
    return this._items.length

    //find whether the queue is empty or no
    return this._items.length===0

Here's how you can use this implementation:

let my_queue = new Queue(1,24,4);
// [1, 24, 4]
//[1, 24, 4, 23]
//[1, 24, 4, 23, 1, 2, 342]
//[24, 4, 23, 1, 2, 342]
//[1, 2, 342]
// false

To go through the complete tutorial of how these data structures have been implemented and how can these further be improved, you may want to go through the 'Playing with data structures in javascript' series at . Here's the links for queues -

JDK was not found on the computer for NetBeans 6.5

For netbeans 8.2

1. First run command as administrator.
2. set path to you downloads folder using cd 'location to the downloads folder'
3. extract using netbeans-8.2-windows.exe --extract command
4. run java -jar bundle.jar
5. Done :)

Convert DataSet to List

Try something like this:

var empList = ds.Tables[0].AsEnumerable()
    .Select(dataRow => new Employee
        Name = dataRow.Field<string>("Name")

What does <T> denote in C#

It is a Generic Type Parameter.

A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.

For example:

public T[] Reverse<T>(T[] array)
    var result = new T[array.Length];
    int j=0;
    for(int i=array.Length - 1; i>= 0; i--)
        result[j] = array[i];
    return result;

reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.

So, to reverse an array of strings:

string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);

Will produce a string array in result of { "5", "4", "3", "2", "1" }

This has the same effect as if you had called an ordinary (non-generic) method that looks like this:

public string[] Reverse(string[] array)
    var result = new string[array.Length];
    int j=0;
    for(int i=array.Length - 1; i >= 0; i--)
        result[j] = array[i];
    return result;

The compiler sees that array contains strings, so it returns an array of strings. Type string is substituted for the T type parameter.

Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>, the T is a placeholder for an arbitrary type; it means that SampleCollection can represent a collection of objects, the type of which you specify when you create the collection.


var collection = new SampleCollection<string>();

creates a collection that can hold strings. The Reverse method illustrated above, in a somewhat different form, can be used to reverse the collection's members.

Executing Javascript code "on the spot" in Chrome?

You can use bookmarklets if you want run bigger scripts in more convenient way and run them automatically by one click.

When does Java's Thread.sleep throw InterruptedException?

The InterruptedException is usually thrown when a sleep is interrupted.

Get current time in hours and minutes

date +%H:%M

Would be easier, I think :). If you really wanted to chop off the seconds, you could have done

date | sed 's/.* \([0-9]*:[0-9]*\):[0-9]*.*/\1/'

How to insert a column in a specific position in oracle without dropping and recreating the table?

You (still) can not choose the position of the column using ALTER TABLE: it can only be added to the end of the table. You can obviously select the columns in any order you want, so unless you are using SELECT * FROM column order shouldn't be a big deal.

If you really must have them in a particular order and you can't drop and recreate the table, then you might be able to drop and recreate columns instead:-

First copy the table

CREATE TABLE my_tab_temp AS SELECT * FROM my_tab;

Then drop columns that you want to be after the column you will insert


Now add the new column (two in this example) and the ones you removed.

ALTER TABLE my_tab ADD (two NUMBER(2), three NUMBER(10));

Lastly add back the data for the re-created columns

UPDATE my_tab SET my_tab.three = (SELECT my_tab_temp.three FROM my_tab_temp WHERE =;

Obviously your update will most likely be more complex and you'll have to handle indexes and constraints and won't be able to use this in some cases (LOB columns etc). Plus this is a pretty hideous way to do this - but the table will always exist and you'll end up with the columns in a order you want. But does column order really matter that much?

how to make div click-able?

The simplest of them all:

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

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    var a = call['a'], b = call['b']
    if(a == null || b == null) {
        result = false

Place input box at the center of div

You can just use either of the following approaches:

.center-block {
  margin: auto;
  display: block;
  <input class="center-block">

.parent {
  display: grid;
  place-items: center;
<div class="parent">

How to replace case-insensitive literal substrings in Java

For non-Unicode characters:

String result = Pattern.compile("(?i)????????", 

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

Executing a shell script from a PHP script

Without really knowing the complexity of the setup, I like the sudo route. First, you must configure sudo to permit your webserver to sudo run the given command as root. Then, you need to have the script that the webserver shell_exec's(testscript) run the command with sudo.

For A Debian box with Apache and sudo:

  1. Configure sudo:

    • As root, run the following to edit a new/dedicated configuration file for sudo:

      visudo -f /etc/sudoers.d/Webserver

      (or whatever you want to call your file in /etc/sudoers.d/)

    • Add the following to the file:

      www-data ALL = (root) NOPASSWD: <executable_file_path>

      where <executable_file_path> is the command that you need to be able to run as root with the full path in its name(say /bin/chown for the chown executable). If the executable will be run with the same arguments every time, you can add its arguments right after the executable file's name to further restrict its use.

      For example, say we always want to copy the same file in the /root/ directory, we would write the following:

      www-data ALL = (root) NOPASSWD: /bin/cp /root/test1 /root/test2
  2. Modify the script(testscript):

    Edit your script such that sudo appears before the command that requires root privileges(say sudo /bin/chown ... or sudo /bin/cp /root/test1 /root/test2). Make sure that the arguments specified in the sudo configuration file exactly match the arguments used with the executable in this file. So, for our example above, we would have the following in the script:

    sudo /bin/cp /root/test1 /root/test2

If you are still getting permission denied, the script file and it's parent directories' permissions may not allow the webserver to execute the script itself. Thus, you need to move the script to a more appropriate directory and/or change the script and parent directory's permissions to allow execution by www-data(user or group), which is beyond the scope of this tutorial.

Keep in mind:

When configuring sudo, the objective is to permit the command in it's most restricted form. For example, instead of permitting the general use of the cp command, you only allow the cp command if the arguments are, say, /root/test1 /root/test2. This means that cp's arguments(and cp's functionality cannot be altered).

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

How to make HTML element resizable using pure Javascript?

There are very good examples here to start trying with, but all of them are based on adding some extra or external element like a "div" as a reference element to drag it, and calculate the new dimensions or position of the original element.

Here's an example that doesn't use any extra elements. We could add borders, padding or margin without affecting its operation. In this example we have not added color, nor any visual reference to the borders nor to the lower right corner as a clue where you can enlarge or reduce dimensions, but using the cursor around the resizable elements the clues appears!

let resizerForCenter = new Resizer('center')  

See it in action with CodeSandbox:

In this example we use ES6, and a module that exports a class called Resizer. An example is worth a thousand words:

Edit boring-snow-qz1sd

Or with the code snippet:

const html = document.querySelector('html')_x000D_
class Resizer {_x000D_
 constructor(elemId) {_x000D_
  this._elem = document.getElementById(elemId)_x000D_
   * Stored binded context handlers for method passed to eventListeners!_x000D_
   * _x000D_
   * See:
  this._checkBorderHandler = this._checkBorder.bind(this)_x000D_
  this._doResizeHandler  = this._doResize.bind(this)_x000D_
  this._initResizerHandler = this.initResizer.bind(this)_x000D_
  this._onResizeHandler  = this._onResize.bind(this)_x000D_
 initResizer() {_x000D_
 _beginResizer() {_x000D_
  this._elem.addEventListener('mousemove', this._checkBorderHandler, false)_x000D_
 stopResizer() {_x000D_ = 'default'_x000D_ = 'default'_x000D_
  window.removeEventListener('mousemove', this._doResizeHandler, false)_x000D_
  window.removeEventListener('mouseup', this._initResizerHandler, false)_x000D_
  this._elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
  this._elem.removeEventListener('mousemove', this._checkBorderHandler, false)_x000D_
 _doResize(e) {_x000D_
  let elem = this._elem_x000D_
  let boxSizing = getComputedStyle(elem).boxSizing_x000D_
  let borderRight = 0_x000D_
  let borderLeft = 0_x000D_
  let borderTop = 0_x000D_
  let borderBottom = 0_x000D_
  let paddingRight = 0_x000D_
  let paddingLeft = 0_x000D_
  let paddingTop = 0_x000D_
  let paddingBottom = 0_x000D_
  switch (boxSizing) {_x000D_
   case 'content-box':_x000D_
     paddingRight = parseInt(getComputedStyle(elem).paddingRight)_x000D_
     paddingLeft = parseInt(getComputedStyle(elem).paddingLeft)_x000D_
     paddingTop = parseInt(getComputedStyle(elem).paddingTop)_x000D_
     paddingBottom = parseInt(getComputedStyle(elem).paddingBottom)_x000D_
   case 'border-box':_x000D_
     borderRight = parseInt(getComputedStyle(elem).borderRight)_x000D_
     borderLeft = parseInt(getComputedStyle(elem).borderLeft)_x000D_
     borderTop = parseInt(getComputedStyle(elem).borderTop)_x000D_
     borderBottom = parseInt(getComputedStyle(elem).borderBottom)_x000D_
   default: break_x000D_
  let horizontalAdjustment = (paddingRight + paddingLeft) - (borderRight + borderLeft)_x000D_
  let verticalAdjustment  = (paddingTop + paddingBottom) - (borderTop + borderBottom)_x000D_
  let newWidth = elem.clientWidth  + e.movementX - horizontalAdjustment + 'px'_x000D_
  let newHeight = elem.clientHeight + e.movementY - verticalAdjustment   + 'px'_x000D_
  let cursorType = getComputedStyle(elem).cursor_x000D_
  switch (cursorType) {_x000D_
   case 'all-scroll':_x000D_ = newWidth_x000D_ = newHeight_x000D_
   case 'col-resize':_x000D_ = newWidth_x000D_
   case 'row-resize':_x000D_ = newHeight_x000D_
   default: break_x000D_
 _onResize(e) {_x000D_
  // On resizing state!_x000D_
  let elem = e.target_x000D_
  let newCursorType = undefined_x000D_
  let cursorType = getComputedStyle(elem).cursor_x000D_
  switch (cursorType) {_x000D_
   case 'nwse-resize':_x000D_
    newCursorType = 'all-scroll'_x000D_
   case 'ew-resize':_x000D_
    newCursorType = 'col-resize'_x000D_
   case 'ns-resize':_x000D_
    newCursorType = 'row-resize'_x000D_
   default: break_x000D_
  _x000D_ = newCursorType // Avoid cursor's flickering _x000D_ = newCursorType_x000D_
  // Remove what is not necessary, and could have side effects!_x000D_
  elem.removeEventListener('mousemove', this._checkBorderHandler, false);_x000D_
  // Events on resizing state_x000D_
   * We do not apply the mousemove event on the elem to resize it, but to the window to prevent the mousemove from slippe out of the elem to resize. This work bc we calculate things based on the mouse position_x000D_
  window.addEventListener('mousemove', this._doResizeHandler, false);_x000D_
  window.addEventListener('mouseup', this._initResizerHandler, false);_x000D_
 _checkBorder(e) {_x000D_
  const elem = e.target_x000D_
  const borderSensitivity = 5_x000D_
  const coor = getCoordenatesCursor(e)_x000D_
  const onRightBorder  = ((coor.x + borderSensitivity) > elem.scrollWidth)_x000D_
  const onBottomBorder = ((coor.y + borderSensitivity) > elem.scrollHeight)_x000D_
  const onBottomRightCorner = (onRightBorder && onBottomBorder)_x000D_
  if (onBottomRightCorner) {_x000D_ = 'nwse-resize'_x000D_
  } else if (onRightBorder) {_x000D_ = 'ew-resize'_x000D_
  } else if (onBottomBorder) {_x000D_ = 'ns-resize'_x000D_
  } else {_x000D_ = 'auto'_x000D_
  if (onRightBorder || onBottomBorder) {_x000D_
   elem.addEventListener('mousedown', this._onResizeHandler, false)_x000D_
  } else {_x000D_
   elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
function getCoordenatesCursor(e) {_x000D_
 let elem =;_x000D_
 // Get the Viewport-relative coordinates of cursor._x000D_
 let viewportX = e.clientX_x000D_
 let viewportY = e.clientY_x000D_
 // Viewport-relative position of the target element._x000D_
 let elemRectangle = elem.getBoundingClientRect()_x000D_
 // The  function returns the largest integer less than or equal to a given number._x000D_
 let x = Math.floor(viewportX - elemRectangle.left) // - elem.scrollWidth_x000D_
 let y = Math.floor(viewportY - // - elem.scrollHeight_x000D_
 return {x, y}_x000D_
let resizerForCenter = new Resizer('center')_x000D_
let resizerForLeft = new Resizer('left')_x000D_
setTimeout(handler, 10000, true); // 10s_x000D_
function handler() {_x000D_
body {_x000D_
 background-color: white;_x000D_
#wrapper div {_x000D_
 /* box-sizing: border-box; */_x000D_
 position: relative;_x000D_
 overflow: hidden;_x000D_
 height: 50px;_x000D_
 width: 50px;_x000D_
 padding: 3px;_x000D_
#left {_x000D_
 background-color: blueviolet;_x000D_
#center {_x000D_
 background-color:lawngreen ;_x000D_
#right {_x000D_
 background: blueviolet;_x000D_
#wrapper {_x000D_
 border: 5px solid hotpink;_x000D_
 display: inline-block;_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
 <meta charset="UTF-8">_x000D_
 <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
 <meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
 <title>Resizer v0.0.1</title>_x000D_
    <div id="wrapper">_x000D_
      <div id="left">Left</div>_x000D_
      <div id="center">Center</div>_x000D_
      <div id="right">Right</div>_x000D_

PHP, Get tomorrows date from date

 $tomorrow = date("Y-m-d", strtotime('tomorrow'));


  $tomorrow = date("Y-m-d", strtotime("+1 day"));

Help Link: STRTOTIME()

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

FTP protocol may be blocked by your ISP firewall, try connecting via SFTP (i.e. use 22 for port num instead of 21 which is simply FTP).

For more information try this link.

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

To handle the situation in which there is no wiring, beans are available with @Autowired required attribute set to false.

But when using @Inject, the Provider interface works with the bean which means that the bean is not injected directly but with the Provider.

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

You can try max-height: 70px; See if that works.

How to let PHP to create subdomain automatically for each user?

You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.

Java/Groovy - simple date reformatting

Your DateFormat pattern does not match you input date String. You could use

new SimpleDateFormat("dd-MMM-yyyy")

Array inside a JavaScript Object?

Kill the braces.

var defaults = {
 backgroundcolor: '#000',
 color: '#fff',
 weekdays: ['sun','mon','tue','wed','thu','fri','sat']

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

I wrote my self a helper method to get patterns for this.

public static String getPattern(int month) {
    String first = "MMMM dd";
    String last = ", yyyy";
    String pos = (month == 1 || month == 21 || month == 31) ? "'st'" : (month == 2 || month == 22) ? "'nd'" : (month == 3 || month == 23) ? "'rd'" : "'th'";
    return first + pos + last;

and then we can call it as

LocalDate localDate =;//For reference
int month = localDate.getDayOfMonth();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(getPattern(month));
String date = localDate.format(formatter);

the output is

December 12th, 2018

Decompile Python 2.7 .pyc

UPDATE (2019-04-22) - It sounds like you want to use uncompyle6 nowadays rather than the answers I had mentioned originally.

This sounds like it works:

Issue 8 says it supports 2.7:

UPDATE (2013-09-03) - As noted in the comments and in other answers, you should look at or instead of unpyc.

Wi-Fi Direct and iOS Support

It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.

Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.

It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."

Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.

There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.

Can't create handler inside thread which has not called Looper.prepare()

You create handler in background thread this way

private void createHandler() {
        Thread thread = new Thread() {
          public void run() {

               final Handler handler = new Handler();
               handler.postDelayed(new Runnable() {
                    public void run() {
                       // Do Work
                }, 2000);


Difference between request.getSession() and request.getSession(true)

A major practical difference is its use:

in security scenario where we always needed a new session, we should use request.getSession(true).

request.getSession(false): will return null if no session found.

How do you add an image?

Just to clarify the problem here - the error is in the following bit of code:

<xsl:attribute name="src">
    <xsl:copy-of select="/root/Image/node()"/>

The instruction xsl:copy-of takes a node or node-set and makes a copy of it - outputting a node or node-set. However an attribute cannot contain a node, only a textual value, so xsl:value-of would be a possible solution (as this returns the textual value of a node or nodeset).

A MUCH shorter solution (and perhaps more elegant) would be the following:

<img width="100" height="100" src="{/root/Image/node()}" class="CalloutRightPhoto"/>

The use of the {} in the attribute is called an Attribute Value Template, and can contain any XPATH expression.

Note, the same XPath can be used here as you have used in the xsl_copy-of as it knows to take the textual value when used in a Attribute Value Template.

Callback when CSS3 transition finishes

Another option would be to use the jQuery Transit Framework to handle your CSS3 transitions. The transitions/effects perform well on mobile devices and you don't have to add a single line of messy CSS3 transitions in your CSS file in order to do the animation effects.

Here is an example that will transition an element's opacity to 0 when you click on it and will be removed once the transition is complete:

$("#element").click( function () {
    $('#element').transition({ opacity: 0 }, function () { $(this).remove(); });

JS Fiddle Demo

Bootstrap 3 modal vertical position center

A simple way. Work for me. Thks rensdenobel :)

.vertical-alignment-helper {
    height: 100%;
    width: 100%;
.vertical-align-center {
    /* To center vertically */
    display: table-cell;
    vertical-align: middle;
.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    /* To center horizontally */
    margin: 0 auto;
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="vertical-alignment-helper">
        <div class="modal-dialog vertical-align-center">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>

                     <h4 class="modal-title" id="myModalLabel">Modal title</h4>

                <div class="modal-body">...</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>

How to open the default webbrowser using java

java.awt.Desktop is the class you're looking for.

import java.awt.Desktop;

// ...

if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
    Desktop.getDesktop().browse(new URI(""));

get unique machine id

I'd stay well away from using MAC addresses. On some hardware, the MAC address can change when you reboot. We learned quite early during our research not to rely on it.

Take a look at the article Developing for Software Protection and Licensing which has some pointers on how to design & implement apps to reduce piracy.

Obligatory disclaimer & plug: the company I co-founded produces the OffByZero Cobalt licensing solution. So it probably won't surprise you to hear that I recommend outsourcing your licensing, & focusing on your core competencies.

How to access route, post, get etc. parameters in Zend Framework 2

The easisest way to get a posted json string, for example, is to read the contents of 'php://input' and then decode it. For example i had a simple Zend route:

'save-json' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
            'options' => array(
                'route'    => '/save-json/',
                'defaults' => array(
                    'controller' => 'CDB\Controller\Index',
                    'action'     => 'save-json',

and i wanted to post data to it using Angular's $ The post was fine but the retrive method in Zend


didn't get anything in this case. So my solution was, after trying all kinds of methods like $_POST and the other methods stated above, to read from 'php://':

$content = file_get_contents('php://input');

I got my json array in the end. Hope this helps.

How can I do an OrderBy with a dynamic string parameter?

Another solution from codeConcussion (

var param = "Address";    
var pi = typeof(Student).GetProperty(param);    
var orderByAddress = items.OrderBy(x => pi.GetValue(x, null));

Randomize a List<T>

EDIT The RemoveAt is a weakness in my previous version. This solution overcomes that.

public static IEnumerable<T> Shuffle<T>(
        this IEnumerable<T> source,
        Random generator = null)
    if (generator == null)
        generator = new Random();

    var elements = source.ToArray();
    for (var i = elements.Length - 1; i >= 0; i--)
        var swapIndex = generator.Next(i + 1);
        yield return elements[swapIndex];
        elements[swapIndex] = elements[i];

Note the optional Random generator, if the base framework implementation of Random is not thread-safe or cryptographically strong enough for your needs, you can inject your implementation into the operation.

A suitable implementation for a thread-safe cryptographically strong Random implementation can be found in this answer.

Here's an idea, extend IList in a (hopefully) efficient way.

public static IEnumerable<T> Shuffle<T>(this IList<T> list)
    var choices = Enumerable.Range(0, list.Count).ToList();
    var rng = new Random();
    for(int n = choices.Count; n > 1; n--)
        int k = rng.Next(n);
        yield return list[choices[k]];

    yield return list[choices[0]];

Reading a UTF8 CSV file with Python

Using as Alex Martelli suggested proved to be useful to me.

import codecs

delimiter = ';'
reader ="your_filename.csv", 'r', encoding='utf-8')
for line in reader:
    row = line.split(delimiter)
    # do something with your row ...

extract digits in a simple way from a python string

>>> x='$120'
>>> import string
>>> a=string.maketrans('','')
>>> ch=a.translate(a, string.digits)
>>> int(x.translate(a, ch))

Doctrine2: Best way to handle many-to-many with extra columns in reference table

This really useful example. It lacks in the documentation doctrine 2.

Very thank you.

For the proxies functions can be done :

class AlbumTrack extends AlbumTrackAbstract {
   ... proxy method.
   function getTitle() {} 

class TrackAlbum extends AlbumTrackAbstract {
   ... proxy method.
   function getTitle() {}

class AlbumTrackAbstract {
   private $id;


/** @OneToMany(targetEntity="TrackAlbum", mappedBy="album") */
protected $tracklist;

/** @OneToMany(targetEntity="AlbumTrack", mappedBy="track") */
protected $albumsFeaturingThisTrack;

Error when deploying an artifact in Nexus

Ensure that not exists already (artifact and version) in nexus (as release). In that case return Bad Request.

How do I unlock a SQLite database?

If you want to remove a "database is locked" error then follow these steps:

  1. Copy your database file to some other location.
  2. Replace the database with the copied database. This will dereference all processes which were accessing your database file.

View's SELECT contains a subquery in the FROM clause

Looks to me as MySQL 3.6 gives the following error while MySQL 3.7 no longer errors out. I am yet to find anything in the documentation regarding this fix.

Set default host and port for ng serve in config file

You can configure the default HTTP port and the one used by the LiveReload server with two command-line options :

ng serve --host --port 4201 --live-reload-port 49153

How to add RSA key to authorized_keys file?

>ssh user@serverip -p portnumber 
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys

json_decode to array

This will also change it into an array:

    print_r((array) json_decode($object));

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Paths specified with a . are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js but not if you run node folder/app.js. The only exception to this is require('./file') and that is only possible because require exists per-module and thus knows what module it is being called from.

To make a path relative to the script, you must use the __dirname variable.

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

path.join(__dirname, 'path', 'to', 'file')

Why does my Eclipse keep not responding?

I had similar symptoms recently. Turned out it was caused by the Subversion server being unavailable - once that was restarted I was able to right-click. My environment was Eclipse Luna with Subclipse.

So worth checking that any connected source control systems are operational. Hope that helps.

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:


Up next is the create script. Creating a database file:


SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);


After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.

How to disable JavaScript in Chrome Developer Tools?

Full and fast instructions for Chrome browsers (Opera incl.)

The first way

  1. If Developer Tools aren't open then press F12 key on keyboard to show the Developer Tools. In Opera browser you have to use key combination Ctrl + Shift + i on keyboard to open it.
  2. To show the settings just press F1 key on keyboard. The Developer Tools window must be focused when you are doing it. Or if you want to open the settings with the mouse then you have to click on ? button in the top right corner of the Developer Tools, then click Settings in the menu.

Then you have to scroll down the settings window to bottom and then you will see the checkbox for disabling JavaScript like follows:

disable JavaScript in chrome developer tools

Just click on this checkbox and push esc key on keyboard for hide the settings. If you want to enable it then you have to do the same way again.

The second way

  1. If Developer Tools aren't open then open it like in the first way is described.
  2. Press the key combination Ctrl + Shift + P (for Windows or Linux) or Cmd (?) + Shift + P (for Mac) to open the Command Menu. Be sure that the focus is on the DevTools window.
  3. Type there "Disable JavaScript" and then press Enter or click it with the mouse. If you want to turn back the enanled JS then open the Command Menu again and type there "Enable JavaScript" and then press Enter or click it with the mouse. You could also write just only "JavaScript" or "Java" there and then choose it with the mouse.

disable JavaScript in chrome developer tools

If all this does not work

For some reason it is possible that it does not work. I this case open a new empty site in "Incognito Mode" and do all this there.

The quickest way

In Chrome Web Store or on Opera Addon site you can find and install extensions which do it per one click. Just search "Javascript Switcher":

Android Studio - How to Change Android SDK Path

I'm guessing from the responses that people aren't understanding your question... If I'm right in that you want to have ~\Desktop\github\ then changing the SDK location isn't what you're after.

From Android Studio 3.2.1: From the new project dialog, choose Configure -> Preferences -> Tools -> Terminal -> Start Directory

Put the folder you want as your project default in the field.

e.g. Mine is set to ~/Desktop/github/ since all my work is in ~/Desktop/github/

CSS: image link, change on hover

<!DOCTYPE html>
<html lang="en">
<title>Change Image on Hover in CSS</title>
<style type="text/css">
    .card {
        width: 130px;
        height: 195px;
        background: url("../images/pic.jpg") no-repeat;
        margin: 50px;
    .card:hover {
        background: url("../images/anotherpic.jpg") no-repeat;
    <div class="card"></div>

Difference between DOMContentLoaded and load events

The DOMContentLoaded event will fire as soon as the DOM hierarchy has been fully constructed, the load event will do it when all the images and sub-frames have finished loading.

DOMContentLoaded will work on most modern browsers, but not on IE including IE9 and above. There are some workarounds to mimic this event on older versions of IE, like the used on the jQuery library, they attach the IE specific onreadystatechange event.

What exactly is LLVM?

LLVM (used to mean "Low Level Virtual Machine" but not anymore) is a compiler infrastructure, written in C++, which is designed for compile-time, link-time, run-time, and "idle-time" optimization of programs written in arbitrary programming languages. Originally implemented for C/C++, the language-independent design (and the success) of LLVM has since spawned a wide variety of front-ends, including Objective C, Fortran, Ada, Haskell, Java bytecode, Python, Ruby, ActionScript, GLSL, and others.

Read this for more explanation
Also check out Unladen Swallow

How to install pip for Python 3.6 on Ubuntu 16.10?

In at least in ubuntu 16.10, the default python3 is python3.5. As such, all of the python3-X packages will be installed for python3.5 and not for python3.6.

You can verify this by checking the shebang of pip3:

$ head -n1 $(which pip3)

Fortunately, the pip installed by the python3-pip package is installed into the "shared" /usr/lib/python3/dist-packages such that python3.6 can also take advantage of it.

You can install packages for python3.6 by doing:

python3.6 -m pip install ...

For example:

$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'

Hidden Features of Xcode

Select a block of text and type cmd-/ to comment it out. Do it again to remove the comments characters.

This is especially useful when combined with brace-matching by double-clicking on balanced chars (parens, braces, brackets).

get everything between <tag> and </tag> with php

function contentDisplay($text)
    //replace UTF-8
    $convertUT8 = array("\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\x93", "\xe2\x80\x94", "\xe2\x80\xa6");
    $to = array("'", "'", '"', '"', '-', '--', '...');
    $text = str_replace($convertUT8,$to,$text);

    //replace Windows-1252
    $convertWin1252 = array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133));
    $to = array("'", "'", '"', '"', '-', '--', '...');
    $text = str_replace($convertWin1252,$to,$text);

    //replace accents
    $convertAccents = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'Ð', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', '?', '?', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', '?', '?', 'L', 'l', 'N', 'n', 'N', 'n', 'N', 'n', '?', 'O', 'o', 'O', 'o', 'O', 'o', 'Œ', 'œ', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'Š', 'š', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Ÿ', 'Z', 'z', 'Z', 'z', 'Ž', 'ž', '?', 'ƒ', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', '?', '?', '?', '?', '?', '?');
    $to = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
    $text = str_replace($convertAccents,$to,$text);

    //Encode the characters
    $text = htmlentities($text);

    //normalize the line breaks (here because it applies to all text)
    $text = str_replace("\r\n", "\n", $text);
    $text = str_replace("\r", "\n", $text);

    //decode the <code> tags
    $codeOpen = htmlentities('<').'code'.htmlentities('>');
    if (strpos($text, $codeOpen))
        $text = str_replace($codeOpen, html_entity_decode(htmlentities('<')) . "code" . html_entity_decode(htmlentities('>')), $text);
    $codeOpen = htmlentities('<').'/code'.htmlentities('>');
    if (strpos($text, $codeOpen))
        $text = str_replace($codeOpen, html_entity_decode(htmlentities('<')) . "/code" . html_entity_decode(htmlentities('>')), $text);

    //match everything between <code> and </code>, the msU is what makes this work here, ADD this to REGEX archive
    $regex = '/<code>(.*)<\/code>/msU';
    $code = preg_match($regex, $text, $matches);
    if ($code == 1)
        if (is_array($matches) && count($matches) >= 2)
            $newcode = $matches[1];

            $newcode = nl2br($newcode);

    //remove <code>and this</code> from $text;
    $text = str_replace('<code>' . $matches[1] . '</code>', 'PLACEHOLDERCODE1', $text);

    //convert the line breaks to paragraphs
    $text = '<p>' . str_replace("\n\n", '</p><p>', $text) . '</p>';
    $text = str_replace("\n" , '<br />', $text);
    $text = str_replace('</p><p>', '</p>' . "\n\n" . '<p>', $text);

    $text = str_replace('PLACEHOLDERCODE1', '<code>'.$newcode.'</code>', $text);
        $code = false;

    if ($code == false)
        //convert the line breaks to paragraphs
        $text = '<p>' . str_replace("\n\n", '</p><p>', $text) . '</p>';
        $text = str_replace("\n" , '<br />', $text);
        $text = str_replace('</p><p>', '</p>' . "\n\n" . '<p>', $text);

    return $text;

How to get parameters from the URL with JSP

Use EL (JSP Expression Language):


How do I pretty-print existing JSON data with Java?

In one line:

String niceFormattedJson = JsonWriter.formatJson(jsonString)



The json-io libray ( is a small (75K) library with no other dependencies than the JDK.

In addition to pretty-printing JSON, you can serialize Java objects (entire Java object graphs with cycles) to JSON, as well as read them in.

start/play embedded (iframe) youtube-video on click of an image

Html Code:-

<a href="#" id="playerID">Play</a>
<iframe src="" class="embed-responsive-item" data-play="0" id="VdoID" ></iframe>

Jquery Code:-

    var videoURL = $('#VdoID').attr('src'),
    dataplay = $('#VdoID').attr('data-play');

    //for check autoplay
    //if not set autoplay=1
    if(dataplay == 0 ){
        var videoURL = $('#VdoID').attr('src');
        videoURL = videoURL.replace("?autoplay=1", "");



Thats It!

Passing array in GET for a REST call

As @Ravi_MCA mentioned, /users?ids[]=id1&ids[]=id2 worked for me, too.

When you want to send an array through PATCH or POST method, it's better to use JSON or XML. (I use JSON)
In HTTP Request body you should follow like this:

{"params":["arg1", "arg2", ...]}

You can even use JSON object instead of array.

Can I change the headers of the HTTP request sent by the browser?

I don't think it's possible to do it in the way you are trying to do it.

Indication of the accepted data format is usually done through adding the extension to the resource name. So, if you have resource like


and GET /resources/resource returns its HTML representation, to indicate that you want its XML representation instead, you can use following pattern:


You have to do the accepted content type determination magic on the server side, then.

Or use Javascript as James suggests.

Laravel Eloquent: Ordering results of all()

Try this:

$categories     =   Category::all()->sortByDesc("created_at");

ng-if check if array is empty

To overcome the null / undefined issue, try using the ? operator to check existence:

<p ng-if="post?.capabilities?.items?.length > 0">
  • Sidenote, if anyone got to this page looking for an Ionic Framework answer, ensure you use *ngIf:

    <p *ngIf="post?.capabilities?.items?.length > 0">

IOCTL Linux device driver

An ioctl, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.

An alternative is the sysfs interface, where you set up a file under /sys/ and read/write that to get information from and to the driver. An example of how to set this up:

static ssize_t mydrvr_version_show(struct device *dev,
        struct device_attribute *attr, char *buf)
    return sprintf(buf, "%s\n", DRIVER_RELEASE);

static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);

And during driver setup:

device_create_file(dev, &dev_attr_version);

You would then have a file for your device in /sys/, for example, /sys/block/myblk/version for a block driver.

Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl or libnl3 libraries.

CSS two div width 50% in one line with line break in file

The problem you run into when setting width to 50% is the rounding of subpixels. If the width of your container is i.e. 99 pixels, a width of 50% can result in 2 containers of 50 pixels each.

Using float is probably easiest, and not such a bad idea. See this question for more details on how to fix the problem then.

If you don't want to use float, try using a width of 49%. This will work cross-browser as far as I know, but is not pixel-perfect..


<div id="a">A</div>
<div id="b">B</div>


#a, #b {
    width: 49%;
    display: inline-block; 
#a {background-color: red;}
#b {background-color: blue;}

Delete dynamically-generated table row using jQuery

I know this is old but I've used a function similar to this...

deleteRow: function (ctrl) {

    //remove the row from the table


... with markup like this ...

<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>

...and it works fine

Inserting a value into all possible locations in a list

Coming from JavaScript, this was something I was used to having "built-in" via Array.prototype.splice(), so I made a Python function that does the same:

def list_splice(target, start, delete_count=None, *items):
    """Remove existing elements and/or add new elements to a list.

    target        the target list (will be changed)
    start         index of starting position
    delete_count  number of items to remove (default: len(target) - start)
    *items        items to insert at start index

    Returns a new list of removed items (or an empty list)
    if delete_count == None:
        delete_count = len(target) - start

    # store removed range in a separate list and replace with *items
    total = start + delete_count
    removed = target[start:total]
    target[start:total] = items

    return removed

Can I dispatch an action in reducer?

You might try using a library like redux-saga. It allows for a very clean way to sequence async functions, fire off actions, use delays and more. It is very powerful!

When are static variables initialized?

From See Java Static Variable Methods:

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object.

Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them. Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.

What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.

In case of inner classes, they can not have static fields

An inner class is a nested class that is not explicitly or implicitly declared static.


Inner classes may not declare static initializers (§8.7) or member interfaces...

Inner classes may not declare static members, unless they are constant variables...

See JLS 8.1.3 Inner Classes and Enclosing Instances

final fields in Java can be initialized separately from their declaration place this is however can not be applicable to static final fields. See the example below.

final class Demo
    private final int x;
    private static final int z;  //must be initialized here.

        z = 10;  //It can be initialized here.

    public Demo(int x)
        this.x=x;  //This is possible.
        //z=15; compiler-error - can not assign a value to a final variable z

This is because there is just one copy of the static variables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initialize z of type static final within the constructor, it will attempt to reinitialize the static final type field z because the constructor is run on each instantiation of the class that must not occur to static final fields.

How to deal with page breaks when printing a large HTML table

I ended up following @vicenteherrera's approach, with some tweaks (that are possibly bootstrap 3 specific).

Basically; we can't break trs, or tds because they're not block-level elements. So we embed divs into each, and apply our page-break-* rules against the div. Secondly; we add some padding to the top of each of these divs, to compensate for any styling artifacts.

    @media print {
        /* avoid cutting tr's in half */
        th div, td div {
        // Wrap each tr and td's content within a div
        // (todo: add logic so we only do this when printing)
        $("table tbody th, table tbody td").wrapInner("<div></div>");

The margin and padding adjustments were necessary to offset some kind of jitter that was being introduced (by my guess - from bootstrap). I'm not sure that I'm presenting any new solution from the other answers to this question, but I figure maybe this will help someone.

How to put a delay on AngularJS instant search?

 <input type="text"
    ng-model ="criteria.searchtext""  
    ng-model-options="{debounce: {'default': 1000, 'blur': 0}}"
    placeholder="Search" >

Now we can set ng-model-options debounce with time and when blur, model need to be changed immediately otherwise on save it will have older value if delay is not completed.

Write Array to Excel Range

You could put your data into a recordset and use Excel's CopyFromRecordset Method - it's much faster than populating cell-by-cell.

You can create a recordset from a dataset using this code. You will have to do some trials to see if using this method is faster than what you are currently doing.

How can I rename a conda environment?

conda should have given us a simple tool like cond env rename <old> <new> but it hasn't. Simply renaming the directory, as in this previous answer, of course, breaks the hardcoded hashbangs(#!). Hence, we need to go one more level deeper to achieve what we want.

conda env list
# conda environments:
base                  *  /home/tgowda/miniconda3
junkdetect               /home/tgowda/miniconda3/envs/junkdetect
rtg                      /home/tgowda/miniconda3/envs/rtg

Here I am trying to rename rtg --> unsup (please bear with those names, this is my real use case)

$ cd /home/tgowda/miniconda3/envs 
$ OLD=rtg
$ NEW=unsup
$ mv $OLD $NEW   # rename dir

$ conda env list
# conda environments:
base                  *  /home/tgowda/miniconda3
junkdetect               /home/tgowda/miniconda3/envs/junkdetect
unsup                    /home/tgowda/miniconda3/envs/unsup

$ conda activate $NEW
$ which python

the previous answer reported upto this, but wait, we are not done yet! the pending task is, $NEW/bin dir has a bunch of executable scripts with hashbangs (#!) pointing to the $OLD env paths.

See jupyter, for example:

$ which jupyter

$ head -1 $(which jupyter) # its hashbang is still looking at old

So, we can easily fix it with a sed

$ sed  -i.bak "s:envs/$OLD/bin:envs/$NEW/bin:" $NEW/bin/*  
# `-i.bak` created backups, to be safe

$ head -1 $(which jupyter) # check if updated
$ jupyter --version # check if it works
jupyter core     : 4.6.3
jupyter-notebook : 6.0.3

$ rm $NEW/bin/*.bak  # remove backups

Now we are done

I think it should be trivial to write a portable script to do all those and bind it to conda env rename old new.

I tested this on ubuntu. For whatever unforseen reasons, if things break and you wish to revert the above changes:

$ mv $NEW  $OLD
$ sed  -i.bak "s:envs/$NEW/bin:envs/$OLD/bin:" $OLD/bin/*

How do I find a list of Homebrew's installable packages?

Please use Homebrew Formulae page to see the list of installable packages.

To install any package => command to use is :

brew install node

How do I correct the character encoding of a file?

Follow these steps with Notepad++

1- Copy the original text

2- In Notepad++, open new file, change Encoding -> pick an encoding you think the original text follows. Try as well the encoding "ANSI" as sometimes Unicode files are read as ANSI by certain programs

3- Paste

4- Then to convert to Unicode by going again over the same menu: Encoding -> "Encode in UTF-8" (Not "Convert to UTF-8") and hopefully it will become readable

The above steps apply for most languages. You just need to guess the original encoding before pasting in notepad++, then convert through the same menu to an alternate Unicode-based encoding to see if things become readable.

Most languages exist in 2 forms of encoding: 1- The old legacy ANSI (ASCII) form, only 8 bits, was used initially by most computers. 8 bits only allowed 256 possibilities, 128 of them where the regular latin and control characters, the final 128 bits were read differently depending on the PC language settings 2- The new Unicode standard (up to 32 bit) give a unique code for each character in all currently known languages and plenty more to come. if a file is unicode it should be understood on any PC with the language's font installed. Note that even UTF-8 goes up to 32 bit and is just as broad as UTF-16 and UTF-32 only it tries to stay 8 bits with latin characters just to save up disk space

Oracle: how to INSERT if a row doesn't exist

You should use Merge: For example:

MERGE INTO employees e
    USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
    ON ( = h.emp_id)
    UPDATE SET e.address = h.address
    INSERT (id, address)
    VALUES (h.emp_id, h.address);


MERGE INTO employees e
    USING hr_records h
    ON ( = h.emp_id)
    UPDATE SET e.address = h.address
    INSERT (id, address)
    VALUES (h.emp_id, h.address);

How to create a Restful web service with input parameters?

Be careful. For this you need @GET (not @PUT).

Variable not accessible when initialized outside function

My guess is that the system-status element is declared after the variable declaration is run. Thus, at the time the variable is declared, it is actually being set to null?

You should declare it only, then assign its value from an onLoad handler instead, because then you will be sure that it has properly initialized (loaded) the element in question.

You could also try putting the script at the bottom of the page (or at least somewhere after the system-status element is declared) but it's not guaranteed to always work.

How can I get my Twitter Bootstrap buttons to right align?

Using the Bootstrap pull-right helper didn't work for us because it uses float: right, which forces inline-block elements to become block. And when the .btns become block, they lose the natural margin that inline-block was providing them as quasi-textual elements.

So instead we used direction: rtl; on the parent element, which causes the text inside that element to layout from right to left, and that causes inline-block elements to layout from right to left, too. You can use LESS like the following to prevent children from being laid out rtl too:

/* Flow the inline-block .btn starting from the right. */
.btn-container-right {
  direction: rtl;

  * {
    direction: ltr;

and use it like:

<div class="btn-container-right">
    <button class="btn">Click Me</button>

What’s the best way to load a JSONObject from a json text file?

On Google'e Gson library, for having a JsonObject, or more abstract a JsonElement:


JsonElement json = JsonParser.parseReader( new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8") );

This is not demanding a given Object structure for receiving/reading the json string.

val() doesn't trigger change() in jQuery

As of feb 2019 .addEventListener() is not currently work with jQuery .trigger() or .change(), you can test it below using Chrome or Firefox.

txt.addEventListener('input', function() {_x000D_
  console.log('not called?');_x000D_
<script src=""></script>_x000D_
<input type="text" id="txt">

you have to use .dispatchEvent() instead.

txt.addEventListener('input', function() {_x000D_
  console.log('it works!');_x000D_
txt.dispatchEvent(new Event('input'));
<script src=""></script>_x000D_
<input type="text" id="txt">

How to create number input field in Flutter?

You can try this:

     keyboardType: TextInputType.number,
     decoration: InputDecoration(
              prefixIcon: Text("Enter your number: ")
     initialValue: "5",
     onSaved: (input) => _value = num.tryParse(input),

How to retrieve a module's path?

This was trivial.

Each module has a __file__ variable that shows its relative path from where you are right now.

Therefore, getting a directory for the module to notify it is simple as:


Find size of Git repository

The git command

git count-objects -v

will give you a good estimate of the git repository's size. Without the -v flag, it only tells you the size of your unpacked files. This command may not be in your $PATH, you may have to track it down (on Ubuntu I found it in /usr/lib/git-core/, for instance).

From the Git man-page:

-v, --verbose

In addition to the number of loose objects and disk space consumed, it reports the number of in-pack objects, number of packs, disk space consumed by those packs, and number of objects that can be removed by running git prune-packed.

Your output will look similar to the following:

count: 1910
size: 19764
in-pack: 41814
packs: 3
size-pack: 1066963
prune-packable: 1
garbage: 0

The line you're looking for is size-pack. That is the size of all the packed commit objects, or the smallest possible size for the new cloned repository.

What is the equivalent to getLastInsertId() in Cakephp?

this is best way to find out last inserted id.


other way is using

$this->ModelName->find('first',array('order'=>'id DESC')) 

How to do multiple arguments to map function where one remains the same in python?

If you really really need to use map function (like my class assignment here...), you could use a wrapper function with 1 argument, passing the rest to the original one in its body; i.e. :

extraArguments = value
def myFunc(arg):
    # call the target function
    return Func(arg, extraArguments)

map(myFunc, itterable)

Dirty & ugly, still does the trick

SQL how to make null values come last when sorting ascending

order by coalesce(date-time-field,large date in future)

How do I print out the contents of an object in Rails for easy debugging?

pp does the job too, no gem requiring is required.

@a = Accrual.first ; pp @a

 id: 4,
 year: 2018,
 Jan: #<BigDecimal:7ff521e58f08,'0.11E2',9(27)>,
 Feb: #<BigDecimal:7ff521e585d0,'0.88E2',9(27)>,
 Mar: #<BigDecimal:7ff521e58030,'0.0',9(27)>,
 Apr: #<BigDecimal:7ff521e53698,'0.88E2',9(27)>,
 May: #<BigDecimal:7ff521e52fb8,'0.8E1',9(27)>,
 June: #<BigDecimal:7ff521e52900,'0.8E1',9(27)>,
 July: #<BigDecimal:7ff521e51ff0,'0.8E1',9(27)>,
 Aug: #<BigDecimal:7ff521e51bb8,'0.88E2',9(27)>,
 Sep: #<BigDecimal:7ff521e512f8,'0.88E2',9(27)>,
 Oct: #<BigDecimal:7ff521e506c8,'0.0',9(27)>,
 Nov: #<BigDecimal:7ff521e43d38,'0.888E3',9(27)>,
 Dec: #<BigDecimal:7ff521e43478,'0.0',9(27)>,

You can also print two instances of an object:

 pp( Accrual.first , Accrual.second)

A keyboard shortcut to comment/uncomment the select text in Android Studio

At least in Android Studio 2.2.3 with default key mapping, to comment or uncomment a select text, same hotkeys are used as Toggle. Using the hotkeys changes the state from comment to uncomment, and next time Uncomment to comment on next and vice versa.

1. Comment / uncomment a block of code

Comment sample: /* --- Code block ---- */

Hotkey: Ctrl + Shift + "/"

Using the same key combinations again will "toggle" commenting or uncommenting the selection.

2. Comment / uncomment a line of code

Comment sample: // -- Code ---

Hotkey: Ctrl + "/"

Using the same key combinations again will "toggle" commenting or uncommenting the selection.

Note: Key mapping can be changed to different schemes like eclipse, visual studio... or to the custom hotkeys in File -> Settings -> Keymap

Rails has_many with alias name

You could also use alias_attribute if you still want to be able to refer to them as tasks as well:

class User < ActiveRecord::Base
  alias_attribute :jobs, :tasks

  has_many :tasks

How can I be notified when an element is added to the page?

Between the deprecation of mutation events and the emergence of MutationObserver, an efficent way to be notified when a specific element was added to the DOM was to exploit CSS3 animation events.

To quote the blog post:

Setup a CSS keyframe sequence that targets (via your choice of CSS selector) whatever DOM elements you want to receive a DOM node insertion event for. I used a relatively benign and little used css property, clip I used outline-color in an attempt to avoid messing with intended page styles – the code once targeted the clip property, but it is no longer animatable in IE as of version 11. That said, any property that can be animated will work, choose whichever one you like.

Next I added a document-wide animationstart listener that I use as a delegate to process the node insertions. The animation event has a property called animationName on it that tells you which keyframe sequence kicked off the animation. Just make sure the animationName property is the same as the keyframe sequence name you added for node insertions and you’re good to go.

How to sort by column in descending order in Spark SQL?

PySpark only

I came across this post when looking to do the same in PySpark. The easiest way is to just add the parameter ascending=False:

df.orderBy("col1", ascending=False).show(10)


ByRef argument type mismatch in Excel VBA

It looks like ByRef needs to know the size of the parameter. A declaration of Dim last_name as string doesn't specify the size of the string so it takes it as an error. Before using Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name) The last_name has to be declared as Dim last_name as string *10 ' size of string is up to you but must be a fix length

No need to change the function. Function doesn't take a fix length declaration.

Remove carriage return from string

You can also try:

string res = string.Join("", sample.Split(Environment.NewLine.ToCharArray())

Environment.NewLine should make it independent of platform.

Recommended Read:

Environment.NewLine Property

Microsoft SQL Server 2005 service fails to start

While that error message is on the screen (before the rollback begins) go to Control Panel -> Administrative Tools -> Services and see if the service is actually installed. Also check what account it is using to run as. If it's not using Local System, then double and triple check that the account it's using has rights to the program directory where MS SQL installed to.

Using 'make' on OS X

I agree with the other two answers: install the Apple Developer Tools.

But it is also worth noting that OS X ships with ant and rake.

java.util.NoSuchElementException: No line found

with Scanner you need to check if there is a next line with hasNextLine()

so the loop becomes


it's readers that return null on EOF

ofcourse in this piece of code this is dependent on whether the input is properly formatted

Is there a limit on how much JSON can hold?

There is no fixed limit on how large a JSON data block is or any of the fields.

There are limits to how much JSON the JavaScript implementation of various browsers can handle (e.g. around 40MB in my experience). See this question for example.

How to redirect to another page using PHP

Just like you used echo to print a webpage. You could use also do the same with redirecting.

print("<script type=\"text/javascript\">location.href=\"urlHere\"</script>")

How do I best silence a warning about unused variables?

I found most of the presented answers work for local unused variable only, and will cause compile error for unused static global variable.

Another macro needed to suppress the warning of unused static global variable.

template <typename T>
const T* UNUSED_VARIABLE(const T& dummy) { 
    return &dummy;
#define UNUSED_GLOBAL_VARIABLE(x) namespace {\
    const auto dummy = UNUSED_VARIABLE(x);\

static int a = 0;

int main ()
    int b = 3;
    return 0;

This works because no warning will be reported for non-static global variable in anonymous namespace.

C++ 11 is required though

 g++  -Wall -O3  -std=c++11 test.cpp

split string in two on given index and return both parts

You can also do it like this.

var str, result;
str = prompt("Enter Any Number");

var valueSplit = function (value, length) {
    if (length < 7) {
        var index = length - 3;
        return str.slice(0, index) + ',' + str.slice(index);
    else if (length < 10 && length > 6) {
        var index1, index2;
        index1 = length - 6;
        index2 = length - 3;
        return str.slice(0,index1) + "," + str.slice(index1,index2) + "," + str.slice(index2);

result = valueSplit(str, str.length);

How to automatically insert a blank row after a group of data

This does exactly what you are asking, checks the rows, and inserts a blank empty row at each change in column A:

sub AddBlankRows()
dim iRow as integer, iCol as integer
dim oRng as range

set oRng=range("a1")


if cells(irow+1, iCol)<>cells(irow,iCol) then
    cells(irow+1,iCol).entirerow.insert shift:=xldown
end if
loop while not cells (irow,iCol).text=""
end sub

I hope that gets you started, let us know!


When creating a service with sc.exe how to pass in context parameters?

I had issues getting this to work on Windows 7. It seemed to ignore the first argument I passed in so I used binPath= "C:\path\to\service.exe -bogusarg -realarg1 -realarg2" and it worked.

What are abstract classes and abstract methods?

With abstract classes you can have some kind of skeleton for other classes to extend.

You can't instantiate them but you can put some common implementation which you can use in the classes that extend them.

How to verify if $_GET exists?

Use and empty() whit negation (for test if not empty)

if(!empty($_GET['id'])) {
    // if get id is not empty

How to use LDFLAGS in makefile

Seems like the order of the linking flags was not an issue in older versions of gcc. Eg gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16) comes with Centos-6.7 happy with linker option before inputfile; but gcc with ubuntu 16.04 gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413 does not allow.

Its not the gcc version alone, I has got something to with the distros

Check whether there is an Internet connection available on Flutter app


  connectivity: ^0.4.2

what we got from resouces is

      import 'package:connectivity/connectivity.dart';

      Future<bool> check() async {
        var connectivityResult = await (Connectivity().checkConnectivity());
        if (connectivityResult == {
          return true;
        } else if (connectivityResult == ConnectivityResult.wifi) {
          return true;
        return false;

Future is little problematic for me, we have to implement it every single time like :

check().then((intenet) {
      if (intenet != null && intenet) {
        // Internet Present Case
      // No-Internet Case

So to solve this problem i have created a class Which accept a function with boolean isNetworkPresent parameter like this

methodName(bool isNetworkPresent){}

And the Utility Class is

import 'package:connectivity/connectivity.dart';

class NetworkCheck {
  Future<bool> check() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == {
      return true;
    } else if (connectivityResult == ConnectivityResult.wifi) {
      return true;
    return false;

  dynamic checkInternet(Function func) {
    check().then((intenet) {
      if (intenet != null && intenet) {

And to use connectivity-check utilty

  fetchPrefrence(bool isNetworkPresent) {



i will use this syntax

NetworkCheck networkCheck = new NetworkCheck();

Creating an Array from a Range in VBA

In addition to solutions proposed, and in case you have a 1D range to 1D array, i prefer to process it through a function like below. The reason is simple: If for any reason your range is reduced to 1 element range, as far as i know the command Range().Value will not return a variant array but just a variant and you will not be able to assign a variant variable to a variant array (previously declared).

I had to convert a variable size range to a double array, and when the range was of 1 cell size, i was not able to use a construct like range().value so i proceed with a function like below.

Public Function Rng2Array(inputRange As Range) As Double()

    Dim out() As Double    
    ReDim out(inputRange.Columns.Count - 1)

    Dim cell As Range
    Dim i As Long
    For i = 0 To inputRange.Columns.Count - 1
        out(i) = inputRange(1, i + 1) 'loop over a range "row"

    Rng2Array = out  
End Function

What is the difference between document.location.href and document.location?

document.location is a synonym for window.location that has been deprecated for almost as long as JavaScript has existed. Don't use it.

location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string. Assigning a string to either is defined to cause the same kind of navigation, so take your pick.

I consider writing to location.href = something to be marginally better as it's slightly more explicit about what it's doing. You generally want to avoid just location = something as it looks misleadingly like a variable assignment. window.location = something is fine though.

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You can't show dialog box ON SERVER from ASP.NET application, well of course tehnically you can do that but it makes no sense since your user is using browser and it can't see messages raised on server. You have to understand how web sites work, server side code (ASP.NET in your case) produces html, javascript etc on server and then browser loads that content and displays it to the user, so in order to present modal message box to the user you have to use Javascript, for example alert function.

Here is the example for :

Move SQL Server 2008 database files to a new folder location

Some notes to complement the ALTER DATABASE process:

1) You can obtain a full list of databases with logical names and full paths of MDF and LDF files:

   USE master SELECT name, physical_name FROM sys.master_files

2) You can move manually the files with CMD move command:

Move "Source" "Destination"


md "D:\MSSQLData"
Move "C:\test\SYSADMIT-DB.mdf" "D:\MSSQLData\SYSADMIT-DB_Data.mdf"
Move "C:\test\SYSADMIT-DB_log.ldf" "D:\MSSQLData\SYSADMIT-DB_log.ldf"

3) You should change the default database path for new databases creation. The default path is obtained from the Windows registry.

You can also change with T-SQL, for example, to set default destination to: D:\MSSQLData

USE [master]


EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', REG_SZ, N'D:\MSSQLData'


EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', REG_SZ, N'D:\MSSQLData'


Extracted from:

Executable directory where application is running from?

You can write the following:

Path.Combine(Path.GetParentDirectory(GetType(MyClass).Assembly.Location), "Images\image.jpg")