Programs & Examples On #Bind

This tag means different things in different contexts: consider using less ambiguous tags instead. Common meanings include: the bind function in socket programming; binding to naming contexts; the bind method in jQuery; BIND the DNS server (named), . For boost::bind in C++, use [boost-bind]. Do not use this tag just to say that you're binding something to something else.

What does it mean to bind a multicast (UDP) socket?

It is also very important to distinguish a SENDING multicast socket from a RECEIVING multicast socket.

I agree with all the answers above regarding RECEIVING multicast sockets. The OP noted that binding a RECEIVING socket to an interface did not help. However, it is necessary to bind a multicast SENDING socket to an interface.

For a SENDING multicast socket on a multi-homed server, it is very important to create a separate socket for each interface you want to send to. A bound SENDING socket should be created for each interface.

  // This is a fix for that bug that causes Servers to pop offline/online.
  // Servers will intermittently pop offline/online for 10 seconds or so.
  // The bug only happens if the machine had a DHCP gateway, and the gateway is no longer accessible.
  // After several minutes, the route to the DHCP gateway may timeout, at which
  // point the pingponging stops.
  // You need 3 machines, Client machine, server A, and server B
  // Client has both ethernets connected, and both ethernets receiving CITP pings (machine A pinging to en0, machine B pinging to en1)
  // Now turn off the ping from machine B (en1), but leave the network connected.
  // You will notice that the machine transmitting on the interface with
  // the DHCP gateway will fail sendto() with errno 'No route to host'
  if ( theErr == 0 )
  {
     // inspired by 'ping -b' option in man page:      
     //      -b boundif
     //             Bind the socket to interface boundif for sending.
     struct sockaddr_in bindInterfaceAddr;
     bzero(&bindInterfaceAddr, sizeof(bindInterfaceAddr));
     bindInterfaceAddr.sin_len = sizeof(bindInterfaceAddr);
     bindInterfaceAddr.sin_family = AF_INET;
     bindInterfaceAddr.sin_addr.s_addr = htonl(interfaceipaddr);
     bindInterfaceAddr.sin_port = 0; // Allow the kernel to choose a random port number by passing in 0 for the port.
     theErr = bind(mSendSocketID, (struct sockaddr *)&bindInterfaceAddr, sizeof(bindInterfaceAddr));
     struct sockaddr_in serverAddress;
     int namelen = sizeof(serverAddress);  
     if (getsockname(mSendSocketID, (struct sockaddr *)&serverAddress, (socklen_t *)&namelen) < 0) {
        DLogErr(@"ERROR Publishing service... getsockname err");
     }
     else
     {
        DLog( @"socket %d bind, %@ port %d", mSendSocketID, [NSString stringFromIPAddress:htonl(serverAddress.sin_addr.s_addr)], htons(serverAddress.sin_port) );
     }

Without this fix, multicast sending will intermittently get sendto() errno 'No route to host'. If anyone can shed light on why unplugging a DHCP gateway causes Mac OS X multicast SENDING sockets to get confused, I would love to hear it.

Cannot assign requested address using ServerSocket.socketBind

In my case, delete from /etc/hosts

  • 127.0.0.1 localhost
  • 192.168.100.20 localhost <<<<---- (delete or comment)

jQuery how to bind onclick event to dynamically added HTML element

It is possible and sometimes necessary to create the click event along with the element. This is for example when selector based binding is not an option. The key part is to avoid the problem that Tobias was talking about by using .replaceWith() on a single element. Note that this is just a proof of concept.

<script>
    // This simulates the object to handle
    var staticObj = [
        { ID: '1', Name: 'Foo' },
        { ID: '2', Name: 'Foo' },
        { ID: '3', Name: 'Foo' }
    ];
    staticObj[1].children = [
        { ID: 'a', Name: 'Bar' },
        { ID: 'b', Name: 'Bar' },
        { ID: 'c', Name: 'Bar' }
    ];
    staticObj[1].children[1].children = [
        { ID: 'x', Name: 'Baz' },
        { ID: 'y', Name: 'Baz' }
    ];

    // This is the object-to-html-element function handler with recursion
    var handleItem = function( item ) {
        var ul, li = $("<li>" + item.ID + " " + item.Name + "</li>");

        if(typeof item.children !== 'undefined') {
            ul = $("<ul />");
            for (var i = 0; i < item.children.length; i++) {
                ul.append(handleItem(item.children[i]));
            }
            li.append(ul);
        }

        // This click handler actually does work
        li.click(function(e) {
            alert(item.Name);
            e.stopPropagation();
        });
        return li;
    };

    // Wait for the dom instead of an ajax call or whatever
    $(function() {
        var ul = $("<ul />");

        for (var i = 0; i < staticObj.length; i++) {
            ul.append(handleItem(staticObj[i]));
        }

        // Here; this works.
        $('#something').replaceWith(ul);
    });
</script>
<div id="something">Magical ponies ?</div>

Update Angular model after setting input value with jQuery

I've written this little plugin for jQuery which will make all calls to .val(value) update the angular element if present:

(function($, ng) {
  'use strict';

  var $val = $.fn.val; // save original jQuery function

  // override jQuery function
  $.fn.val = function (value) {
    // if getter, just return original
    if (!arguments.length) {
      return $val.call(this);
    }

    // get result of original function
    var result = $val.call(this, value);

    // trigger angular input (this[0] is the DOM object)
    ng.element(this[0]).triggerHandler('input');

    // return the original result
    return result; 
  }
})(window.jQuery, window.angular);

Just pop this script in after jQuery and angular.js and val(value) updates should now play nice.


Minified version:

!function(n,t){"use strict";var r=n.fn.val;n.fn.val=function(n){if(!arguments.length)return r.call(this);var e=r.call(this,n);return t.element(this[0]).triggerHandler("input"),e}}(window.jQuery,window.angular);

Example:

_x000D_
_x000D_
// the function_x000D_
(function($, ng) {_x000D_
  'use strict';_x000D_
  _x000D_
  var $val = $.fn.val;_x000D_
  _x000D_
  $.fn.val = function (value) {_x000D_
    if (!arguments.length) {_x000D_
      return $val.call(this);_x000D_
    }_x000D_
    _x000D_
    var result = $val.call(this, value);_x000D_
    _x000D_
    ng.element(this[0]).triggerHandler('input');_x000D_
    _x000D_
    return result;_x000D_
    _x000D_
  }_x000D_
})(window.jQuery, window.angular);_x000D_
_x000D_
(function(ng){ _x000D_
  ng.module('example', [])_x000D_
    .controller('ExampleController', function($scope) {_x000D_
      $scope.output = "output";_x000D_
      _x000D_
      $scope.change = function() {_x000D_
        $scope.output = "" + $scope.input;_x000D_
      }_x000D_
    });_x000D_
})(window.angular);_x000D_
_x000D_
(function($){  _x000D_
  $(function() {_x000D_
    var button = $('#button');_x000D_
  _x000D_
    if (button.length)_x000D_
      console.log('hello, button');_x000D_
    _x000D_
    button.click(function() {_x000D_
      var input = $('#input');_x000D_
      _x000D_
      var value = parseInt(input.val());_x000D_
      value = isNaN(value) ? 0 : value;_x000D_
      _x000D_
      input.val(value + 1);_x000D_
    });_x000D_
  });_x000D_
})(window.jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div ng-app="example" ng-controller="ExampleController">_x000D_
  <input type="number" id="input" ng-model="input" ng-change="change()" />_x000D_
  <span>{{output}}</span>_x000D_
  <button id="button">+</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to enable named/bind/DNS full logging?

I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:

logging {
    channel default_file {
        file "/var/log/named/default.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel general_file {
        file "/var/log/named/general.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel database_file {
        file "/var/log/named/database.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel security_file {
        file "/var/log/named/security.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel config_file {
        file "/var/log/named/config.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel resolver_file {
        file "/var/log/named/resolver.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-in_file {
        file "/var/log/named/xfer-in.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-out_file {
        file "/var/log/named/xfer-out.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel notify_file {
        file "/var/log/named/notify.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel client_file {
        file "/var/log/named/client.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel unmatched_file {
        file "/var/log/named/unmatched.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel queries_file {
        file "/var/log/named/queries.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel network_file {
        file "/var/log/named/network.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel update_file {
        file "/var/log/named/update.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dispatch_file {
        file "/var/log/named/dispatch.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dnssec_file {
        file "/var/log/named/dnssec.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel lame-servers_file {
        file "/var/log/named/lame-servers.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };

    category default { default_file; };
    category general { general_file; };
    category database { database_file; };
    category security { security_file; };
    category config { config_file; };
    category resolver { resolver_file; };
    category xfer-in { xfer-in_file; };
    category xfer-out { xfer-out_file; };
    category notify { notify_file; };
    category client { client_file; };
    category unmatched { unmatched_file; };
    category queries { queries_file; };
    category network { network_file; };
    category update { update_file; };
    category dispatch { dispatch_file; };
    category dnssec { dnssec_file; };
    category lame-servers { lame-servers_file; };
};

Hope this helps.

Understanding ASP.NET Eval() and Bind()

For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind.

Imagine for example a GridView with a ItemTemplate and EditItemTemplate. If you use Bind or Eval in the ItemTemplate, there will be no difference. If you use Eval in the EditItemTemplate, the value will not be able to be passed to the Update method of the DataSource that the grid is bound to.


UPDATE: I've come up with this example:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Data binding demo</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView 
            ID="grdTest" 
            runat="server" 
            AutoGenerateEditButton="true" 
            AutoGenerateColumns="false" 
            DataSourceID="mySource">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox 
                            ID="edtName" 
                            runat="server" 
                            Text='<%# Bind("Name") %>' 
                        />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>

    <asp:ObjectDataSource 
        ID="mySource" 
        runat="server"
        SelectMethod="Select" 
        UpdateMethod="Update" 
        TypeName="MyCompany.CustomDataSource" />
</body>
</html>

And here's the definition of a custom class that serves as object data source:

public class CustomDataSource
{
    public class Model
    {
        public string Name { get; set; }
    }

    public IEnumerable<Model> Select()
    {
        return new[] 
        {
            new Model { Name = "some value" }
        };
    }

    public void Update(string Name)
    {
        // This method will be called if you used Bind for the TextBox
        // and you will be able to get the new name and update the
        // data source accordingly
    }

    public void Update()
    {
        // This method will be called if you used Eval for the TextBox
        // and you will not be able to get the new name that the user
        // entered
    }
}

Docker Error bind: address already in use

docker-compose down --rmi all 

and then restart your computer

jQuery Event Keypress: Which key was pressed?

If you are using jQuery UI you have translations for common key codes. In ui/ui/ui.core.js:

$.ui.keyCode = { 
    ...
    ENTER: 13, 
    ...
};

There's also some translations in tests/simulate/jquery.simulate.js but I could not find any in the core JS library. Mind you, I merely grep'ed the sources. Maybe there is some other way to get rid of these magic numbers.

You can also make use of String.charCodeAt and .fromCharCode:

>>> String.charCodeAt('\r') == 13
true
>>> String.fromCharCode(13) == '\r'
true

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

I would do something like:

$(documento).on('click', '#answer', function() {
  feedback('hey there');
});

What is the use of the JavaScript 'bind' method?

Variables has local and global scopes. Let's suppose that we have two variables with the same name. One is globally defined and the other is defined inside a function closure and we want to get the variable value which is inside the function closure. In that case we use this bind() method. Please see the simple example below:

_x000D_
_x000D_
var x = 9; // this refers to global "window" object here in the browser_x000D_
var person = {_x000D_
  x: 81,_x000D_
  getX: function() {_x000D_
    return this.x;_x000D_
  }_x000D_
};_x000D_
_x000D_
var y = person.getX; // It will return 9, because it will call global value of x(var x=9)._x000D_
_x000D_
var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81)._x000D_
_x000D_
document.getElementById("demo1").innerHTML = y();_x000D_
document.getElementById("demo2").innerHTML = x2();
_x000D_
<p id="demo1">0</p>_x000D_
<p id="demo2">0</p>
_x000D_
_x000D_
_x000D_

Identify duplicates in a List

This should work for sorted and unsorted.

public void testFindDuplicates() {

    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(3);
    list.add(3);

    Set<Integer> result = new HashSet<Integer>();
    int currentIndex = 0;
    for (Integer i : list) {
        if (!result.contains(i) && list.subList(currentIndex + 1, list.size()).contains(i)) {
            result.add(i);
        }
        currentIndex++;
    }
    assertEquals(2, result.size());
    assertTrue(result.contains(1));
    assertTrue(result.contains(3));
}

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

IndexOf function in T-SQL

CHARINDEX is what you are looking for

select CHARINDEX('@', '[email protected]')
-----------
8

(1 row(s) affected)

-or-

select CHARINDEX('c', 'abcde')
-----------
3

(1 row(s) affected)

Android runOnUiThread explanation

Instead of creating a thread, and using runOnUIThread, this is a perfect job for ASyncTask:

  • In onPreExecute, create & show the dialog.

  • in doInBackground prepare the data, but don't touch the UI -- store each prepared datum in a field, then call publishProgress.

  • In onProgressUpdate read the datum field & make the appropriate change/addition to the UI.

  • In onPostExecute dismiss the dialog.


If you have other reasons to want a thread, or are adding UI-touching logic to an existing thread, then do a similar technique to what I describe, to run on UI thread only for brief periods, using runOnUIThread for each UI step. In this case, you will store each datum in a local final variable (or in a field of your class), and then use it within a runOnUIThread block.

How do I convert a float number to a whole number in JavaScript?

var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue ); 
var intvalue = Math.round( floatvalue );

// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );

Math object reference


Examples

Positive
// value=x        //  x=5          5<x<5.5      5.5<=x<6  

Math.floor(value) //  5            5            5
Math.ceil(value)  //  5            6            6
Math.round(value) //  5            5            6
Math.trunc(value) //  5            5            5
parseInt(value)   //  5            5            5
~~value           //  5            5            5
value | 0         //  5            5            5
value >> 0        //  5            5            5
value >>> 0       //  5            5            5
value - value % 1 //  5            5            5
Negative
// value=x        // x=-5         -5>x>=-5.5   -5.5>x>-6

Math.floor(value) // -5           -6           -6
Math.ceil(value)  // -5           -5           -5
Math.round(value) // -5           -5           -6
Math.trunc(value) // -5           -5           -5
parseInt(value)   // -5           -5           -5
value | 0         // -5           -5           -5
~~value           // -5           -5           -5
value >> 0        // -5           -5           -5
value >>> 0       // 4294967291   4294967291   4294967291
value - value % 1 // -5           -5           -5
Positive - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1

// value=x            x=900719925474099    x=900719925474099.4  x=900719925474099.5
           
Math.floor(value) //  900719925474099      900719925474099      900719925474099
Math.ceil(value)  //  900719925474099      900719925474100      900719925474100
Math.round(value) //  900719925474099      900719925474099      900719925474100
Math.trunc(value) //  900719925474099      900719925474099      900719925474099
parseInt(value)   //  900719925474099      900719925474099      900719925474099
value | 0         //  858993459            858993459            858993459
~~value           //  858993459            858993459            858993459
value >> 0        //  858993459            858993459            858993459
value >>> 0       //  858993459            858993459            858993459
value - value % 1 //  900719925474099      900719925474099      900719925474099
Negative - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1

// value = x      // x=-900719925474099   x=-900719925474099.5 x=-900719925474099.6

Math.floor(value) // -900719925474099     -900719925474100     -900719925474100
Math.ceil(value)  // -900719925474099     -900719925474099     -900719925474099
Math.round(value) // -900719925474099     -900719925474099     -900719925474100
Math.trunc(value) // -900719925474099     -900719925474099     -900719925474099
parseInt(value)   // -900719925474099     -900719925474099     -900719925474099
value | 0         // -858993459           -858993459           -858993459
~~value           // -858993459           -858993459           -858993459
value >> 0        // -858993459           -858993459           -858993459
value >>> 0       //  3435973837           3435973837           3435973837
value - value % 1 // -900719925474099     -900719925474099     -900719925474099

How to make Bootstrap Panel body with fixed height

You can use max-height in an inline style attribute, as below:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

To use scrolling with content that overflows a given max-height, you can alternatively try the following:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>

To restrict the height to a fixed value you can use something like this.

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

Specify the same value for both max-height and min-height (either in pixels or in points – as long as it’s consistent).

You can also put the same styles in css class in a stylesheet (or a style tag as shown below) and then include the same in your tag. See below:

Style Code:

.fixed-panel {
  min-height: 10;
  max-height: 10;
  overflow-y: scroll;
}

Apply Style :

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>

Hope this helps with your need.

require(vendor/autoload.php): failed to open stream

I was able to resolve by removing composer and reinstalling the proper way. Here is what I did:

I was then able to get composer install to work again. Found my answer at the bottom of this issue: https://github.com/composer/composer/issues/5510

PHP is_numeric or preg_match 0-9 validation

Meanwhile, all the values above will only restrict the values to integer, so i use

/^[1-9][0-9\.]{0,15}$/

to allow float values too.

Performing Breadth First Search recursively

I had to implement a heap traversal which outputs in a BFS order. It isn't actually BFS but accomplishes the same task.

private void getNodeValue(Node node, int index, int[] array) {
    array[index] = node.value;
    index = (index*2)+1;

    Node left = node.leftNode;
    if (left!=null) getNodeValue(left,index,array);
    Node right = node.rightNode;
    if (right!=null) getNodeValue(right,index+1,array);
}

public int[] getHeap() {
    int[] nodes = new int[size];
    getNodeValue(root,0,nodes);
    return nodes;
}

Java array reflection: isArray vs. instanceof

If you ever have a choice between a reflective solution and a non-reflective solution, never pick the reflective one (involving Class objects). It's not that it's "Wrong" or anything, but anything involving reflection is generally less obvious and less clear.

C++ Compare char array with string

There is more stable function, also gets rid of string folding.

// Add to C++ source
bool string_equal (const char* arg0, const char* arg1)
{
    /*
     * This function wraps string comparison with string pointers
     * (and also works around 'string folding', as I said).
     * Converts pointers to std::string
     * for make use of string equality operator (==).
     * Parameters use 'const' for prevent possible object corruption.
     */
    std::string var0 = (std::string) arg0;
    std::string var1 = (std::string) arg1;
    if (var0 == var1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

And add declaration to header

// Parameters use 'const' for prevent possible object corruption.
bool string_equal (const char* arg0, const char* arg1);

For usage, just place an 'string_equal' call as condition of if (or ternary) statement/block.

if (string_equal (var1, "dev"))
{
    // It is equal, do what needed here.
}
else
{
    // It is not equal, do what needed here (optional).
}

Source: sinatramultimedia/fl32 codec (it's written by myself)

How do I get the max and min values from a set of numbers entered?

here you need to skip int 0 like following:

val = s.nextInt();
  if ((val < min) && (val!=0)) {
      min = val;
  }

Install psycopg2 on Ubuntu

Use

sudo apt-get install python3-psycopg2

for Python3 )

Clear text field value in JQuery

We can use this for text clear

_x000D_
_x000D_
$('input[name="message"]').val("");  
_x000D_
_x000D_
_x000D_

Collision resolution in Java HashMap

It isn't defined to do so. In order to achieve this functionality, you need to create a map that maps keys to lists of values:

Map<Foo, List<Bar>> myMap;

Or, you could use the Multimap from google collections / guava libraries

How do you create a Marker with a custom icon for google maps API v3?

LatLng hello = new LatLng(X, Y);          // whereX & Y are coordinates

Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
                R.drawable.university);   // where university is the icon name that is used as a marker.

mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(icon)).position(hello).title("Hello World!"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(hello));

javascript createElement(), style problem

Works fine:

var obj = document.createElement('div');
obj.id = "::img";
obj.style.cssText = 'position:absolute;top:300px;left:300px;width:200px;height:200px;-moz-border-radius:100px;border:1px  solid #ddd;-moz-box-shadow: 0px 0px 8px  #fff;display:none;';

document.getElementById("divInsteadOfDocument.Write").appendChild(obj);

You can also see how to set the the CSS in one go (using element.style.cssText).


I suggest you use some more meaningful variable names and don't use the same name for different elements. It looks like you are using obj for different elements (overwriting the value in the function) and this can be confusing.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

I had a similar problem and I solved it by setting a static IP on the Android device.

When you add the network on Android, first you enter the SSID and password, then underneath you can open advanced options and set a static IP.

How to monitor the memory usage of Node.js?

You can use node.js memoryUsage

const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024 * 100) / 100} MB`

const memoryData = process.memoryUsage()

const memoryUsage = {
                rss: `${formatMemoryUsage(memoryData.rss)} -> Resident Set Size - total memory allocated for the process execution`,
                heapTotal: `${formatMemoryUsage(memoryData.heapTotal)} -> total size of the allocated heap`,
                heapUsed: `${formatMemoryUsage(memoryData.heapUsed)} -> actual memory used during the execution`,
                external: `${formatMemoryUsage(memoryData.external)} -> V8 external memory`,
}

console.log(memoryUsage)
/*
{
    "rss": "177.54 MB -> Resident Set Size - total memory allocated for the process execution",
    "heapTotal": "102.3 MB -> total size of the allocated heap",
    "heapUsed": "94.3 MB -> actual memory used during the execution",
    "external": "3.03 MB -> V8 external memory"
}
*/

Print new output on same line

From help(print):

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

You can use the end keyword:

>>> for i in range(1, 11):
...     print(i, end='')
... 
12345678910>>> 

Note that you'll have to print() the final newline yourself. BTW, you won't get "12345678910" in Python 2 with the trailing comma, you'll get 1 2 3 4 5 6 7 8 9 10 instead.

How to count duplicate rows in pandas dataframe?

None of the existing answers quite offers a simple solution that returns "the number of rows that are just duplicates and should be cut out". This is a one-size-fits-all solution that does:

# generate a table of those culprit rows which are duplicated:
dups = df.groupby(df.columns.tolist()).size().reset_index().rename(columns={0:'count'})

# sum the final col of that table, and subtract the number of culprits:
dups['count'].sum() - dups.shape[0]

jquery - How to determine if a div changes its height or any css attribute?

First, There is no such css-changes event out of the box, but you can create one by your own, as onchange is for :input elements only. not for css changes.

There are two ways to track css changes.

  1. Examine the DOM element for css changes every x time(500 milliseconds in the example).
  2. Trigger an event when you change the element css.
  3. Use the DOMAttrModified mutation event. But it's deprecated, so I'll skip on it.

First way:

var $element = $("#elementId");
var lastHeight = $("#elementId").css('height');
function checkForChanges()
{
    if ($element.css('height') != lastHeight)
    {
        alert('xxx');
        lastHeight = $element.css('height'); 
    }

    setTimeout(checkForChanges, 500);
}

Second way:

$('#mainContent').bind('heightChange', function(){
        alert('xxx');
    });


$("#btnSample1").click(function() {
    $("#mainContent").css('height', '400px');
    $("#mainContent").trigger('heightChange'); //<====
    ...
});    

If you control the css changes, the second option is a lot more elegant and efficient way of doing it.

Documentations:

  • bind: Description: Attach a handler to an event for the elements.
  • trigger: Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

java.io.IOException: Server returned HTTP response code: 500

This Status Code 500 is an Internal Server Error. This code indicates that a part of the server (for example, a CGI program) has crashed or encountered a configuration error.

i think the problem does'nt lie on your side, but rather on the side of the Http server. the resources you used to access may have been moved or get corrupted, or its configuration just may have altered or spoiled

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id

More details here.

From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

How do I wrap text in a span?

I've got a solution that should work in IE6 (and definitely works in 7+ & FireFox/Chrome).
You were on the right track using a span, but the use of a ul was wrong and the css wasn't right.

Try this

<a class="htooltip" href="#">
    Notes

    <span>
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
    </span>
</a>
.htooltip, .htooltip:visited, .tooltip:active {
    color: #0077AA;
    text-decoration: none;
}

.htooltip:hover {
    color: #0099CC;
}

.htooltip span {
    display : none;
    position: absolute;
    background-color: black;
    color: #fff;
    padding: 5px 10px 5px 40px;
    text-decoration: none;
    width: 350px;
    z-index: 10;
}

.htooltip:hover span {
    display: block;
}

Everyone was going about this the wrong way. The code isn't valid, ul's cant go in a's, p's can't go in a's, div's cant go in a's, just use a span (remembering to make it display as a block so it will wrap as if it were a div/p etc).

Python - converting a string of numbers into a list of int

it should work

example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
example_list = [int(k) for k in example_string.split(',')]

check for null date in CASE statement, where have I gone wrong?

select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
  'Awaiting'
Else
  'Approved'
END AS StartDateStatus
From MyTable

Change Image of ImageView programmatically in Android

In your XML for the image view, where you have android:background="@drawable/thumbs_down change this to android:src="@drawable/thumbs_down"

Currently it is placing that image as the background to the view and not the actual image in it.

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

jQuery - keydown / keypress /keyup ENTERKEY detection?

I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.

How do I implement a progress bar in C#?

This will Helpfull.Easy to implement,100% tested.

for(int i=1;i<linecount;i++)
{
 progressBar1.Value = i * progressBar1.Maximum / linecount;  //show process bar counts
 LabelTotal.Text = i.ToString() + " of " + linecount; //show number of count in lable
 int presentage = (i * 100) / linecount;
 LabelPresentage.Text = presentage.ToString() + " %"; //show precentage in lable
 Application.DoEvents(); keep form active in every loop
}

Initialization of all elements of an array to one default value in C++?

There is an extension to the gcc compiler which allows the syntax:

int array[100] = { [0 ... 99] = -1 };

This would set all of the elements to -1.

This is known as "Designated Initializers" see here for further information.

Note this isn't implemented for the gcc c++ compiler.

Run react-native application on iOS device directly from command line?

The following worked for me (tested on react native 0.38 and 0.40):

npm install -g ios-deploy
# Run on a connected device, e.g. Max's iPhone:
react-native run-ios --device "Max's iPhone"

If you try to run run-ios, you will see that the script recommends to do npm install -g ios-deploy when it reach install step after building.

While the documentation on the various commands that react-native offers is a little sketchy, it is worth going to react-native/local-cli. There, you can see all the commands available and the code that they run - you can thus work out what switches are available for undocumented commands.

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

tqdm in Jupyter Notebook prints new progress bars repeatedly

None of the above works for me. I find that running the following sorts this issue after error (It just clears all the instances of progress bars in the background):

from tqdm import tqdm

# blah blah your code errored

tqdm._instances.clear()

What's the difference between setWebViewClient vs. setWebChromeClient?

From the source code:

// Instance of WebViewClient that is the client callback.
private volatile WebViewClient mWebViewClient;
// Instance of WebChromeClient for handling all chrome functions.
private volatile WebChromeClient mWebChromeClient;

// SOME OTHER SUTFFF.......

/**
 * Set the WebViewClient.
 * @param client An implementation of WebViewClient.
 */
public void setWebViewClient(WebViewClient client) {
    mWebViewClient = client;
}

/**
 * Set the WebChromeClient.
 * @param client An implementation of WebChromeClient.
 */
public void setWebChromeClient(WebChromeClient client) {
    mWebChromeClient = client;
}

Using WebChromeClient allows you to handle Javascript dialogs, favicons, titles, and the progress. Take a look of this example: Adding alert() support to a WebView

At first glance, there are too many differences WebViewClient & WebChromeClient. But, basically: if you are developing a WebView that won't require too many features but rendering HTML, you can just use a WebViewClient. On the other hand, if you want to (for instance) load the favicon of the page you are rendering, you should use a WebChromeClient object and override the onReceivedIcon(WebView view, Bitmap icon).

Most of the times, if you don't want to worry about those things... you can just do this:

webView= (WebView) findViewById(R.id.webview); 
webView.setWebChromeClient(new WebChromeClient()); 
webView.setWebViewClient(new WebViewClient()); 
webView.getSettings().setJavaScriptEnabled(true); 
webView.loadUrl(url); 

And your WebView will (in theory) have all features implemented (as the android native browser).

C++ compile time error: expected identifier before numeric constant

Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor

vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);

As an alternative you can use constructor initializer lists

 Attribute():name(5), val(5, 0) {}

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

Make sure you import the @Test annotation from the correct library:

import org.junit.jupiter.api.Test

not

import org.junit.Test

Where does PostgreSQL store the database?

As suggested in "PostgreSQL database default location on Linux", under Linux you can find out using the following command:

ps aux | grep postgres | grep -- -D

How to delete a cookie?

would this work?

function eraseCookie(name) {
    document.cookie = name + '=; Max-Age=0'
}

I know Max-Age causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.

How to write and read java serialized objects into a file

I think you have to write each object to an own File or you have to split the one when reading it. You may also try to serialize your list and retrieve that when deserializing.

Can (domain name) subdomains have an underscore "_" in it?

I followed the link to RFC1034 and read most of it and was surprised to see this:

The labels must follow the rules for ARPANET host names. They must start with a letter, end with a letter or digit, and have as interior characters only letters, digits, and hyphen. There are also some restrictions on the length. Labels must be 63 characters or less.

For clarification, a domain names are made up of labels which are separated by dots ".". This spec must be outdated because it doesn't mention the use of underscores. I can understand the confusion if anybody stumbles over this spec without knowing it is obsolete. It is obsolete, isn't it?

I followed the link to RFC2181 and read some of it. Especially where it pertains to the issue of what is an authoritative, or canonical, name and the issue of what makes a valid DNS label.

As posted earlier it states there's only a length restriction then to sum it up it reads:

(about names and valid labels)

These are already adequately specified, however the specifications seem to be sometimes ignored. We seek to reinforce the existing specifications.

Kind of leaves me wondering if "a length only restriction" is "adequate". Are we going to start seeing domain names like @#$%!! soon? Isn't the internet screwed up enough?

Using JQuery to open a popup window and print

Got it! I found an idea here

http://www.mail-archive.com/[email protected]/msg18410.html

In this example, they loaded a blank popup window into an object, cloned the contents of the element to be displayed, and appended it to the body of the object. Since I already knew what the contents of view-details (or any page I load in the lightbox), I just had to clone that content instead and load it into an object. Then, I just needed to print that object. The final outcome looks like this:

$('.printBtn').bind('click',function() {
    var thePopup = window.open( '', "Customer Listing", "menubar=0,location=0,height=700,width=700" );
    $('#popup-content').clone().appendTo( thePopup.document.body );
    thePopup.print();
});

I had one small drawback in that the style sheet I was using in view-details.php was using a relative link. I had to change it to an absolute link. The reason being that the window didn't have a URL associated with it, so it had no relative position to draw on.

Works in Firefox. I need to test it in some other major browsers too.

I don't know how well this solution works when you're dealing with images, videos, or other process intensive solutions. Although, it works pretty well in my case, since I'm just loading tables and text values.

Thanks for the input! You gave me some ideas of how to get around this.

How to initialize a dict with keys from a list and empty value in Python?

You could use dict.fromkeys as follows:

dict.fromkeys([1, 2, 3, 4], list())

This will create a list object for each key. If you change value for any specific key it won't affect other keys (as most people would want, I presume).

Removing black dots from li and ul

There you go, this is what I used to fix your problem:

CSS CODE

nav ul { list-style-type: none; }

HTML CODE

<nav>
<ul>
<li><a href="#">Milk</a>
   <ul>
   <li><a href="#">Goat</a></li>
   <li><a href="#">Cow</a></li>
   </ul>
</li>
<li><a href="#">Eggs</a>
   <ul>
   <li><a href="#">Free-range</a></li>
   <li><a href="#">Other</a></li>
   </ul>
</li>
<li><a href="#">Cheese</a>
   <ul>
   <li><a href="#">Smelly</a></li>
   <li><a href="#">Extra smelly</a></li>
   </ul>
</li>
</ul>
</nav>

Change navbar text color Bootstrap

Thanks WChoward for your answer. I expanded:

.nav-link, .dropdown-item {
    color: blue !important;
}
.nav-link:hover, .dropdown-item:hover {
    color: darkgreen !important;
}

Fully change package name including company domain

I have read almost all the answers. But I think one is missing. Sometimes I may be wrong. I have used the below method and it's working.

3 Methods to change package name in Android Studio

  1. Select your package and Right-click, Refactor -> Move.
  2. Choose Move package from "your package" to another package and click Ok.
  3. A new dialog appears, says Multiple directories correspond to package "your package" and click Yes.
  4. Enter the new package name except for the last level or last name. Means If you want to rename package name to "info.xyz.yourapplication". Then type down "info.xyz" only leave "yourapplication".
  5. Click Refactor.
  6. A new dialog, Package info.xyz does not exist. Do you want to create it?. Click on Yes.
  7. Click Do refactor.
  8. Right-click on the new package to change the last name. Refactor-> Rename.
  9. Rename package
  10. type new name and click Do refactor.
  11. Delete all old package directories.
  12. Change ApplicationId in build.gradle file and click on sync now

"The operation is not valid for the state of the transaction" error and transaction scope

When I encountered this exception, there was an InnerException "Transaction Timeout". Since this was during a debug session, when I halted my code for some time inside the TransactionScope, I chose to ignore this issue.

When this specific exception with a timeout appears in deployed code, I think that the following section in you .config file will help you out:

<system.transactions> 
        <machineSettings maxTimeout="00:05:00" /> 
</system.transactions>

Vbscript list all PDF files in folder and subfolders

May not help OP, but hopefully others may find this helpful:

run

%ComSpec% /c cd/d StartPath & dir/s/b *.pdf

using shell object

StdOut will contain all PDF files

Refused to load the script because it violates the following Content Security Policy directive

The self answer given by MagngooSasa did the trick, but for anyone else trying to understand the answer, here are a few bit more details:

When developing Cordova apps with Visual Studio, I tried to import a remote JavaScript file [located here http://Guess.What.com/MyScript.js], but I have the error mentioned in the title.

Here is the meta tag before, in the index.html file of the project:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

Here is the corrected meta tag, to allow importing a remote script:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;**script-src 'self' http://onlineerp.solution.quebec 'unsafe-inline' 'unsafe-eval';** ">

And no more error!

How to add \newpage in Rmarkdown in a smart way?

You can make the pagebreak conditional on knitting to PDF. This worked for me.

```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```

how to check if a form is valid programmatically using jQuery Validation Plugin

Use .valid() from the jQuery Validation plugin:

$("#form_id").valid();

Checks whether the selected form is valid or whether all selected elements are valid. validate() needs to be called on the form before checking it using this method.

Where the form with id='form_id' is a form that has already had .validate() called on it.

What is the difference between class and instance methods?

Also remember, the same idea applies to variables. You will come across terms like static, member, instance, class and so on when talking about variables the same as you would for methods/functions.

It seems the common term in the Obj-C community is ivar for instance variable, but I am not an Obj-C guy, yet.

Change one value based on another value in pandas

You can use map, it can map vales from a dictonairy or even a custom function.

Suppose this is your df:

    ID First_Name Last_Name
0  103          a         b
1  104          c         d

Create the dicts:

fnames = {103: "Matt", 104: "Mr"}
lnames = {103: "Jones", 104: "X"}

And map:

df['First_Name'] = df['ID'].map(fnames)
df['Last_Name'] = df['ID'].map(lnames)

The result will be:

    ID First_Name Last_Name
0  103       Matt     Jones
1  104         Mr         X

Or use a custom function:

names = {103: ("Matt", "Jones"), 104: ("Mr", "X")}
df['First_Name'] = df['ID'].map(lambda x: names[x][0])

Min/Max-value validators in asp.net mvc

jQuery Validation Plugin already implements min and max rules, we just need to create an adapter for our custom attribute:

public class MaxAttribute : ValidationAttribute, IClientValidatable
{
    private readonly int maxValue;

    public MaxAttribute(int maxValue)
    {
        this.maxValue = maxValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();

        rule.ErrorMessage = ErrorMessageString, maxValue;

        rule.ValidationType = "max";
        rule.ValidationParameters.Add("max", maxValue);
        yield return rule;
    }

    public override bool IsValid(object value)
    {
        return (int)value <= maxValue;
    }
}

Adapter:

$.validator.unobtrusive.adapters.add(
   'max',
   ['max'],
   function (options) {
       options.rules['max'] = parseInt(options.params['max'], 10);
       options.messages['max'] = options.message;
   });

Min attribute would be very similar.

How to increment a JavaScript variable using a button press event

Had a similar problem. Needed to append as many text inputs as the user wanted, to a form. The functionality of it using jQuery was the answer to the question:

<div id='inputdiv'>
<button id='mybutton'>add an input</button>
</div>

<script>
var thecounter=0; //declare and initialize the counter outside of the function
$('#mybutton').on('click', function(){
thecounter++;
$('#inputdiv').append('<input id="input'+thecounter+'" type="text/>);
});
</script>

Adding the count to each new input id resulted in unique ids which lets you get all the values using the jQuery serialize() function.

Writing sqlplus output to a file

Also note that the SPOOL output is driven by a few SQLPlus settings:

  • SET LINESIZE nn - maximum line width; if the output is longer it will wrap to display the contents of each result row.

  • SET TRIMSPOOL OFF|ON - if set OFF (the default), every output line will be padded to LINESIZE. If set ON, every output line will be trimmed.

  • SET PAGESIZE nn - number of lines to output for each repetition of the header. If set to zero, no header is output; just the detail.

Those are the biggies, but there are some others to consider if you just want the output without all the SQLPlus chatter.

Real escape string and PDO

PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.

Here is an excerpt from the PHP website:

<?php
    $conn = new PDO('sqlite:/home/lynn/music.sql3');

    /* Simple string */
    $string = 'Nice';
    print "Unquoted string: $string\n";
    print "Quoted string: " . $conn->quote($string) . "\n";
?>

The above code will output:

Unquoted string: Nice
Quoted string: 'Nice'

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

Python threading.timer - repeat function every 'n' seconds

I had to do this for a project. What I ended up doing was start a separate thread for the function

t = threading.Thread(target =heartbeat, args=(worker,))
t.start()

****heartbeat is my function, worker is one of my arguments****

inside of my heartbeat function:

def heartbeat(worker):

    while True:
        time.sleep(5)
        #all of my code

So when I start the thread the function will repeatedly wait 5 seconds, run all of my code, and do that indefinitely. If you want to kill the process just kill the thread.

Using jQuery Fancybox or Lightbox to display a contact form

Greybox cannot handle forms inside it on its own. It requires a forms plugin. No iframes or external html files needed. Don't forget to download the greybox.css file too as the page misses that bit out.

Kiss Jquery UI goodbye and a lightbox hello. You can get it here.

Not class selector in jQuery

You can use the :not filter selector:

$('foo:not(".someClass")')

Or not() method:

$('foo').not(".someClass")

More Info:

Long press on UITableView

First add the long press gesture recognizer to the table view:

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
  initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //seconds
lpgr.delegate = self;
[self.myTableView addGestureRecognizer:lpgr];
[lpgr release];

Then in the gesture handler:

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint p = [gestureRecognizer locationInView:self.myTableView];

    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:p];
    if (indexPath == nil) {
        NSLog(@"long press on table view but not on a row");
    } else if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"long press on table view at row %ld", indexPath.row);
    } else {
        NSLog(@"gestureRecognizer.state = %ld", gestureRecognizer.state);
    }
}

You have to be careful with this so that it doesn't interfere with the user's normal tapping of the cell and also note that handleLongPress may fire multiple times (this will be due to the gesture recognizer state changes).

DataTrigger where value is NOT null?

My solution is in the DataContext instance (or ViewModel if using MVVM). I add a property that returns true if the Not Null condition I want is met.

    Public ReadOnly Property IsSomeFieldNull() As Boolean
        Get
            Return If(SomeField is Null, True, False)
        End Get
    End Property

and bind the DataTrigger to the above property. Note: In VB.NET be sure to use the operator If and NOT the IIf function, which doesn't work with Null objects. Then the XAML is:

    <DataTrigger Binding="{Binding IsSomeFieldNull}" Value="False">
      <Setter Property="TextBlock.Text" Value="It's NOT NULL Baby!" />
    </DataTrigger>

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

To add to the valuable content, I would like to create this reminder on why sometimes RegEx within VBA is not ideal. Not all expressions are supported, but instead may throw an Error 5017 and may leave the author guessing (which I am a victim of myself).

Whilst we can find some sources on what is supported, it would be helpfull to know which metacharacters etc. are not supported. A more in-depth explaination can be found here. Mentioned in this source:

"Although "VBScript’s regular expression ... version 5.5 implements quite a few essential regex features that were missing in previous versions of VBScript. ... JavaScript and VBScript implement Perl-style regular expressions. However, they lack quite a number of advanced features available in Perl and other modern regular expression flavors:"


So, not supported are:

  • Start of String ancor \A, alternatively use the ^ caret to match postion before 1st char in string
  • End of String ancor \Z, alternatively use the $ dollar sign to match postion after last char in string
  • Positive LookBehind, e.g.: (?<=a)b (whilst postive LookAhead is supported)
  • Negative LookBehind, e.g.: (?<!a)b (whilst negative LookAhead is supported)
  • Atomic Grouping
  • Possessive Quantifiers
  • Unicode e.g.: \{uFFFF}
  • Named Capturing Groups. Alternatively use Numbered Capturing Groups
  • Inline modifiers, e.g.: /i (case sensitivity) or /g (global) etc. Set these through the RegExp object properties > RegExp.Global = True and RegExp.IgnoreCase = True if available.
  • Conditionals
  • Regular Expression Comments. Add these with regular ' comments in script

I already hit a wall more than once using regular expressions within VBA. Usually with LookBehind but sometimes I even forget the modifiers. I have not experienced all these above mentioned backdrops myself but thought I would try to be extensive referring to some more in-depth information. Feel free to comment/correct/add. Big shout out to regular-expressions.info for a wealth of information.

P.S. You have mentioned regular VBA methods and functions, and I can confirm they (at least to myself) have been helpful in their own ways where RegEx would fail.

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Simply cleaning the project solved it for me.

My project is a C++ application (not a shared library). I randomly got this error after a lot of successful builds.

Add MIME mapping in web.config for IIS Express

I know this is an old question, but...

I was just noticing my instance of IISExpress wasn't serving woff files, so I wen't searching (Found this) and then found:

http://www.tomasmcguinness.com/2011/07/06/adding-support-for-svg-to-iis-express/

I suppose my install has support for SVG since I haven't had issue with that. But the instructions are trivially modifiable for woff:

  • Open a console application with administrator privilages.
  • Navigation to the IIS Express directory. This lives under Program Files or Program Files (x86)
  • Run the command:

    appcmd set config /section:staticContent /+[fileExtension='woff',mimeType='application/x-woff']

Solved my problem, and I didn't have to mess with some crummy config (like I had to to add support for the PUT and DELETE verbs). Yay!

Entity Framework Core add unique constraint code-first

On EF core you cannot create Indexes using data annotations.But you can do it using the Fluent API.

Like this inside your {Db}Context.cs:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<User>()
        .HasIndex(u => u.Email)
        .IsUnique();
}

...or if you're using the overload with the buildAction:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<User>(entity => {
        entity.HasIndex(e => e.Email).IsUnique();
    });
}

You can read more about it here : Indexes

Pandas count(distinct) equivalent

Here is another method, much simple, lets say your dataframe name is daat and column name is YEARMONTH

daat.YEARMONTH.value_counts()

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

How do I separate an integer into separate digits in an array in JavaScript?

(123456789).toString(10).split("")

^^ this will return an array of strings

(123456789).toString(10).split("").map(function(t){return parseInt(t)})

^^ this will return an array of ints

CSS - center two images in css side by side

You can't have two elements with the same ID.

Aside from that, you are defining them as block elemnts, meaning (in layman's terms) that they are being forced to appear on their own line.

Instead, try something like this:

<div class="link"><a href="..."><img src="..."... /></a></div>
<div class="link"><a href="..."><img src="..."... /></a></div>

CSS:

.link {
    width: 50%;
    float: left;
    text-align: center;
}

Lombok added but getters and setters not recognized in Intellij IDEA

It's possible that you already have the Lombok plugin, and still the generated methods are not recognised by Android Studio. In such case the plugin might be out of date, so the solution is to simply update it.

Preferences -> Plugins -> Lombok Plugin -> Update Plugin

How do I get the MAX row with a GROUP BY in LINQ query?

var q = from s in db.Serials
        group s by s.Serial_Number into g
        select new {Serial_Number = g.Key, MaxUid = g.Max(s => s.uid) }

'cl' is not recognized as an internal or external command,

You can use Command prompt for VS 2010 and then select the path that your boost located. Use "bootstrap.bat", you can successfully install it.

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

First, I purchased the domain in GoDaddy, and when I clicked this link https://www.google.com/settings/security/lesssecureapps I didn't have the option, it show this message "The domain administrator manages these settings", so I go to the Admin Console https://admin.google.com/

There is this option enter image description here

Then appears the option that I needed in enter image description here

how to get the cookies from a php curl into a variable

My understanding is that cookies from curl must be written out to a file (curl -c cookie_file). If you're running curl through PHP's exec or system functions (or anything in that family), you should be able to save the cookies to a file, then open the file and read them in.

JDBC connection failed, error: TCP/IP connection to host failed

The error is self explanatory:

  • Check if your SQL server is actually up and running
  • Check SQL server hostname, username and password is correct
  • Check there's no firewall rule blocking TCP connection to port 1433
  • Check the host is actually reachable

A good check I often use is to use telnet, eg on a windows command prompt run:

telnet 127.0.0.1 1433

If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem

String Resource new line /n not possible?

I want to expand on this answer. What they meant is this icon:

Editor window button

It opens a "real editor window" instead of the limited-feature text box in the big overview. In that editor window, special chars, linebreaks etc. are allowed and converted to the correct xml "code" when saved

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Print: Entry, ":CFBundleIdentifier", Does Not Exist

If you're using Xcode 10, it may be due to an incompatibility with the latest build system of Xcode. Try switching to the legacy build system.

Open Xcode 10, File > Project Settings > Build System > switch dropdown to Legacy Build System.

Screenshot

jQuery get the image src

You may find likr

$('.class').find('tag').attr('src');

Changing button color programmatically

Here is an example using HTML:

<input type="button" value="click me" onclick="this.style.color='#000000';
this.style.backgroundColor = '#ffffff'" />

And here is an example using JavaScript:

document.getElementById("button").bgcolor="#Insert Color Here";

MongoDB and "joins"

The first example you link to shows how MongoDB references behave much like lazy loading not like a join. There isn't a query there that's happening on both collections, rather you query one and then you lookup items from another collection by reference.

How can I find WPF controls by name or type?

These options already talk about traversing the Visual Tree in C#. Its possible to traverse the visual tree in xaml as well using RelativeSource markup extension. msdn

find by type

Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type <TypeToFind>}}}" 

Is it possible to compile a program written in Python?

Python, as a dynamic language, cannot be "compiled" into machine code statically, like C or COBOL can. You'll always need an interpreter to execute the code, which, by definition in the language, is a dynamic operation.

You can "translate" source code in bytecode, which is just an intermediate process that the interpreter does to speed up the load of the code, It converts text files, with comments, blank spaces, words like 'if', 'def', 'in', etc in binary code, but the operations behind are exactly the same, in Python, not in machine code or any other language. This is what it's stored in .pyc files and it's also portable between architectures.

Probably what you need it's not "compile" the code (which it's not possible) but to "embed" an interpreter (in the right architecture) with the code to allow running the code without an external installation of the interpreter. To do that, you can use all those tools like py2exe or cx_Freeze.

Maybe I'm being a little pedantic on this :-P

How to make a view with rounded corners?

Create a xml file called round.xml in the drawable folder and paste this content:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
  <solid android:color="#FFFFFF" />
  <stroke android:width=".05dp" android:color="#d2d2d2" />
  <corners android:topLeftRadius="5dp" android:topRightRadius="5dp" android:bottomRightRadius="5dp" android:bottomLeftRadius="5dp"/>
</shape>

then use the round.xml as background to any item. Then it will give you rounded corners.

How do I access the HTTP request header fields via JavaScript?

This can be accessed through Javascript because it's a property of the loaded document, not of its parent.

Here's a quick example:

<script type="text/javascript">
document.write(document.referrer);
</script>

The same thing in PHP would be:

<?php echo $_SERVER["HTTP_REFERER"]; ?>

Get GMT Time in Java

You can’t

First, you are asking the impossible. An old-fashioned Date object hasn’t got, as in cannot have a time zone or GMT offset.

But the date is always is interpreted in my local time zone.

I suppose that you have printed the Date or done something else that implicitly calls it toString method. I believe that this is the only time that the Date is interpreted in your time zone. More precisely in the current default time zone of your JVM. On the other hand this is unavoidable. Date.toString() does behave in that way, it picks up the JVM’s time zone setting and uses it for rendering the string to be returned.

You can with java.time

You shouldn’t use a Date, though. That class is poorly designed and fortunately long outdated. Also java.time, the modern Java date and time API that replaces it, has a class or two for dates and times with offset from GMT or UTC. I am considering GMT and UTC synonymous for now, strictly speaking they are not.

    OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
    System.out.println("Time now in UTC (GMT) is " + now);

When I ran this snippet just now, the output was:

Time now in UTC (GMT) is 2019-06-17T11:51:38.246188Z

The trailing Z of the output means UTC.

Links

Java generics: multiple generic parameters?

In your function definition you're constraining sets a and b to the same type. You can also write

public <X,Y> void myFunction(Set<X> s1, Set<Y> s2){...}

CASE .. WHEN expression in Oracle SQL

It will be easier to do using decode.

SELECT
  status,
    decode ( status, 'a1','Active',
                     'a2','Active',
                     'a3','Active',
                     'i','Inactive',
                     't','Terminated',
                     'Default')STATUSTEXT
FROM STATUS

Simultaneously merge multiple data.frames in a list

I will reuse the data example from @PaulRougieux

x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)

Here's a short and sweet solution using purrr and tidyr

library(tidyverse)

 list(x, y, z) %>% 
  map_df(gather, key=key, value=value, -i) %>% 
  spread(key, value)

How can I change the color of my prompt in zsh (different from normal text)?

To complement all of the above answers another convenient trick is to place the coloured prompt settings into a zsh function. There you may define local variables to alias longer commands, e.g. rc=$reset_color or define your own colour variables. Don't forget to place it into your .zshrc file and call the function you have defined:

# Coloured prompt
autoload -U colors && colors
function myprompt {
  local rc=$reset_color
  export PS1="%F{cyan}%n%{$rc%}@%F{green}%m%{$rc%}:%F{magenta}%~%{$rc%}%# "
}
myprompt

Using jquery to get element's position relative to viewport

The easiest way to determine the size and position of an element is to call its getBoundingClientRect() method. This method returns element positions in viewport coordinates. It expects no arguments and returns an object with properties left, right, top, and bottom. The left and top properties give the X and Y coordinates of the upper-left corner of the element and the right and bottom properties give the coordinates of the lower-right corner.

element.getBoundingClientRect(); // Get position in viewport coordinates

Supported everywhere.

Styling HTML email for Gmail

As others have said, some email programs will not read the css styles. If you already have a web email written up you can use the following tool from zurb to inline all of your styles:

http://zurb.com/ink/inliner.php

This comes in extremely handy when using templates like those mentioned above from mailchimp, campaign monitor, etc. as they, as you have found, will not work in some email programs. This tool leaves your style section for the mail programs that will read it and puts all the styles inline to get more universal readability in the format that you wanted.

How to Configure SSL for Amazon S3 bucket

I found you can do this easily via the Cloud Flare service.

Set up a bucket, enable webhosting on the bucket and point the desired CNAME to that endpoint via Cloudflare... and pay for the service of course... but $5-$20 VS $600 is much easier to stomach.

Full detail here: https://www.engaging.io/easy-way-to-configure-ssl-for-amazon-s3-bucket-via-cloudflare/

JQuery Ajax - How to Detect Network Connection error when making Ajax call

What I see in this case is that if I pull the client machine's network cable and make the call, the ajax success handler is called (why, I don't know), and the data parameter is an empty string. So if you factor out the real error handling, you can do something like this:

function handleError(jqXHR, textStatus, errorThrown) {
    ...
}

jQuery.ajax({
    ...
    success: function(data, textStatus, jqXHR) {
        if (data == "") handleError(jqXHR, "clientNetworkError", "");
    },
    error: handleError
});

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

If the shell scripts start with #!/bin/bash, they will always run with bash from /bin. If they however start with #!/usr/bin/env bash, they will search for bash in $PATH and then start with the first one they can find.

Why would this be useful? Assume you want to run bash scripts, that require bash 4.x or newer, yet your system only has bash 3.x installed and currently your distribution doesn't offer a newer version or you are no administrator and cannot change what is installed on that system.

Of course, you can download bash source code and build your own bash from scratch, placing it to ~/bin for example. And you can also modify your $PATH variable in your .bash_profile file to include ~/bin as the first entry (PATH=$HOME/bin:$PATH as ~ will not expand in $PATH). If you now call bash, the shell will first look for it in $PATH in order, so it starts with ~/bin, where it will find your bash. Same thing happens if scripts search for bash using #!/usr/bin/env bash, so these scripts would now be working on your system using your custom bash build.

One downside is, that this can lead to unexpected behavior, e.g. same script on the same machine may run with different interpreters for different environments or users with different search paths, causing all kind of headaches.

The biggest downside with env is that some systems will only allow one argument, so you cannot do this #!/usr/bin/env <interpreter> <arg>, as the systems will see <interpreter> <arg> as one argument (they will treat it as if the expression was quoted) and thus env will search for an interpreter named <interpreter> <arg>. Note that this is not a problem of the env command itself, which always allowed multiple parameters to be passed through but with the shebang parser of the system that parses this line before even calling env. Meanwhile this has been fixed on most systems but if your script wants to be ultra portable, you cannot rely that this has been fixed on the system you will be running.

It can even have security implications, e.g. if sudo was not configured to clean environment or $PATH was excluded from clean up. Let me demonstrate this:

Usually /bin is a well protected place, only root is able to change anything there. Your home directory is not, though, any program you run is able to make changes to it. That means malicious code could place a fake bash into some hidden directory, modify your .bash_profile to include that directory in your $PATH, so all scripts using #!/usr/bin/env bash will end up running with that fake bash. If sudo keeps $PATH, you are in big trouble.

E.g. consider a tool creates a file ~/.evil/bash with the following content:

#!/bin/bash

if [ $EUID -eq 0 ]; then
  echo "All your base are belong to us..."
  # We are root - do whatever you want to do
fi

/bin/bash "$@"

Let's make a simple script sample.sh:

#!/usr/bin/env bash

echo "Hello World"

Proof of concept (on a system where sudo keeps $PATH):

$ ./sample.sh
Hello World

$ sudo ./sample.sh
Hello World

$ export PATH="$HOME/.evil:$PATH"

$ ./sample.sh
Hello World

$ sudo ./sample.sh
All your base are belong to us...
Hello World

Usually the classic shells should all be located in /bin and if you don't want to place them there for whatever reason, it's really not an issue to place a symlink in /bin that points to their real locations (or maybe /bin itself is a symlink), so I would always go with #!/bin/sh and #!/bin/bash. There's just too much that would break if these wouldn't work anymore. It's not that POSIX would require these position (POSIX does not standardize path names and thus it doesn't even standardize the shebang feature at all) but they are so common, that even if a system would not offer a /bin/sh, it would probably still understand #!/bin/sh and know what to do with it and may it only be for compatibility with existing code.

But for more modern, non standard, optional interpreters like Perl, PHP, Python, or Ruby, it's not really specified anywhere where they should be located. They may be in /usr/bin but they may as well be in /usr/local/bin or in a completely different hierarchy branch (/opt/..., /Applications/..., etc.). That's why these often use the #!/usr/bin/env xxx shebang syntax.

CSS scale height to match width - possibly with a formfactor

Here it is. Pure CSS. You do need one extra 'container' element.

The fiddle

(tinkerbin, actually): http://tinkerbin.com/rQ71nWDT (Tinkerbin is dead.)

The solution.

Note I'm using an 100% throughout the example. You can use whichever percentage you'd like.

Since height percentages are relative to the height of the parent element, we can't rely on it. We must rely on something else. Luckily padding is relative to the width - whether it's horizontal or vertical padding. In padding-xyz: 100%, 100% equals 100% of the box's width.

Unfortunately, padding is just that, padding. The content-box's height is 0. No problem!

Stick an absolutely positioned element, give it 100% width, 100% height and use it as your actual content box. The 100% height works because percentage heights on absolutely positioned elements are relative to the padding-box of the box their relatively positioned to.

HTML:

<div id="map_container">
  <div id="map">
  </div>
</div>   

CSS:

#map_container {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
}

#map {
  position: absolute;
  width: 100%;
  height: 100%;
}

Proxy with urllib2

To use the default system proxies (e.g. from the http_support environment variable), the following works for the current request (without installing it into urllib2 globally):

url = 'http://www.example.com/'
proxy = urllib2.ProxyHandler()
opener = urllib2.build_opener(proxy)
in_ = opener.open(url)
in_.read()

Jquery function BEFORE form submission

You can do something like the following these days by referencing the "beforeSubmit" jquery form event. I'm disabling and enabling the submit button to avoid duplicate requests, submitting via ajax, returning a message that's a json array and displaying the information in a pNotify:

jQuery('body').on('beforeSubmit', "#formID", function() {
    $('.submitter').prop('disabled', true);
    var form = $('#formID');
    $.ajax({
        url    : form.attr('action'),
        type   : 'post',
        data   : form.serialize(),
        success: function (response)
        {
            response = jQuery.parseJSON(response);
            new PNotify({
                text: response.message,
                type: response.status,
                styling: 'bootstrap3',
                delay: 2000,
            });
            $('.submitter').prop('disabled', false);
        },
        error  : function ()
        {
            console.log('internal server error');
        }
    });
});

python xlrd unsupported format, or corrupt file.

I know there should be a proper way to solve it but just to save time

I uploaded my xlsx sheet to Google Sheets and then again downloaded it from Google Sheets it working now

If you don't have time to solve the problem, you can try this

When to use SELECT ... FOR UPDATE?

The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE.

However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE explicitly.


To solve this problem, Thread 1 should SELECT id FROM rooms FOR UPDATE, thereby preventing Thread 2 from deleting from rooms until Thread 1 is done. Is that correct?

This depends on the concurrency control your database system is using.

  • MyISAM in MySQL (and several other old systems) does lock the whole table for the duration of a query.

  • In SQL Server, SELECT queries place shared locks on the records / pages / tables they have examined, while DML queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT or DELETE query will lock until another session commits.

  • In databases which use MVCC (like Oracle, PostgreSQL, MySQL with InnoDB), a DML query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE would come handy: it would lock either SELECT or the DELETE query until another session commits, just as SQL Server does.

When should one use REPEATABLE_READ transaction isolation versus READ_COMMITTED with SELECT ... FOR UPDATE?

Generally, REPEATABLE READ does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)

  • In Oracle and earlier PostgreSQL versions, REPEATABLE READ is actually a synonym for SERIALIZABLE. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1 query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE

  • In InnoDB, REPEATABLE READ and SERIALIZABLE are different things: readers in SERIALIZABLE mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML on them. So you don't need a SELECT FOR UPDATE in serializable mode, but do need them in REPEATABLE READ or READ COMMITED.

Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC or otherwise).

When I say "you don't need SELECT FOR UPDATE" I really should have added "because of side effects of certain database engine implementation".

How to clear Tkinter Canvas?

Items drawn to the canvas are persistent. create_rectangle returns an item id that you need to keep track of. If you don't remove old items your program will eventually slow down.

From Fredrik Lundh's An Introduction to Tkinter:

Note that items added to the canvas are kept until you remove them. If you want to change the drawing, you can either use methods like coords, itemconfig, and move to modify the items, or use delete to remove them.

Apply CSS rules to a nested class inside a div

Use Css Selector for this, or learn more about Css Selector just go here https://www.w3schools.com/cssref/css_selectors.asp

#main_text > .title {
  /* Style goes here */
}

#main_text .title {
  /* Style goes here */
}

How to create a byte array in C++?

Byte is not a standard data type in C/C++ but it can still be used the way i suppose you want it. Here is how: Recall that a byte is an eight bit memory size which can represent any of the integers between -128 and 127, inclusive. (There are 256 integers in that range; eight bits can represent 256 -- two raised to the power eight -- different values.). Also recall that a char in C/C++ is one byte (eight bits). So, all you need to do to have a byte data type in C/C++ is to put this code at the top of your source file: #define byte char So you can now declare byte abc[3];

Are there best practices for (Java) package organization?

I've seen some people promote 'package by feature' over 'package by layer' but I've used quite a few approaches over many years and found 'package by layer' much better than 'package by feature'.

Further to that I have found that a hybrid: 'package by module, layer then feature' strategy works extremely well in practice as it has many advantages of 'package by feature':

  • Promotes creation of reusable frameworks (libraries with both model and UI aspects)
  • Allows plug and play layer implementations - virtually impossible with 'package by feature' because it places layer implementations in same package/directory as model code.
  • Many more...

I explain in depth here: Java Package Name Structure and Organization but my standard package structure is:

revdomain.moduleType.moduleName.layer.[layerImpl].feature.subfeatureN.subfeatureN+1...

Where:

revdomain Reverse domain e.g. com.mycompany

moduleType [app*|framework|util]

moduleName e.g. myAppName if module type is an app or 'finance' if its an accounting framework

layer [model|ui|persistence|security etc.,]

layerImpl eg., wicket, jsp, jpa, jdo, hibernate (Note: not used if layer is model)

feature eg., finance

subfeatureN eg., accounting

subfeatureN+1 eg., depreciation

*Sometimes 'app' left out if moduleType is an application but putting it in there makes the package structure consistent across all module types.

Change the row color in DataGridView based on the quantity of a cell value

If drv.Item("Quantity").Value < 5  Then

use this to like this

If Cint(drv.Item("Quantity").Value) < 5  Then

How Connect to remote host from Aptana Studio 3

There's also an option to Auto Sync built-in in Aptana.

step 1

step 2

Enable 'xp_cmdshell' SQL Server

While the accepted answer will work most of the times, I have encountered (still do not know why) some cases that is does not. A slight modification of the query by using the WITH OVERRIDE in RECONFIGURE gives the solution

Use Master
GO

EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
GO

The expected output is

Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.

How to horizontally center a floating element of a variable width?

Assuming the element which is floated and will be centered is a div with an id="content" ...

<body>
<div id="wrap">
   <div id="content">
   This will be centered
   </div>
</div>
</body>

And apply the following CSS:

#wrap {
    float: left;
    position: relative;
    left: 50%;
}

#content {
    float: left;
    position: relative;
    left: -50%;
}

Here is a good reference regarding that.

How do I find all files containing specific text on Linux?

Find any files whose name is ".kube/config", and content include eks_use1d:

locate ".kube/config" | xargs -i sh -c 'echo \\n{};cat {} | grep eks_use1d'

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

If you're interested in the physical RAM, use the command dmidecode. It gives you a lot more information than just that, but depending on your use case, you might also want to know if the 8G in the system come from 2x4GB sticks or 4x2GB sticks.

TypeError: unsupported operand type(s) for -: 'list' and 'list'

This question has been answered but I feel I should also mention another potential cause. This is a direct result of coming across the same error message but for different reasons. If your list/s are empty the operation will not be performed. check your code for indents and typos

Make a phone call programmatically

The Java RoboVM equivalent:

public void dial(String number)
{
  NSURL url = new NSURL("tel://" + number);
  UIApplication.getSharedApplication().openURL(url);
}

Jquery Setting Value of Input Field

$('.formData').attr('value','YOUR_VALUE')

Virtualbox "port forward" from Guest to Host

That's not possible. localhost always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.

If you want to access it e.g. in a browser, connect to it using the local IP instead:

http://192.168.180.1:8000

This is just an example of course, you can find out the actual IP by issuing an ifconfig command on a shell in the guest operating system.

How to interpret "loss" and "accuracy" for a machine learning model

Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.

The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.

Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.

How to send an HTTP request using Telnet

To somewhat expand on earlier answers, there are a few complications.

telnet is not particularly scriptable; you might prefer to use nc (aka netcat) instead, which handles non-terminal input and signals better.

Also, unlike telnet, nc actually allows SSL (and so https instead of http traffic -- you need port 443 instead of port 80 then).

There is a difference between HTTP 1.0 and 1.1. The recent version of the protocol requires the Host: header to be included in the request on a separate line after the POST or GET line, and to be followed by an empty line to mark the end of the request headers.

The HTTP protocol requires carriage return / line feed line endings. Many servers are lenient about this, but some are not. You might want to use

printf "%\r\n" \
    "GET /questions HTTP/1.1" \
    "Host: stackoverflow.com" \
    "" |
nc --ssl stackoverflow.com 443

If you fall back to HTTP/1.0 you don't always need the Host: header, but many modern servers require the header anyway; if multiple sites are hosted on the same IP address, the server doesn't know from GET /foo HTTP/1.0 whether you mean http://site1.example.com/foo or http://site2.example.net/foo if those two sites are both hosted on the same server (in the absence of a Host: header, a HTTP 1.0 server might just default to a different site than the one you want, so you don't get the contents you wanted).

The HTTPS protocol is identical to HTTP in these details; the only real difference is in how the session is set up initially.

Twitter Bootstrap date picker

Much confusion stems from the existence of at least three major libraries named bootstrap-datepicker:

  1. A popular fork of eyecon's datepicker by Andrew 'eternicode' Rowls (use this one!):
  2. The original version by Stefan 'eyecon' Petre, still available at http://www.eyecon.ro/bootstrap-datepicker/
  3. A totally unrelated datepicker widget that 'storborg' sought to have merged into bootstrap. It wasn't merged and no proper release version of the widget was ever created.

If you're starting a new project - or heck, even if you're taking over an old project using the eyecon version - I recommend that you use eternicode's version, not eyecon's. The original eyecon version is outright inferior in terms of both functionality and documentation, and this is unlikely to change - it has not been updated since March 2013.

You can see most of the capabilities of the eternicode datepicker on the demo page which lets you play with the datepicker's configuration and observe the results. For more detail, see the succinct but comprehensive documentation, which you can probably consume in its entirety in under an hour.

In case you're impatient, though, here's a very short step-by-step guide to the simplest and most common use case for the datepicker.

Quick start guide

  1. Include the following libraries (minimum versions noted here) on your page:
  2. Put an input element on your page somewhere, e.g.

    <input id="my-date-input">
    
  3. With jQuery, select your input and call the .datepicker() method:

    jQuery('#my-date-input').datepicker();
    
  4. Load your page and click on or tab into your input element. A datepicker will appear:

    Picture of a datepicker

Insert Picture into SQL Server 2005 Image Field using only SQL

I achieved the goal where I have multiple images to insert in the DB as

INSERT INTO [dbo].[User]
           ([Name]
           ,[Image1]
           ,[Age]
           ,[Image2]
           ,[GroupId]
           ,[GroupName])
           VALUES
           ('Umar'
           , (SELECT BulkColumn 
            FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image1)
           ,26
           ,(SELECT BulkColumn 
            FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image2)
            ,'Group123'
           ,'GroupABC')

What is the most efficient way to store a list in the Django models?

Storing a list of strings in Django model:

class Bar(models.Model):
    foo = models.TextField(blank=True)

    def set_list(self, element):
        if self.foo:
            self.foo = self.foo + "," + element
        else:
            self.foo = element

    def get_list(self):
        if self.foo:
            return self.foo.split(",")
        else:
            None

and you can call it like this:

bars = Bar()
bars.set_list("str1")
bars.set_list("str2")
list = bars.get_list()
if list is not None:
    for bar in list:
        print bar
else:
    print "List is empty."      

public static const in TypeScript

Here's what's this TS snippet compiled into (via TS Playground):

define(["require", "exports"], function(require, exports) {
    var Library = (function () {
        function Library() {
        }
        Library.BOOK_SHELF_NONE = "None";
        Library.BOOK_SHELF_FULL = "Full";
        return Library;
    })();
    exports.Library = Library;
});

As you see, both properties defined as public static are simply attached to the exported function (as its properties); therefore they should be accessible as long as you properly access the function itself.

Sockets - How to find out what port and address I'm assigned

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number %d\n", ntohs(sin.sin_port));

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

Assign a variable inside a Block to a variable outside a Block

Just use the __block prefix to declare and assign any type of variable inside a block.

For example:

__block Person *aPerson = nil;

__block NSString *name = nil;

How can I get key's value from dictionary in Swift?

Use subscripting to access the value for a dictionary key. This will return an Optional:

let apple: String? = companies["AAPL"]

or

if let apple = companies["AAPL"] {
    // ...
}

You can also enumerate over all of the keys and values:

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for (key, value) in companies {
    print("\(key) -> \(value)")
}

Or enumerate over all of the values:

for value in Array(companies.values) {
    print("\(value)")
}

Python string class like StringBuilder in C#?

Using method 5 from above (The Pseudo File) we can get very good perf and flexibility

from cStringIO import StringIO

class StringBuilder:
     _file_str = None

     def __init__(self):
         self._file_str = StringIO()

     def Append(self, str):
         self._file_str.write(str)

     def __str__(self):
         return self._file_str.getvalue()

now using it

sb = StringBuilder()

sb.Append("Hello\n")
sb.Append("World")

print sb

How do I remove a property from a JavaScript object?

I personally use Underscore.js or Lodash for object and array manipulation:

myObject = _.omit(myObject, 'regex');

How to center icon and text in a android button with width set to "fill parent"

I have seen solutions for aligning drawable at start/left but nothing for drawable end/right, so I came up with this solution. It uses dynamically calculated paddings for aligning drawable and text on both left and right side.

class IconButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyle) {

    init {
        maxLines = 1
    }

    override fun onDraw(canvas: Canvas) {
        val buttonContentWidth = (width - paddingLeft - paddingRight).toFloat()

        val textWidth = paint.measureText(text.toString())

        val drawable = compoundDrawables[0] ?: compoundDrawables[2]
        val drawableWidth = drawable?.intrinsicWidth ?: 0
        val drawablePadding = if (textWidth > 0 && drawable != null) compoundDrawablePadding else 0
        val bodyWidth = textWidth + drawableWidth.toFloat() + drawablePadding.toFloat()

        canvas.save()

        val padding = (buttonContentWidth - bodyWidth).toInt() / 2
        val leftOrRight = if (compoundDrawables[0] != null) 1 else -1
        setPadding(leftOrRight * padding, 0, -leftOrRight * padding, 0)

        super.onDraw(canvas)
        canvas.restore()
    }
}

It is important to set gravity in your layout to either "center_vertical|start" or "center_vertical|end" depending on where do you set the icon. For example:

<com.stackoverflow.util.IconButton
        android:id="@+id/cancel_btn"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableStart="@drawable/cancel"
        android:drawablePadding="@dimen/padding_small"
        android:gravity="center_vertical|start"
        android:text="Cancel" />

Only problem with this implementation is that button can only have single line of text, otherwise the area of the text fills the button and paddings will be 0.

Spring RestTemplate GET with parameters

I take different approach, you may agree or not but I want to control from .properties file instead of compiled Java code

Inside application.properties file

endpoint.url = https://yourHost/resource?requestParam1={0}&requestParam2={1}

Java code goes here, you can write if or switch condition to find out if endpoint URL in .properties file has @PathVariable (contains {}) or @RequestParam (yourURL?key=value) etc... then invoke method accordingly... that way its dynamic and not need to code change in future one stop shop...

I'm trying to give more of idea than actual code here ...try to write generic method each for @RequestParam, and @PathVariable etc... then call accordingly when needed

  @Value("${endpoint.url}")
  private String endpointURL;
  // you can use variable args feature in Java
  public String requestParamMethodNameHere(String value1, String value2) {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate
           .getMessageConverters()
           .add(new MappingJackson2HttpMessageConverter());

    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
    HttpEntity<String> entity = new HttpEntity<>(headers);

    try {
      String formatted_URL = MessageFormat.format(endpointURL, value1, value2);
      ResponseEntity<String> response = restTemplate.exchange(
                    formatted_URL ,
                    HttpMethod.GET,
                    entity,
                    String.class);
     return response.getBody();
    } catch (Exception e) { e.printStackTrace(); }

How to find which version of TensorFlow is installed in my system?

For knowing any version of the python library then if your library is installed using the pip then use the following command.

pip show tensorflow

The Output of the above command will be shown below:-

Name: tensorflow
Version: 2.3.0
Summary: TensorFlow is an open source machine learning framework for everyone.
Home-page: https://www.tensorflow.org/
Author: Google Inc.
Author-email: [email protected]
License: Apache 2.0
Location: /usr/local/lib/python3.6/dist-packages
Requires: astunparse, wheel, keras-preprocessing, gast, tensorflow-estimator, opt-einsum, tensorboard, protobuf, absl-py, six, wrapt, termcolor, numpy, grpcio, scipy, google-pasta, h5py
Required-by: fancyimpute

Script not served by static file handler on IIS7.5

cmd -> right click -> Run as administrator

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

C++ convert string to hexadecimal and vice versa

Here is an other solution, largely inspired by the one by @fredoverflow.

/**
 * Return hexadecimal representation of the input binary sequence
 */
std::string hexitize(const std::vector<char>& input, const char* const digits = "0123456789ABCDEF")
{
    std::ostringstream output;

    for (unsigned char gap = 0, beg = input[gap]; gap < input.length(); beg = input[++gap])
        output << digits[beg >> 4] << digits[beg & 15];

    return output.str();
}

Length was required parameter in the intended usage.

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

var i = $("#panel input");

should work :-)

the > will only fetch direct children, no children's children
the : is for using pseudo-classes, eg. :hover, etc.

you can read about available css-selectors of pseudo-classes here: http://docs.jquery.com/DOM/Traversing/Selectors#CSS_Selectors

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

I got a similar error with '/' operand while processing images. I discovered the folder included a text file created by the 'XnView' image viewer. So, this kind of error occurs when some object is not the kind of object expected.

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

angular.service vs angular.factory

  angular.service('myService', myServiceFunction);
  angular.factory('myFactory', myFactoryFunction);

I had trouble wrapping my head around this concept until I put it to myself this way:

Service: the function that you write will be new-ed:

  myInjectedService  <----  new myServiceFunction()

Factory: the function (constructor) that you write will be invoked:

  myInjectedFactory  <---  myFactoryFunction()

What you do with that is up to you, but there are some useful patterns...

Such as writing a service function to expose a public API:

function myServiceFunction() {
  this.awesomeApi = function(optional) {
    // calculate some stuff
    return awesomeListOfValues;
  }
}
---------------------------------------------------------------------------------
// Injected in your controller
$scope.awesome = myInjectedService.awesomeApi();

Or using a factory function to expose a public API:

function myFactoryFunction() {
  var aPrivateVariable = "yay";

  function hello() {
    return "hello mars " + aPrivateVariable;
  }
  
  // expose a public API
  return {
    hello: hello
  };
}
---------------------------------------------------------------------------------
// Injected in your controller
$scope.hello = myInjectedFactory.hello();

Or using a factory function to return a constructor:

function myFactoryFunction() {
    return function() {
        var a = 2;
        this.a2 = function() {
            return a*2;
        };
    };
}
---------------------------------------------------------------------------------
// Injected in your controller
var myShinyNewObject = new myInjectedFactory();
$scope.four = myShinyNewObject.a2();

Which one to use?...

You can accomplish the same thing with both. However, in some cases the factory gives you a little bit more flexibility to create an injectable with a simpler syntax. That's because while myInjectedService must always be an object, myInjectedFactory can be an object, a function reference, or any value at all. For example, if you wrote a service to create a constructor (as in the last example above), it would have to be instantiated like so:

var myShinyNewObject = new myInjectedService.myFunction()

which is arguably less desirable than this:

var myShinyNewObject = new myInjectedFactory();

(But you should be wary about using this type of pattern in the first place because new-ing objects in your controllers creates hard-to-track dependencies that are difficult to mock for testing. Better to have a service manage a collection of objects for you than use new() wily-nilly.)


One more thing, they are all Singletons...

Also keep in mind that in both cases, angular is helping you manage a singleton. Regardless of where or how many times you inject your service or function, you will get the same reference to the same object or function. (With the exception of when a factory simply returns a value like a number or string. In that case, you will always get the same value, but not a reference.)

How to save final model using keras?

you can save the model in json and weights in a hdf5 file format.

# keras library import  for Saving and loading model and weights

from keras.models import model_from_json
from keras.models import load_model

# serialize model to JSON
#  the keras model which is trained is defined as 'model' in this example
model_json = model.to_json()


with open("model_num.json", "w") as json_file:
    json_file.write(model_json)

# serialize weights to HDF5
model.save_weights("model_num.h5")

files "model_num.h5" and "model_num.json" are created which contain our model and weights

To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.

# load json and create model
json_file = open('model_num.json', 'r')

loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("model_num.h5")
print("Loaded model from disk")

loaded_model.save('model_num.hdf5')
loaded_model=load_model('model_num.hdf5')

To predict for different data you can use this

loaded_model.predict_classes("your_test_data here")

How can I select the record with the 2nd highest salary in database Oracle?

select salary from EmployeeDetails order by salary desc limit 1 offset (n-1).

If you want to find 2nd highest than replace n with that 2.

Google Map API v3 — set bounds and center

My suggestion for google maps api v3 would be(don't think it can be done more effeciently):

gmap : {
    fitBounds: function(bounds, mapId)
    {
        //incoming: bounds - bounds object/array; mapid - map id if it was initialized in global variable before "var maps = [];"
        if (bounds==null) return false;
        maps[mapId].fitBounds(bounds);
    }
}

In the result u will fit all points in bounds in your map window.

Example works perfectly and u freely can check it here www.zemelapis.lt

How to get all key in JSON object (javascript)

var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

How do I install an R package from source?

Download the source package, open Terminal.app, navigate to the directory where you currently have the file, and then execute:

R CMD INSTALL RJSONIO_0.2-3.tar.gz

Do note that this will only succeed when either: a) the package does not need compilation or b) the needed system tools for compilation are present. See: https://cran.r-project.org/bin/macosx/tools/

What is the meaning of 'No bundle URL present' in react-native?

Most of the cases this problem occurs when the DNS lookup / IP lookup fails to find localhost.

Solution :

Try adding the localhost ip to your etc host file.

you can add the below lines to your etc host file (/etc/hosts)

127.0.0.1 localhost

255.255.255.255 broadcasthost

::1 l . ocalhost

To confirm this is the issue you can hit the bundle url on safari (if you try it in chrome this will resolve but safari won't be able to resolve it). http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false

The differences between initialize, define, declare a variable

Declaration

Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":

void xyz();

or declare an incomplete type:

class klass;
struct ztruct;

and last but not least, to declare an object:

int x;

It is described, in the C++ standard, at §3.1/1 as:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.

Definition

A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:

int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };

Specifically the C++ standard defines it, at §3.1/1, as:

A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).

Initialization

Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T, it's often in the form:

T x = i;

but in C++ it can be:

T x(i);

or even:

T x {i};

with C++11.

Conclusion

So does it mean definition equals declaration plus initialization?

It depends. On what you are talking about. If you are talking about an object, for example:

int x;

This is a definition without initialization. The following, instead, is a definition with initialization:

int x = 0;

In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.

So, the answer is no: definition does not automatically mean declaration plus initialization.

Getting a slice of keys from a map

I made a sketchy benchmark on the three methods described in other responses.

Obviously pre-allocating the slice before pulling the keys is faster than appending, but surprisingly, the reflect.ValueOf(m).MapKeys() method is significantly slower than the latter:

? go run scratch.go
populating
filling 100000000 slots
done in 56.630774791s
running prealloc
took: 9.989049786s
running append
took: 18.948676741s
running reflect
took: 25.50070649s

Here's the code: https://play.golang.org/p/Z8O6a2jyfTH (running it in the playground aborts claiming that it takes too long, so, well, run it locally.)

jQuery Mobile: Stick footer to bottom of page

In my case, I needed to use something like this to keep the footer pinned down at the bottom if there is not much content, but not floating on top of everything constantly like data-position="fixed" seems to do...

.ui-content
{
    margin-bottom:75px; /* Set this to whatever your footer size is... */
}

.ui-footer {
    position: absolute !important;
    bottom: 0;
    width: 100%;
}

How to change the default collation of a table?

may need to change the SCHEMA not only table

ALTER SCHEMA `<database name>`  DEFAULT CHARACTER SET utf8mb4  DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);

(mariaDB 10)

No provider for Router?

If you created a separate module (eg. AppRoutingModule) to contain your routing commands you can get this same error:

Error: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]: 
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
NullInjectorError: No provider for Router!

You may have forgotten to import it to the main AppModule as shown here:

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
  declarations: [ AppComponent, Page1Component, Page2Component ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

How to increase scrollback buffer size in tmux?

The history limit is a pane attribute that is fixed at the time of pane creation and cannot be changed for existing panes. The value is taken from the history-limit session option (the default value is 2000).

To create a pane with a different value you will need to set the appropriate history-limit option before creating the pane.

To establish a different default, you can put a line like the following in your .tmux.conf file:

set-option -g history-limit 3000

Note: Be careful setting a very large default value, it can easily consume lots of RAM if you create many panes.

For a new pane (or the initial pane in a new window) in an existing session, you can set that session’s history-limit. You might use a command like this (from a shell):

tmux set-option history-limit 5000 \; new-window

For (the initial pane of the initial window in) a new session you will need to set the “global” history-limit before creating the session:

tmux set-option -g history-limit 5000 \; new-session

Note: If you do not re-set the history-limit value, then the new value will be also used for other panes/windows/sessions created in the future; there is currently no direct way to create a single new pane/window/session with its own specific limit without (at least temporarily) changing history-limit (though show-option (especially in 1.7 and later) can help with retrieving the current value so that you restore it later).

Does Notepad++ show all hidden characters?

Yes, it does. The way to enable this depends on your version of Notepad++. On newer versions you can use:

Menu View ? Show Symbol ? *Show All Characters`

or

Menu View ? Show Symbol ? Show White Space and TAB

(Thanks to bers' comment and bkaid's answers below for these updated locations.)


On older versions you can look for:

Menu View ? Show all characters

or

Menu View ? Show White Space and TAB

How do I parallelize a simple Python loop?

I found joblib is very useful with me. Please see following example:

from joblib import Parallel, delayed
def yourfunction(k):   
    s=3.14*k*k
    print "Area of a circle with a radius ", k, " is:", s

element_run = Parallel(n_jobs=-1)(delayed(yourfunction)(k) for k in range(1,10))

n_jobs=-1: use all available cores

Display html text in uitextview

For some cases UIWebView is a good solution. Because:

  • it displays tables, images, other files
  • it's fast (comparing with NSAttributedString: NSHTMLTextDocumentType)
  • it's out of the box

Using NSAttributedString can lead to crashes, if html is complex or contains tables (so example)

For loading text to web view you can use the following snippet (just example):

func loadHTMLText(_ text: String?, font: UIFont) {
        let fontSize = font.pointSize * UIScreen.screens[0].scale
        let html = """
        <html><body><span style=\"font-family: \(font.fontName); font-size: \(fontSize)\; color: #112233">\(text ?? "")</span></body></html>
        """
        self.loadHTMLString(html, baseURL: nil)
    }

trying to animate a constraint in swift

It's very important to point out that view.layoutIfNeeded() applies to the view subviews only.

Therefore to animate the view constraint, it is important to call it on the view-to-animate superview as follows:

    topConstraint.constant = heightShift

    UIView.animate(withDuration: 0.3) {

        // request layout on the *superview*
        self.view.superview?.layoutIfNeeded()
    }

An example for a simple layout as follows:

class MyClass {

    /// Container view
    let container = UIView()
        /// View attached to container
        let view = UIView()

    /// Top constraint to animate
    var topConstraint = NSLayoutConstraint()


    /// Create the UI hierarchy and constraints
    func createUI() {
        container.addSubview(view)

        // Create the top constraint
        topConstraint = view.topAnchor.constraint(equalTo: container.topAnchor, constant: 0)


        view.translatesAutoresizingMaskIntoConstraints = false

        // Activate constaint(s)
        NSLayoutConstraint.activate([
           topConstraint,
        ])
    }

    /// Update view constraint with animation
    func updateConstraint(heightShift: CGFloat) {
        topConstraint.constant = heightShift

        UIView.animate(withDuration: 0.3) {

            // request layout on the *superview*
            self.view.superview?.layoutIfNeeded()
        }
    }
}

try/catch blocks with async/await

Alternatives

An alternative to this:

async function main() {
  try {
    var quote = await getQuote();
    console.log(quote);
  } catch (error) {
    console.error(error);
  }
}

would be something like this, using promises explicitly:

function main() {
  getQuote().then((quote) => {
    console.log(quote);
  }).catch((error) => {
    console.error(error);
  });
}

or something like this, using continuation passing style:

function main() {
  getQuote((error, quote) => {
    if (error) {
      console.error(error);
    } else {
      console.log(quote);
    }
  });
}

Original example

What your original code does is suspend the execution and wait for the promise returned by getQuote() to settle. It then continues the execution and writes the returned value to var quote and then prints it if the promise was resolved, or throws an exception and runs the catch block that prints the error if the promise was rejected.

You can do the same thing using the Promise API directly like in the second example.

Performance

Now, for the performance. Let's test it!

I just wrote this code - f1() gives 1 as a return value, f2() throws 1 as an exception:

function f1() {
  return 1;
}

function f2() {
  throw 1;
}

Now let's call the same code million times, first with f1():

var sum = 0;
for (var i = 0; i < 1e6; i++) {
  try {
    sum += f1();
  } catch (e) {
    sum += e;
  }
}
console.log(sum);

And then let's change f1() to f2():

var sum = 0;
for (var i = 0; i < 1e6; i++) {
  try {
    sum += f2();
  } catch (e) {
    sum += e;
  }
}
console.log(sum);

This is the result I got for f1:

$ time node throw-test.js 
1000000

real    0m0.073s
user    0m0.070s
sys     0m0.004s

This is what I got for f2:

$ time node throw-test.js 
1000000

real    0m0.632s
user    0m0.629s
sys     0m0.004s

It seems that you can do something like 2 million throws a second in one single-threaded process. If you're doing more than that then you may need to worry about it.

Summary

I wouldn't worry about things like that in Node. If things like that get used a lot then it will get optimized eventually by the V8 or SpiderMonkey or Chakra teams and everyone will follow - it's not like it's not optimized as a principle, it's just not a problem.

Even if it isn't optimized then I'd still argue that if you're maxing out your CPU in Node then you should probably write your number crunching in C - that's what the native addons are for, among other things. Or maybe things like node.native would be better suited for the job than Node.js.

I'm wondering what would be a use case that needs throwing so many exceptions. Usually throwing an exception instead of returning a value is, well, an exception.

C fopen vs open

First, there is no particularly good reason to use fdopen if fopen is an option and open is the other possible choice. You shouldn't have used open to open the file in the first place if you want a FILE *. So including fdopen in that list is incorrect and confusing because it isn't very much like the others. I will now proceed to ignore it because the important distinction here is between a C standard FILE * and an OS-specific file descriptor.

There are four main reasons to use fopen instead of open.

  1. fopen provides you with buffering IO that may turn out to be a lot faster than what you're doing with open.
  2. fopen does line ending translation if the file is not opened in binary mode, which can be very helpful if your program is ever ported to a non-Unix environment (though the world appears to be converging on LF-only (except IETF text-based networking protocols like SMTP and HTTP and such)).
  3. A FILE * gives you the ability to use fscanf and other stdio functions.
  4. Your code may someday need to be ported to some other platform that only supports ANSI C and does not support the open function.

In my opinion the line ending translation more often gets in your way than helps you, and the parsing of fscanf is so weak that you inevitably end up tossing it out in favor of something more useful.

And most platforms that support C have an open function.

That leaves the buffering question. In places where you are mainly reading or writing a file sequentially, the buffering support is really helpful and a big speed improvement. But it can lead to some interesting problems in which data does not end up in the file when you expect it to be there. You have to remember to fclose or fflush at the appropriate times.

If you're doing seeks (aka fsetpos or fseek the second of which is slightly trickier to use in a standards compliant way), the usefulness of buffering quickly goes down.

Of course, my bias is that I tend to work with sockets a whole lot, and there the fact that you really want to be doing non-blocking IO (which FILE * totally fails to support in any reasonable way) with no buffering at all and often have complex parsing requirements really color my perceptions.

Which is better, return value or out parameter?

I think one of the few scenarios where it would be useful would be when working with unmanaged memory, and you want to make it obvious that the "returned" value should be disposed of manually, rather than expecting it to be disposed of on its own.

What are all the escape characters?

You can find the full list here.

  • \t Insert a tab in the text at this point.
  • \b Insert a backspace in the text at this point.
  • \n Insert a newline in the text at this point.
  • \r Insert a carriage return in the text at this point.
  • \f Insert a formfeed in the text at this point.
  • \' Insert a single quote character in the text at this point.
  • \" Insert a double quote character in the text at this point.
  • \\ Insert a backslash character in the text at this point.

Return value in a Bash function

The problem with other answers is they either use a global, which can be overwritten when several functions are in a call chain, or echo which means your function cannot output diagnostic info (you will forget your function does this and the "result", i.e. return value, will contain more info than your caller expects, leading to weird bug), or eval which is way too heavy and hacky.

The proper way to do this is to put the top level stuff in a function and use a local with bash's dynamic scoping rule. Example:

func1() 
{
    ret_val=hi
}

func2()
{
    ret_val=bye
}

func3()
{
    local ret_val=nothing
    echo $ret_val
    func1
    echo $ret_val
    func2
    echo $ret_val
}

func3

This outputs

nothing
hi
bye

Dynamic scoping means that ret_val points to a different object depending on the caller! This is different from lexical scoping, which is what most programming languages use. This is actually a documented feature, just easy to miss, and not very well explained, here is the documentation for it (emphasis is mine):

Variables local to the function may be declared with the local builtin. These variables are visible only to the function and the commands it invokes.

For someone with a C/C++/Python/Java/C#/javascript background, this is probably the biggest hurdle: functions in bash are not functions, they are commands, and behave as such: they can output to stdout/stderr, they can pipe in/out, they can return an exit code. Basically there is no difference between defining a command in a script and creating an executable that can be called from the command line.

So instead of writing your script like this:

top-level code 
bunch of functions
more top-level code

write it like this:

# define your main, containing all top-level code
main() 
bunch of functions
# call main
main  

where main() declares ret_val as local and all other functions return values via ret_val.

See also the following Unix & Linux question: Scope of Local Variables in Shell Functions.

Another, perhaps even better solution depending on situation, is the one posted by ya.teck which uses local -n.

How can I create a table with borders in Android?

I used this solution: in TableRow, I created for every cell LinearLayout with vertical line and actual cell in it, and after every TableRow, I added a horizontal line.

Look at the code below:

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:shrinkColumns="1">

    <TableRow            
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <View
                    android:layout_height="match_parent"
                    android:layout_width="1dp"
                    android:background="#BDCAD2"/>

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>
      </TableRow>

      <View
        android:layout_height="1dip"
        android:background="#BDCAD2" />

      <!-- More TableRows -->
</TableLayout>

Hope it will help.

How to call gesture tap on UIView programmatically in swift

Complete answer for Swift 4

Step 1: create an outlet for the view

@IBOutlet weak var rightViewOutlet: UIView!

Step 2: define a tap gesture

var tapGesture = UITapGestureRecognizer()

Step 3: create ObjC function (called when view tapped)

@objc func rightViewTapped(_ recognizer: UIGestureRecognizer) {
    print("Right button is tapped")
}

Step 4: add the following within viewDidLoad()

let rightTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.rightViewTapped(_:)))
    rightViewOutlet.addGestureRecognizer(rightTap)

Convert UTC date time to local date time

Add the time zone at the end, in this case 'UTC':

theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));

after that, use toLocale()* function families to display the date in the correct locale

theDate.toLocaleString();  // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString();  // "9:52:48 AM"
theDate.toLocaleDateString();  // "6/29/2011"

Adding external resources (CSS/JavaScript/images etc) in JSP

The reason that you get the 404 File Not Found error, is that your path to CSS given as a value to the href attribute is missing context path.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

  • Context path: A concatenation of a forward slash (/) with the context root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]

  • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).

  • Path info: The part of the request path that is not part of the context path or the servlet path.

Read more here.


Solutions

There are several solutions to your problem, here are some of them:

1) Using <c:url> tag from JSTL

In my Java web applications I usually used <c:url> tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).

If you say, that your CSS is located inside WebContent folder, then this should work:

<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />

The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):

7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.

NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.


2) Using JSP Expression Language and implicit objects

An alternative solution is using Expression Language (EL) to add application context:

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />

Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.


3) Using <c:set> tag from JSTL

DISCLAIMER
The idea of this solution was taken from here.

To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set> tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.

<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />

IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.


4) Using ServletContextListener

The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.

We need a class that implements ServletContextListener interface. Here is an example of such class:

package com.example.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        sc.setAttribute("ctx", sc.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {}

}

Now in a JSP we can access this global variable using EL:

<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />

NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    ...  
    <listener>
        <listener-class>com.example.listener.AppContextListener</listener-class>
    </listener>
    ...
</webapp>


5) Using scriptlets

As suggested by user @gavenkoa you can also use scriptlets like this:

<%= request.getContextPath() %>

For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.


Conclusion

I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.


Other thoughts

You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.

Concatenating string and integer in python

Let's assume you want to concatenate string and integer in a situation like this:

for i in range(1,11):
   string="string"+i 

and you are getting type or concatenation error

The best way to go about it is to do something like this:

for i in range(1,11):
   print("string",i)    

This will give you concatenated results like string 1, string 2, string 3 ...etc

jquery, find next element by class

You cannot use next() in this scenario, if you look at the documentation it says:
Next() Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling that matches the selector.

so if the second DIV was in the same TD then you could code:


// Won't work in your case
$(obj).next().filter('.class');

But since it's not, I don't see a point to use next(). You can instead code:

$(obj).parents('table').find('.class')

How can I get a channel ID from YouTube?

At any channel page with "user" url for example http://www.youtube.com/user/klauskkpm, without API call, from YouTube UI, click a video of the channel (in its "VIDEOS" tab) and click the channel name on the video. Then you can get to the page with its "channel" url for example https://www.youtube.com/channel/UCfjTOrCPnAblTngWAzpnlMA.

asp.net Button OnClick event not firing

i had the same problem did all changed the button and all above mentioned methods then I did a simple thing I was using two forms on a single page and form with in the form so I removed one and it worked :)

How to center a (background) image within a div?

try background-position:center;

EDIT: since this question is getting lots of views, its worth adding some extra info:

text-align: center will not work because the background image is not part of the document and is therefore not part of the flow.

background-position:center is shorthand for background-position: center center; (background-position: horizontal vertical);

HttpContext.Current.Request.Url.Host what it returns?

Yes, as long as the url you type into the browser www.someshopping.com and you aren't using url rewriting then

string currentURL = HttpContext.Current.Request.Url.Host;

will return www.someshopping.com

Note the difference between a local debugging environment and a production environment

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

pyplot scatter plot marker size

If the size of the circles corresponds to the square of the parameter in s=parameter, then assign a square root to each element you append to your size array, like this: s=[1, 1.414, 1.73, 2.0, 2.24] such that when it takes these values and returns them, their relative size increase will be the square root of the squared progression, which returns a linear progression.

If I were to square each one as it gets output to the plot: output=[1, 2, 3, 4, 5]. Try list interpretation: s=[numpy.sqrt(i) for i in s]

How to do fade-in and fade-out with JavaScript and CSS

Here is a simplified running example of Seattle Ninja's solution.

_x000D_
_x000D_
var slideSource = document.getElementById('slideSource');_x000D_
_x000D_
document.getElementById('handle').onclick = function () {_x000D_
  slideSource.classList.toggle('fade');_x000D_
}
_x000D_
#slideSource {_x000D_
  opacity: 1;_x000D_
  transition: opacity 1s; _x000D_
}_x000D_
_x000D_
#slideSource.fade {_x000D_
  opacity: 0;_x000D_
}
_x000D_
<button id="handle">Fade</button> _x000D_
<div id="slideSource">Whatever you want here - images or text</div>
_x000D_
_x000D_
_x000D_

What's the proper value for a checked attribute of an HTML checkbox?

Strictly speaking, you should put something that makes sense - according to the spec here, the most correct version is:

<input name=name id=id type=checkbox checked=checked>

For HTML, you can also use the empty attribute syntax, checked="", or even simply checked (for stricter XHTML, this is not supported).

Effectively, however, most browsers will support just about any value between the quotes. All of the following will be checked:

<input name=name id=id type=checkbox checked>
<input name=name id=id type=checkbox checked="">
<input name=name id=id type=checkbox checked="yes">
<input name=name id=id type=checkbox checked="blue">
<input name=name id=id type=checkbox checked="false">

And only the following will be unchecked:

<input name=name id=id type=checkbox>

See also this similar question on disabled="disabled".

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

Get selected value of a dropdown's item using jQuery

The id that got generated for your drop down control in the html will be dynamic one. So use the complete id $('ct100_<Your control id>').val(). It will work.

Make Axios send cookies in its requests automatically

I had the same problem and fixed it by using the withCredentials property.

XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.

axios.get('some api url', {withCredentials: true});

How to setup Tomcat server in Netbeans?

In Netbeans 8 you may have to install the Tomcat plugin manually. After you download and extract Tomcat follow these steps:

  1. Tools -> Plugins -> Available plugins, search for 'tomcat' and install the one named "Java EE Base plugin".
  2. Restart Netbeans
  3. On the project view (default left side of the screen), go to services, right click on Servers and then "Add Server"
  4. Select Apache Tomcat, enter username and password and config the rest and finish

REST API using POST instead of GET

In REST, each HTTP verbs has its place and meaning.

For example,

  • GET is to get the 'resource(s)' that is pointed to in the URL.

  • POST is to instructure the backend to 'create' a resource of the 'type' pointed to in the URL. You can supplement the POST operation with parameters or additional data in the body of the POST call.

In you case, since you are interested in 'getting' the info using query, thus it should be a GET operation instead of a POST operation.

This wiki may help to further clarify things.

Hope this help!

How to increase font size in NeatBeans IDE?

Tools >> Options >> Fonts & Colors >> Syntax tab. Select 'Default' from the Category list and click the ... button like you said.

It's the Default you need to select first before changing the size.

How to validate GUID is a GUID

if(MyGuid!=Guild.Empty)

{

//Valid Guild

}

else {

// Invalid Guild

}

Text in Border CSS HTML

You can use a fieldset tag.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<form>_x000D_
 <fieldset>_x000D_
  <legend>Personalia:</legend>_x000D_
  Name: <input type="text"><br>_x000D_
  Email: <input type="text"><br>_x000D_
  Date of birth: <input type="text">_x000D_
 </fieldset>_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Check this link: HTML Tag

git status shows modifications, git checkout -- <file> doesn't remove them

I had also same symptoms but has been caused by different thing.

I was not able to:

git checkout app.js //did nothing
git rm app.js //did nothing
rm -rf app.js //did nothing

even on git rm --cached app.js it signs as deleted and in untracked files I could see app.js. But when I tried rm -rf app.js and peform git status again it still shows me the file in 'untracked'.

After couple of tries with colleague we found out, that it has been caused by Grunt!

As the Grunt has been turned on, and because app.js has been generated from couple of other js files we found out that after each operation with js files (also this app.js) grunt recreate app.js again.

What does "dereferencing" a pointer mean?

A pointer is a "reference" to a value.. much like a library call number is a reference to a book. "Dereferencing" the call number is physically going through and retrieving that book.

int a=4 ;
int *pA = &a ;
printf( "The REFERENCE/call number for the variable `a` is %p\n", pA ) ;

// The * causes pA to DEREFERENCE...  `a` via "callnumber" `pA`.
printf( "%d\n", *pA ) ; // prints 4.. 

If the book isn't there, the librarian starts shouting, shuts the library down, and a couple of people are set to investigate the cause of a person going to find a book that isn't there.

Cannot delete or update a parent row: a foreign key constraint fails

The main problem with this erorr Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails is that it doesn't let you know which table contains the FK failure, so it is difficult to solve the conflict.

If you use MySQL or similar, I found out that you can create an ER diagram for your database, then you can review and safely remove any conflicts triggering the error.

  1. Use MySQL workbench
  2. Click on Database -> Reverse Engineering
  3. Select a correct connection
  4. Next till the end, remember to select database & tables that need examine
  5. Now you have the ER diagram, you can see which table have FK conflict

Convert array to JSON

Wow, seems it got a lot easier nowadays... 3 ways you can do it:

json = { ...array };

json = Object.assign({}, array);

json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});

Why use Gradle instead of Ant or Maven?

Gradle put the fun back into building/assembling software. I used ant to build software my entire career and I have always considered the actual "buildit" part of the dev work being a necessary evil. A few months back our company grew tired of not using a binary repo (aka checking in jars into the vcs) and I was given the task to investigate this. Started with ivy since it could be bolted on top of ant, didn't have much luck getting my built artifacts published like I wanted. I went for maven and hacked away with xml, worked splendid for some simple helper libs but I ran into serious problems trying to bundle applications ready for deploy. Hassled quite a while googling plugins and reading forums and wound up downloading trillions of support jars for various plugins which I had a hard time using. Finally I went for gradle (getting quite bitter at this point, and annoyed that "It shouldn't be THIS hard!")

But from day one my mood started to improve. I was getting somewhere. Took me like two hours to migrate my first ant module and the build file was basically nothing. Easily fitted one screen. The big "wow" was: build scripts in xml, how stupid is that? the fact that declaring one dependency takes ONE row is very appealing to me -> you can easily see all dependencies for a certain project on one page. From then on I been on a constant roll, for every problem I faced so far there is a simple and elegant solution. I think these are the reasons:

  • groovy is very intuitive for java developers
  • documentation is great to awesome
  • the flexibility is endless

Now I spend my days trying to think up new features to add to our build process. How sick is that?

Javascript: Call a function after specific time period

ECMAScript 6 introduced arrow functions so now the setTimeout() or setInterval() don't have to look like this:

setTimeout(function() { FetchData(); }, 1000)

Instead, you can use annonymous arrow function which looks cleaner, and less confusing:

setTimeout(() => {FetchData();}, 1000)

How to write a UTF-8 file with Java?

Below sample code can read file line by line and write new file in UTF-8 format. Also, i am explicitly specifying Cp1252 encoding.

    public static void main(String args[]) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(
            new FileInputStream("c:\\filenonUTF.txt"),
            "Cp1252"));
    String line;

    Writer out = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(
                    "c:\\fileUTF.txt"), "UTF-8"));

    try {

        while ((line = br.readLine()) != null) {

            out.write(line);
            out.write("\n");

        }

    } finally {

        br.close();
        out.close();

    }
}

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

Confused about __str__ on list in Python

Well, container objects' __str__ methods will use repr on their contents, not str. So you could use __repr__ instead of __str__, seeing as you're using an ID as the result.

How to completely uninstall Visual Studio 2010?

If I may give an answer to an old thread; You can use PC Decrapifier to select programs you want to uninstall. PC Decrapifier will uninstall them one by one for you so you don't have to click them all seperately.

This is very useful for removing all the 'junk' - like the SQL Database tools - Visual Studio leaves behind even when uninstalled.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

We use the bulk insert as well. The file we upload is sent from an external party. After a while of troubleshooting, I realized that their file had columns with commas in it. Just another thing to look for...

How to make a <div> appear in front of regular text/tables

z-index only works on absolute or relatively positioned elements. I would use an outer div set to position relative. Set the div on top to position absolute to remove it from the flow of the document.

_x000D_
_x000D_
.wrapper {position:relative;width:500px;}_x000D_
_x000D_
.front {_x000D_
  border:3px solid #c00;_x000D_
  background-color:#fff;_x000D_
  width:300px;_x000D_
  position:absolute;_x000D_
  z-index:10;_x000D_
  top:30px;_x000D_
  left:50px;_x000D_
 }_x000D_
  _x000D_
.behind {background-color:#ccc;}
_x000D_
<div class="wrapper">_x000D_
    <p class="front">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>_x000D_
    <div class="behind">_x000D_
        <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>_x000D_
        <table>_x000D_
            <thead>_x000D_
                <tr>_x000D_
                    <th>aaa</th>_x000D_
                    <th>bbb</th>_x000D_
                    <th>ccc</th>_x000D_
                    <th>ddd</th>_x000D_
                </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
                <tr>_x000D_
                    <td>111</td>_x000D_
                    <td>222</td>_x000D_
                    <td>333</td>_x000D_
                    <td>444</td>_x000D_
                </tr>_x000D_
            </tbody>_x000D_
        </table>_x000D_
        <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>_x000D_
    </div> _x000D_
</div> 
_x000D_
_x000D_
_x000D_

React JS - Uncaught TypeError: this.props.data.map is not a function

You don't need an array to do it.

var ItemNode = this.state.data.map(function(itemData) {
return (
   <ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
 );
});

Why Is `Export Default Const` invalid?

You can also do something like this if you want to export default a const/let, instead of

const MyComponent = ({ attr1, attr2 }) => (<p>Now Export On other Line</p>);
export default MyComponent

You can do something like this, which I do not like personally.

let MyComponent;
export default MyComponent = ({ }) => (<p>Now Export On SameLine</p>);

Creating a list/array in excel using VBA to get a list of unique names in a column

FWIW, here's the dictionary thing. After setting a reference to MS Scripting. You can jack around with the array size of avInput to match your needs.

Sub somemacro()
Dim avInput As Variant
Dim uvals As Dictionary
Dim i As Integer
Dim rop As Range

avInput = Sheets("data").UsedRange
Set uvals = New Dictionary


For i = 1 To UBound(avInput, 1)
    If uvals.Exists(avInput(i, 1)) = False Then
        uvals.Add avInput(i, 1), 1
    Else
        uvals.Item(avInput(i, 1)) = uvals.Item(avInput(i, 1)) + 1
    End If
Next i

ReDim avInput(1 To uvals.Count)
i = 1

For Each kv In uvals.Keys
    avInput(i) = kv
    i = i + 1
Next kv

Set rop = Sheets("sheet2").Range("a1")
rop.Resize(UBound(avInput, 1), 1) = Application.Transpose(avInput)




End Sub

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);

How do you use MySQL's source command to import large files in windows

Option 1. you can do this using single cmd where D is my xampp or wampp install folder so i use this where mysql.exe install and second option database name and last is sql file so replace it as your then run this

D:\xampp\mysql\bin\mysql.exe -u root -p databse_name < D:\yoursqlfile.sql

Option 1 for wampp

D:\wamp64\bin\mysql\mysql5.7.14\bin\mysql.exe -u root -p databse_name< D:\yoursqlfile.sql

change your folder and mysql version

Option 2 Suppose your current path is which is showing command prompt

C:\Users\shafiq;

then change directory using cd.. then goto your mysql directory where your xampp installed. Then cd.. for change directory. then go to bin folder.

C:\xampp\mysql\bin;

C:\xampp\mysql\bin\mysql -u {username} -p {database password}.then please enter when you see enter password in command prompt.

choose database using

mysql->use test (where database name test) 

then put in source sql in bin folder.

then last command will be

mysql-> source test.sql (where test.sql is file name which need to import)

then press enter

This is full command

C:\Users\shafiq;
C:\xampp\mysql\bin
C:\xampp\mysql\bin\mysql -u {username} -p {database password}
 mysql-> use test
 mysql->source test.sql