Programs & Examples On #Nested includes

Setting up a websocket on Apache?

The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.

Can I display the value of an enum with printf()?

enum A { foo, bar } a;
a = foo;
printf( "%d", a );   // see comments below

joining two select statements

You should use UNION if you want to combine different resultsets. Try the following:

        FROM orders_products 
        INNER JOIN orders ON orders_products.orders_id = orders.orders_id  
        WHERE products_id = 181) AS A)

        FROM orders_products 
        INNER JOIN orders ON orders_products.orders_id = orders.orders_id 
        WHERE products_id = 180) AS B
ON A.orders_id=B.orders_id)

Function overloading in Javascript - Best practices


Checking / Switching inside the function is not OVERLOADING.

The concept of overloading: In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.

All suggested implementations are great, but truth to be told, there is no native implementation for JavaScript.

What does from __future__ import absolute_import actually do?

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/
$ touch pkg/
$ echo 'import string;print(string.ascii_uppercase)' > pkg/
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2

In particular:

$ python2 pkg/
Traceback (most recent call last):
  File "pkg/", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
$ python2 -m pkg.main2

Note that python2 pkg/ has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.

How to implode array with key and value without foreach in PHP

and another way:

$input = array(
    'item1'  => 'object1',
    'item2'  => 'object2',
    'item-n' => 'object-n'

$output = implode(', ', array_map(
    function ($v, $k) {
            return $k.'[]='.implode('&'.$k.'[]=', $v);
            return $k.'='.$v;


$output = implode(', ', array_map(
    function ($v, $k) { return sprintf("%s='%s'", $k, $v); },

How does the "final" keyword in Java work? (I can still modify an object.)

If you make foo static, you must initialize it in the class constructor (or inline where you define it) like the following examples.

Class constructor (not instance):

private static final List foo;

   foo = new ArrayList();


private static final List foo = new ArrayList();

The problem here is not how the final modifier works, but rather how the static modifier works.

The final modifier enforces an initialization of your reference by the time the call to your constructor completes (i.e. you must initialize it in the constructor).

When you initialize an attribute in-line, it gets initialized before the code you have defined for the constructor is run, so you get the following outcomes:

  • if foo is static, foo = new ArrayList() will be executed before the static{} constructor you have defined for your class is executed
  • if foo is not static, foo = new ArrayList() will be executed before your constructor is run

When you do not initilize an attribute in-line, the final modifier enforces that you initialize it and that you must do so in the constructor. If you also have a static modifier, the constructor you will have to initialize the attribute in is the class' initialization block : static{}.

The error you get in your code is from the fact that static{} is run when the class is loaded, before the time you instantiate an object of that class. Thus, you will have not initialized foo when the class is created.

Think of the static{} block as a constructor for an object of type Class. This is where you must do the initialization of your static final class attributes (if not done inline).

Side note:

The final modifier assures const-ness only for primitive types and references.

When you declare a final object, what you get is a final reference to that object, but the object itself is not constant.

What you are really achieving when declaring a final attribute is that, once you declare an object for your specific purpose (like the final List that you have declared), that and only that object will be used for that purpose: you will not be able to change List foo to another List, but you can still alter your List by adding/removing items (the List you are using will be the same, only with its contents altered).

Excel "External table is not in the expected format."

ACE has Superceded JET

Ace Supports all Previous versions of Office

This Code works well!

        OleDbConnection MyConnection;
        DataSet DtSet;
        OleDbDataAdapter MyCommand;
        MyConnection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\\Book.xlsx;Extended Properties=Excel 12.0;");
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
        DtSet = new System.Data.DataSet();
        dataGridView1.DataSource = DtSet.Tables[0];

How do I get the current absolute URL in Ruby on Rails?

You can set a variable to URI.parse(current_url), I don't see this proposal here yet and it works for me.

Get the data received in a Flask request

The raw data is passed in to the Flask application from the WSGI server as The length of the stream is in the Content-Length header.

length = request.headers["Content-Length"]
data =

It is usually safer to use request.get_data() instead.

Scale the contents of a div by a percentage?

You can simply use the zoom property:

    zoom: 0.5;
    -moz-transform: scale(0.5);

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

make: Nothing to be done for `all'

Make is behaving correctly. hello already exists and is not older than the .c files, and therefore there is no more work to be done. There are four scenarios in which make will need to (re)build:

  • If you modify one of your .c files, then it will be newer than hello, and then it will have to rebuild when you run make.
  • If you delete hello, then it will obviously have to rebuild it
  • You can force make to rebuild everything with the -B option. make -B all
  • make clean all will delete hello and require a rebuild. (I suggest you look at @Mat's comment about rm -f *.o hello

C# removing items from listbox

You can't use an enumerator, you have to loop using an index, starting at the last item:

for (int n = listBox1.Items.Count - 1; n >= 0; --n)
    string removelistitem = "OBJECT";
    if (listBox1.Items[n].ToString().Contains(removelistitem))

Where can I download JSTL jar

You can download JSTL 1.1 here and JSTL 1.2 here.

See also:

HTML5 Number Input - Always show 2 decimal places

Based on this answer from @Guilherme Ferreira you can trigger the parseFloat method every time the field changes. Therefore the value always shows two decimal places, even if a user changes the value by manual typing a number.

<script src=""></script>_x000D_
<script type="text/javascript">_x000D_
    $(document).ready(function () {_x000D_
        $(".floatNumberField").change(function() {_x000D_
<input type="number" class="floatNumberField" value="0.00" placeholder="0.00" step="0.01" />

Efficient way to determine number of digits in an integer

int digits = 0; while (number != 0) { number /= 10; digits++; }

Note: "0" will have 0 digits! If you need 0 to appear to have 1 digit, use:

int digits = 0; do { number /= 10; digits++; } while (number != 0);

(Thanks Kevin Fegan)

In the end, use a profiler to know which of all the answers here will be faster on your machine...

jquery find closest previous sibling with class

You can follow this code:

<script src=""></script>
    $(document).ready(function () {
        $(".add").on("click", function () {
            var v = $(this).closest(".division").find("input[name='roll']").val();

for ($i = 1; $i <= 5; $i++) {
    echo'<div class = "division">'
        . '<form method="POST" action="">'
        . '<p><input type="number" name="roll" placeholder="Enter Roll"></p>'
        . '<p><input type="button" class="add" name = "submit" value = "Click"></p>'
        . '</form></div>';

You can get idea from this.

ExtJs Gridpanel store refresh

Another approach in 3.4 (don't know if this is proper Ext): You can have a delete handler like this, assuming every row has a 'delete' button.

handler: function(grid, rowIndex, colIndex) {
    var rec = grid.getStore().getAt(rowIndex);
    var id = rec.get('id');
    // some DELETE/GET ajax callback here...
    // pass in 'id' var or some key
    // inside success

How do I check if an object's type is a particular subclass in C++?

I don't know if I understand your problem correctly, so let me restate it in my own words...

Problem: Given classes B and D, determine if D is a subclass of B (or vice-versa?)

Solution: Use some template magic! Okay, seriously you need to take a look at LOKI, an excellent template meta-programming library produced by the fabled C++ author Andrei Alexandrescu.

More specifically, download LOKI and include header TypeManip.h from it in your source code then use the SuperSubclass class template as follows:


According to documentation, SuperSubClass<B,D>::value will be true if B is a public base of D, or if B and D are aliases of the same type.

i.e. either D is a subclass of B or D is the same as B.

I hope this helps.


Please note the evaluation of SuperSubClass<B,D>::value happens at compile time unlike some methods which use dynamic_cast, hence there is no penalty for using this system at runtime.

.mp4 file not playing in chrome

This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-

<!DOCTYPE html>
<video  controls >
 <source src="sample.mp4" type="video/mp4">
 <track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">

the video and subtitle files are stored in the same folder as default.htm

I have the very latest version of Chrome (just updated this morning)

When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!

(note that if I input localhost.. to IE11 the video plays!!!!

In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.

This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4

How to change color of SVG image using CSS (jQuery SVG image replacement)?

The selected solution is fine if you want jQuery to process all svg elements in your DOM and your DOM is of reasonable size. But if your DOM is large and you decide to load parts of your DOM dynamically, it really makes no sense to have to rescan the entire DOM just to update svg elements. Instead, use a jQuery plugin to do this:

 * A jQuery plugin that loads an svg file and replaces the jQuery object with its contents.
 * The path to the svg file is specified in the src attribute (which normally does not exist for an svg element).
 * The width, height and class attributes in the loaded svg will be replaced by those that exist in the jQuery object's
 * underlying html. Note: All other attributes in the original element are lost including the style attribute. Place
 * any styles in a style class instead.
(function ($) {
    $.fn.svgLoader = function () {
        var src = $(this).attr("src");
        var width = this.attr("width");
        var height = this.attr("height");
        var cls = this.attr("class");
        var ctx = $(this);

        // Get the svg file and replace the <svg> element.
            url: src,
            cache: false
        }).done(function (html) {
            let svg = $(html);
            svg.attr("width", width);
            svg.attr("height", height);
            svg.attr("class", cls);
            var newHtml = $('<a></a>').append(svg.clone()).html();

        return this;


In your html, specify an svg element as follows:

<svg src="images/someSvgFile.svg" height="45" width="45" class="mySVGClass"/>

And apply the plugin:


need to add a class to an element

Try using setAttribute on the result:


How to get all selected values from <select multiple=multiple>?

Works everywhere without jquery:

var getSelectValues = function (select) {
    var ret = [];

    // fast but not universally supported
    if (select.selectedOptions != undefined) {
        for (var i=0; i < select.selectedOptions.length; i++) {

    // compatible, but can be painfully slow
    } else {
        for (var i=0; i < select.options.length; i++) {
            if (select.options[i].selected) {
    return ret;

How can I see the entire HTTP request that's being sent by my Python application?

You can use HTTP Toolkit to do exactly this.

It's especially useful if you need to do this quickly, with no code changes: you can open a terminal from HTTP Toolkit, run any Python code from there as normal, and you'll be able to see the full content of every HTTP/HTTPS request immediately.

There's a free version that can do everything you need, and it's 100% open source.

I'm the creator of HTTP Toolkit; I actually built it myself to solve the exact same problem for me a while back! I too was trying to debug a payment integration, but their SDK didn't work, I couldn't tell why, and I needed to know what was actually going on to properly fix it. It's very frustrating, but being able to see the raw traffic really helps.

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

If it is just single column to delete the below syntax works

ALTER TABLE tablename DROP COLUMN column1;

For deleting multiple columns, using the DROP COLUMN doesnot work, the below syntax works

ALTER TABLE tablename DROP (column1, column2, column3......);

forEach is not a function error with JavaScript array

There is no need for the forEach, you can iterate using only the from's second parameter, like so:

let nodeList = [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]_x000D_
Array.from(nodeList, child => {_x000D_

How can I make setInterval also work when a tab is inactive in Chrome?

Note: this solution is not suitable if you like your interval works on the background, for example, playing audio or ... but if you are confused for example about your animation not working properly when coming back to your page(tab) this is a good solution.

There are many ways to achieve this goal, maybe the "WebWorkers" is the most standard one but certainly, it's not the easiest and handy one, especially If you don't have enough Time, so you can try this way:


1- build a name for your interval(or animation) and set your interval(animation), so it would run when user first time open your page : var interval_id = setInterval(your_func, 3000);

2- by $(window).focus(function() {}); and $(window).blur(function() {}); you can clearInterval(interval_id) everytime browser(tab) is deactived and ReRun your interval(animation) everytime browser(tab) would acive again by interval_id = setInterval();


var interval_id = setInterval(your_func, 3000);

$(window).focus(function() {
    interval_id = setInterval(your_func, 3000);
$(window).blur(function() {
    interval_id = 0;

Is there an easy way to check the .NET Framework version?

Little large, but looks like it is up-to-date to Microsoft oddities:

    public static class Versions
        static Version 

        static SortedList<String,Version>

#if NET40
        public static bool VersionTry(String S, out Version V)
                V=new Version(S); 
                return true;
                return false;
        const string _NetFrameWorkKey = "SOFTWARE\\Microsoft\\NET Framework Setup\\NDP";
        static void FillNetInstalled()
            if (_NETInstalled == null)
                _NETInstalled = new SortedList<String, Version>(StringComparer.InvariantCultureIgnoreCase);
                    frmks = Registry.LocalMachine.OpenSubKey(_NetFrameWorkKey);
                    names = frmks.GetSubKeyNames();
                foreach (string name in names)
                    if (name.StartsWith("v", StringComparison.InvariantCultureIgnoreCase) && name.Length > 1)
                            f, vs;
                        vs = name.Substring(1);
                        if (vs.IndexOf('.') < 0)
                            vs += ".0";
#if NET40
                        if (Version.TryParse(vs, out v))
                        if (VersionTry(vs, out v))
                            f = String.Format("{0}.{1}", v.Major, v.Minor);
#if NET40
                            if (Version.TryParse((string)frmks.OpenSubKey(name).GetValue("Version"), out v))
                            if (VersionTry((string)frmks.OpenSubKey(name).GetValue("Version"), out v))
                                if (!_NETInstalled.ContainsKey(f) || v.CompareTo(_NETInstalled[f]) > 0)
                                    _NETInstalled[f] = v;
                            { // parse variants
                                    best = null;
                                if (_NETInstalled.ContainsKey(f))
                                    best = _NETInstalled[f];
                                    varieties = frmks.OpenSubKey(name).GetSubKeyNames();
                                foreach (string variety in varieties)
#if NET40
                                    if (Version.TryParse((string)frmks.OpenSubKey(name + '\\' + variety).GetValue("Version"), out v))
                                    if (VersionTry((string)frmks.OpenSubKey(name + '\\' + variety).GetValue("Version"), out v))
                                        if (best == null || v.CompareTo(best) > 0)
                                            _NETInstalled[f] = v;
                                            best = v;
                                        vs = f + '.' + variety;
                                        if (!_NETInstalled.ContainsKey(vs) || v.CompareTo(_NETInstalled[vs]) > 0)
                                            _NETInstalled[vs] = v;
        } // static void FillNetInstalled()

        public static Version NETInstalled
                return _NETInstalled[_NETInstalled.Keys[_NETInstalled.Count-1]];
        } // NETInstalled

        public static Version NET
                    clr = String.Format("{0}.{1}", Environment.Version.Major, Environment.Version.Minor);
                    found = _NETInstalled[_NETInstalled.Keys[_NETInstalled.Count-1]];
                    return _NETInstalled[clr];

                for (int i = _NETInstalled.Count - 1; i >= 0; i--)
                    if (_NETInstalled.Keys[i].CompareTo(clr) < 0)
                        return found;
                        found = _NETInstalled[_NETInstalled.Keys[i]];
                return found;
        } // NET

Node.js getaddrinfo ENOTFOUND

in my case error was because of using incorrect host value was

  var options = {
    host: '',
    path: path

should be

  var options = {
    host: '',
    path: path

so anything after .com or .net etc should be moved to path parameter value

Trim to remove white space

jQuery.trim() capital Q?

or $.trim()

How to determine equality for two JavaScript objects?

Depends on what you mean by equality. And therefore it is up to you, as the developer of the classes, to define their equality.

There's one case used sometimes, where two instances are considered 'equal' if they point to the same location in memory, but that is not always what you want. For instance, if I have a Person class, I might want to consider two Person objects 'equal' if they have the same Last Name, First Name, and Social Security Number (even if they point to different locations in memory).

On the other hand, we can't simply say that two objects are equal if the value of each of their members is the same, since, sometimes, you don't want that. In other words, for each class, it's up to the class developer to define what members make up the objects 'identity' and develop a proper equality operator (be it via overloading the == operator or an Equals method).

Saying that two objects are equal if they have the same hash is one way out. However you then have to wonder how the hash is calculated for each instance. Going back to the Person example above, we could use this system if the hash was calculated by looking at the values of the First Name, Last Name, and Social Security Number fields. On top of that, we are then relying on the quality of the hashing method (that's a huge topic on its own, but suffice it to say that not all hashes are created equal, and bad hashing methods can lead to more collisions, which in this case would return false matches).

Clone() vs Copy constructor- which is recommended in java

Great sadness: neither Cloneable/clone nor a constructor are great solutions: I DON'T WANT TO KNOW THE IMPLEMENTING CLASS!!! (e.g. - I have a Map, which I want copied, using the same hidden MumbleMap implementation) I just want to make a copy, if doing so is supported. But, alas, Cloneable doesn't have the clone method on it, so there is nothing to which you can safely type-cast on which to invoke clone().

Whatever the best "copy object" library out there is, Oracle should make it a standard component of the next Java release (unless it already is, hidden somewhere).

Of course, if more of the library (e.g. - Collections) were immutable, this "copy" task would just go away. But then we would start designing Java programs with things like "class invariants" rather than the verdammt "bean" pattern (make a broken object and mutate until good [enough]).

How to get a list of programs running with nohup

If you have standart output redirect to "nohup.out" just see who use this file

lsof | grep nohup.out

Reactjs: Unexpected token '<' Error

Check if .babelrc is inside your application root folder, not inside a subfolder. if that's the case move file to root.

UIView background color in Swift

self.view.backgroundColor = UIColor.redColor()

In Swift 3:

self.view.backgroundColor =

iOS: UIButton resize according to text length

In Xcode 4.5 and above, this can now be done by using 'Auto-layouting / Constraints'.

Major advantages are that:

  1. You don't need to programmatically set frames at all!
  2. If done right, you don't need to bother about resetting frames for orientation changes.
  3. Also, device changes needn't bother you (read, no need to code separately for different screen sizes).

A few disadvantages:

  1. Not backward compatible - works only for iOS 6 and above.
  2. Need to get familiarised (but will save time later on).

Coolest thing is we get to focus on declaring an intent such as:

  • I want these two buttons to be of the same width; or
  • I need this view to be vertically centered and extend to a max entent of 10 pts from the superview's edge; or even,
  • I want this button/label to resize according to the label it is displaying!

Here is a simple tutorial to get introduced to auto-layouting.

For a more details.

It takes some time at first, but it sure looks like it will be well worth the effort.

Can we pass model as a parameter in RedirectToAction?

    public async Task<ActionResult> Capture(string imageData)
        if (imageData.Length > 0)
            var imageBytes = Convert.FromBase64String(imageData);
            using (var stream = new MemoryStream(imageBytes))
                var result = (JsonResult)await IdentifyFace(stream);
                var serializer = new JavaScriptSerializer();
                var faceRecon = serializer.Deserialize<FaceIdentity>(serializer.Serialize(result.Data));

                if (faceRecon.Success) return RedirectToAction("Index", "Auth", new { param = serializer.Serialize(result.Data) });


        return Json(new { success = false, responseText = "Der opstod en fejl - Intet billede, manglede data." }, JsonRequestBehavior.AllowGet);


// GET: Auth
    public ActionResult Index(string param)
        var serializer = new JavaScriptSerializer();
        var faceRecon = serializer.Deserialize<FaceIdentity>(param);

        return View(faceRecon);

Difference between Relative path and absolute path in javascript

If you use the relative version on your browser will look at for the image and would get 404 - Not found.

What is the role of "Flatten" in Keras?

I came across this recently, it certainly helped me understand:

So there's an input, a Conv2D, MaxPooling2D etc, the Flatten layers are at the end and show exactly how they are formed and how they go on to define the final classifications (0-9).

1064 error in CREATE TABLE ... TYPE=MYISAM

FROM user_log    
GROUP BY Email    
HAVING COUNT(*) > 1    

MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TYPE=MyISAM' at line 36

Which correction below:

CREATE TABLE users_online (
  ip varchar(15) NOT NULL default '',
  time int(11) default NULL,
  PRIMARY KEY  (ip),
  UNIQUE KEY id (ip),
  KEY id_2 (ip)
# Data untuk tabel `users_online`

INSERT INTO users_online VALUES ('', 1158666872);

How to do IF NOT EXISTS in SQLite

If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:

CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));

And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:

INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');

It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.

Page scroll when soft keyboard popped up

Also if you want to do that programmatically just add the below line to the onCreate of the activity.

            WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | 
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE );

Running npm command within Visual Studio Code

On Win10 I had to run VSCode as administrator to npm commands work.

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: (Courtesy of Old Pro in the comments)

Ruby: How to turn a hash into HTTP parameters?

Update: This functionality was removed from the gem.

Julien, your self-answer is a good one, and I've shameless borrowed from it, but it doesn't properly escape reserved characters, and there are a few other edge cases where it breaks down.

require "addressable/uri"
uri =
uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
# => "a=a&b[0]=c&b[1]=d&b[2]=e"
uri.query_values = {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]}
# => "a=a&b[0][c]=c&b[0][d]=d&b[1][e]=e&b[1][f]=f"
uri.query_values = {:a => "a", :b => {:c => "c", :d => "d"}}
# => "a=a&b[c]=c&b[d]=d"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}}
# => "a=a&b[c]=c&b[d]"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}, :e => []}
# => "a=a&b[c]=c&b[d]"

The gem is 'addressable'

gem install addressable

How do I set the eclipse.ini -vm option?

I'd like to share this little hack:

A click on the Eclipse's icon indicated a problem with the JRE. So, I put this command in the destination field of the icon's properties:

C:\...\eclipse.exe -vm c:\'Program Files'\Java\jdk1.7.0_51\jre\bin\javaw

Thinking that the "'" would solve the problem with the space in the path. That did not function. Then, I tried this command:

C:\...\eclipse.exe -vm c:\Progra~1\Java\jdk1.7.0_51\jre\bin\javaw

with success

How to perform an SQLite query within an Android application?

Alternatively, db.rawQuery(sql, selectionArgs) exists.

Cursor c = db.rawQuery(select, null);

Putting -moz-available and -webkit-fill-available in one width (css property)

CSS will skip over style declarations it doesn't understand. Mozilla-based browsers will not understand -webkit-prefixed declarations, and WebKit-based browsers will not understand -moz-prefixed declarations.

Because of this, we can simply declare width twice:

elem {
    width: 100%;
    width: -moz-available;          /* WebKit-based browsers will ignore this. */
    width: -webkit-fill-available;  /* Mozilla-based browsers will ignore this. */
    width: fill-available;

The width: 100% declared at the start will be used by browsers which ignore both the -moz and -webkit-prefixed declarations or do not support -moz-available or -webkit-fill-available.

Size-limited queue that holds last N elements in Java

The only thing I know that has limited space is the BlockingQueue interface (which is e.g. implemented by the ArrayBlockingQueue class) - but they do not remove the first element if filled, but instead block the put operation until space is free (removed by other thread).

To my knowledge your trivial implementation is the easiest way to get such an behaviour.

PHP mPDF save file as PDF

This can be done like this. It worked fine for me. And also set the directory permissions to 777 or 775 if not set.

$mpdf->Output('directory_name/pdf_file_name.pdf', 'F');

How do I set multipart in axios with react?

If you are sending alphanumeric data try changing

'Content-Type': 'multipart/form-data'


'Content-Type': 'application/x-www-form-urlencoded'

If you are sending non-alphanumeric data try to remove 'Content-Type' at all.

If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)

How to create web service (server & Client) in Visual Studio 2012?

WCF is a newer technology that is a viable alternative in many instances. ASP is great and works well, but I personally prefer WCF. And you can do it in .Net 4.5.

WCF Project

enter image description here

Create a new project. enter image description here Right-Click on the project in solution explorer, select "Add Service Reference" enter image description here

Create a textbox and button in the new application. Below is my click event for the button:

private void btnGo_Click(object sender, EventArgs e)
        ServiceReference1.Service1Client testClient = new ServiceReference1.Service1Client();
        //Add error handling, null checks, etc...
        int iValue = int.Parse(txtInput.Text);
        string sResult = testClient.GetData(iValue).ToString();

And you're done. enter image description here

Arrays.asList() of an array

I think you have found an example where auto-boxing doesn't really work. Because Arrays.asList(T... a) has a varargs parameter the compiler apparently considers the int[] and returns a List<int[]> with a single element in it.

You should change the method into this:

public int getTheNumber(Integer[] factors) {
    ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));  
    return f.get(0) * f.get(f.size() - 1);

and possibly add this for compatibility

public int getTheNumber(int[] factors) {
    Integer[] factorsInteger = new Integer[factors.length];
    for(int ii=0; ii<factors.length; ++ii) {
        factorsInteger[ii] = factors[ii];

    return getTheNumber(factorsInteger);

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

I used to meet the similar problem because 'localhost' was not available on server when it restarted network service, e.g. 'ifdown -a' but followed by only 'ifup -eo1'. Besides server is not listening to the port, you can also check 'localhost' is available or not.

ps: Post it just hope someone who has the similar problem may benefit.

How can I exclude multiple folders using Get-ChildItem -exclude?

I'd do it like this:

Get-ChildItem -Path $folder -r  | 
          ? { $_.PsIsContainer -and $_.FullName -notmatch 'archive' }

request exceeds the configured maxQueryStringLength when using [Authorize]

When an unauthorized request comes in, the entire request is URL encoded, and added as a query string to the request to the authorization form, so I can see where this may result in a problem given your situation.

According to MSDN, the correct element to modify to reset maxQueryStringLength in web.config is the <httpRuntime> element inside the <system.web> element, see httpRuntime Element (ASP.NET Settings Schema). Try modifying that element.

How to compile and run a C/C++ program on the Android system

If you want to compile and run Java/C/C++ apps directly on your Android device, I recommend the Terminal IDE environment from Google Play. It's a very slick package to develop and compile Android APKs, Java, C and C++ directly on your device. The interface is all command line and "vi" based, so it has real Linux feel. It comes with the gnu C/C++ implementation.

Additionally, there is a telnet and telnet server application built in, so you can do all the programming with your PC and big keyboard, but working on the device. No root permission is needed.

Create Log File in Powershell

function WriteLog
    Param ([string]$LogString)
    $LogFile = "C:\$(gc env:computername).log"
    $DateTime = "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
    $LogMessage = "$Datetime $LogString"
    Add-content $LogFile -value $LogMessage

WriteLog "This is my log message"

matplotlib does not show my drawings although I call

After running your code include:

import pylab as p

Driver executable must be set by the system property

I just put the driver files directly into my project to not get any dependency to my local machine.

final File file = new File("driver/chromedriver_2_22_mac");
System.setProperty("", file.getAbsolutePath());

driver = new ChromeDriver();

Tried to Load Angular More Than Once

I had this same problem ("Tried to Load Angular More Than Once") because I had included twice angularJs file (without perceive) in my index.html.

<script src="angular.js">
<script src="angular.min.js">

How can I change the Y-axis figures into percentages in a barplot?


+ scale_y_continuous(labels = scales::percent)

Or, to specify formatting parameters for the percent:

+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))

(the command labels = percent is obsolete since version 2.2.1 of ggplot2)

How to get name of the computer in VBA?

A shell method to read the environmental variable for this courtesy of devhut

Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")

Same source gives an API method:

Option Explicit

#If VBA7 And Win64 Then
    'x64 Declarations
    Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
    'x32 Declaration
    Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If

Public Sub test()

    Debug.Print ComputerName
End Sub

Public Function ComputerName() As String
    Dim sBuff                 As String * 255
    Dim lBuffLen              As Long
    Dim lResult               As Long
    lBuffLen = 255
    lResult = GetComputerName(sBuff, lBuffLen)
    If lBuffLen > 0 Then
        ComputerName = Left(sBuff, lBuffLen)
    End If
End Function

Getting JavaScript object key list

obj = {'a':'c','b':'d'}

You can try:

[index for (index in obj)] 

this will return:


to get the list of keys or

[obj[index] for (index in obj)]

to get the values

How to get `DOM Element` in Angular 2?

Angular 2.0.0 Final:

I have found that using a ViewChild setter is most reliable way to set the initial form control focus:

set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => {
            this._renderer.invokeElementMethod(_input.nativeElement, "focus");
        }, 0);

The setter is first called with an undefined value followed by a call with an initialized ElementRef.

Working example and full source here:

Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).

UPDATE for Angular 4+

Renderer has been deprecated in favor of Renderer2, but Renderer2 does not have the invokeElementMethod. You will need to access the DOM directly to set the focus as in input.nativeElement.focus().

I'm still finding that the ViewChild setter approach works best. When using AfterViewInit I sometimes get read property 'nativeElement' of undefined error.

set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => { //This setTimeout call may not be necessary anymore.
        }, 0);

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

The permission denied error probably indicates that SSH private key authentication has failed. Assuming that you're using an image derived from the Debian or Centos images recommended by gcutil, it's likely one of the following:

  1. You don't have any ssh keys loaded into your ssh keychain, and you haven't specified a private ssh key with the -i option.
  2. None of your ssh keys match the entries in .ssh/authorized_keys for the account you're attempting to log in to.
  3. You're attempting to log into an account that doesn't exist on the machine, or attempting to log in as root. (The default images disable direct root login – most ssh brute-force attacks are against root or other well-known accounts with weak passwords.)

How to determine what accounts and keys are on the instance:

There's a script that runs every minute on the standard Compute Engine Centos and Debian images which fetches the 'sshKeys' metadata entry from the metadata server, and creates accounts (with sudoers access) as necessary. This script expects entries of the form "account:\n" in the sshKeys metadata, and can put several entries into authorized_keys for a single account. (or create multiple accounts if desired)

In recent versions of the image, this script sends its output to the serial port via syslog, as well as to the local logs on the machine. You can read the last 1MB of serial port output via gcutil getserialportoutput, which can be handy when the machine isn't responding via SSH.

How gcutil ssh works:

gcutil ssh does the following:

  1. Looks for a key in $HOME/.ssh/google_compute_engine, and calls ssh-keygen to create one if not present.
  2. Checks the current contents of the project metadata entry for sshKeys for an entry that looks like ${USER}:$(cat $HOME/.ssh/
  3. If no such entry exists, adds that entry to the project metadata, and waits for up to 5 minutes for the metadata change to propagate and for the script inside the VM to notice the new entry and create the new account.
  4. Once the new entry is in place, (or immediately, if the user:key was already present) gcutil ssh invokes ssh with a few command-line arguments to connect to the VM.

A few ways this could break down, and what you might be able to do to fix them:

  1. If you've removed or modified the scripts that read sshKeys, the console and command line tool won't realize that modifying sshKeys doesn't work, and a lot of the automatic magic above can get broken.
  2. If you're trying to use raw ssh, it may not find your .ssh/google_compute_engine key. You can fix this by using gcutil ssh, or by copying your ssh public key (ends in .pub) and adding to the sshKeys entry for the project or instance in the console. (You'll also need to put in a username, probably the same as your local-machine account name.)
  3. If you've never used gcutil ssh, you probably don't have a .ssh/ file. You can either use ssh-keygen to create a new SSH public/private keypair and add it to sshKeys, as above, or use gcutil ssh to create them and manage sshKeys.
  4. If you're mostly using the console, it's possible that the account name in the sshKeys entry doesn't match your local username, you may need to supply the -l argument to SSH.

IE11 Document mode defaults to IE7. How to reset?

For the website ensure that IIS HTTP response headers setting and add new key X-UA-Compatible pointing to "IE=edge"

Click here for more details

If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add Name: X-UA-Compatible Value: IE=edge This will override your browser and your code.

Regular Expression usage with ls

You are confusing regular expression with shell globbing. If you want to use regular expression to match file names you could do:

$ ls | egrep '.+\..+'

How do you calculate log base 2 in Java for integers?

To add to x4u answer, which gives you the floor of the binary log of a number, this function return the ceil of the binary log of a number :

public static int ceilbinlog(int number) // returns 0 for bits=0
    int log = 0;
    int bits = number;
    if ((bits & 0xffff0000) != 0) {
        bits >>>= 16;
        log = 16;
    if (bits >= 256) {
        bits >>>= 8;
        log += 8;
    if (bits >= 16) {
        bits >>>= 4;
        log += 4;
    if (bits >= 4) {
        bits >>>= 2;
        log += 2;
    if (1 << log < number)
    return log + (bits >>> 1);

How to solve npm error "npm ERR! code ELIFECYCLE"

This solved me on ubuntu 16

1) Update npm and node to latest version . 2) Restart System 3) Remove node_modules and again npm i & npm start

How can I find the maximum value and its index in array in MATLAB?

This will return the maximum value in a matrix


This will return the row and the column of that value


For minimum just swap the word max with min and that's all.

How to use Monitor (DDMS) tool to debug application

I think things (location) have changed little bit. For: Android Studio Build @AI-141.1903250 - built on May 5, 2015

Franco Rondinis answer should be

To track memory allocation of objects:

  1. Start your app as described in Run Your App in Debug Mode.
  2. Click Android to open the Android DDMS tool window.
  3. Select your device from the dropdown list.
  4. Select your app by its package name from the list of running apps.
  5. On the Android DDMS tool window, select Memory tab.
  6. Click Start Allocation Tracking Interact with your app on the device. Click Stop Allocation Tracking (same icon)

how to start allocation tracking in android studio

git am error: "patch does not apply"

git format-patch also has the -B flag.

The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).

This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.

An example:

git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch

Outline radius?

Try using padding and a background color for the border, then a border for the outline:

.round_outline {
  padding: 8px;
  background-color: white;
  border-radius: 50%;
  border: 1px solid black;

Worked in my case.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

OSX users can follow by Nicolay77 or mikkom that uses the mdbtools utility. You can install it via Homebrew. Just have your homebrew installed and then go

$ homebrew install mdbtools

Then create one of the scripts described by the guys and use it. I've used mikkom's one, converted all my mdb files into sql.

$ ./ myfile.mdb > myfile.sql

(which btw contains more than 1 table)

Polygon Drawing and Getting Coordinates with Google Map API v3

It's cleaner/safer to use the getters provided by google instead of accessing the properties like some did

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
    var coordinatesArray = polygon.overlay.getPath().getArray();

jQuery .scrollTop(); + animation

jQuery("html,body").animate({scrollTop: jQuery("#your-elemm-id-where you want to scroll").offset().top-<some-number>}, 500, 'swing', function() { 
       alert("Finished animating");

Calling Python in Java?

GraalVM is a good choice. I've done Java+Javascript combination with GraalVM for microservice design (Java with Javascript reflection). They recently added support for python, I'd give it a try especially with how big its community has grown over the years.

check / uncheck checkbox using jquery?

You can use prop() for this, as Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

var prop=false;
if(value == 1) {

or simply,

$('#checkbox').prop('checked',(value == 1));


$(document).ready(function() {_x000D_
  var chkbox = $('.customcheckbox');_x000D_
  $(".customvalue").keyup(function() {_x000D_
    chkbox.prop('checked', this.value==1);_x000D_
<script src=""></script>_x000D_
<h4>This is a domo to show check box is checked_x000D_
if you enter value 1 else check box will be unchecked </h4>_x000D_
Enter a value:_x000D_
<input type="text" value="" class="customvalue">_x000D_
<br>checkbox output :_x000D_
<input type="checkbox" class="customcheckbox">

Windows command to convert Unix line endings?

Late to the party, but there is still no correct answer using a FOR /F loop.
(But you don't need a FOR loop at all, the solution from @TampaHaze works too and is much simpler)

The answer from @IR relevant has some drawbacks.
It drops the exclamation marks and can also drop carets.

@echo off
    setlocal Disabledelayedexpansion
    for /f "tokens=* delims=" %%L in ('findstr /n "^" "%~1"') do (
        set "line=%%L"
        setlocal enabledelayedexpansion
        set "line=!line:*:=!"
) > file.dos

The trick is to use findstr /n to prefix each line with <line number>:, this avoids skipping of empty lines or lines beginning with ;.
To remove the <number>: the FOR "tokens=1,* delims=:" option can't be used, because this would remove all leading colons in a line, too.

Therefore the line number is removed by set "line=!line:*:=!", this requires EnableDelayedExpansion.
But with EnableDelayedExpansion the line set "line=%%L" would drop all exclamation marks and also carets (only when exclams are in the line).

That's why I disable the delayed expansion before and only enable it for the two lines, where it is required.

The (echo(!line!) looks strange, but has the advantage, that echo( can display any content in !line! and the outer parenthesis avoids accidentials whitespaces at the line end.

How to refresh activity after changing language (Locale) inside application

The way we have done it was using Broadcasts:

  1. Send the broadcast every time the user changes language
  2. Register the broadcast receiver in the AppActivity.onCreate() and unregister in AppActivity.onDestroy()
  3. In BroadcastReceiver.onReceive() just restart the activity.

AppActivity is the parent activity which all other activities subclass.

Below is the snippet from my code, not tested outside the project, but should give you a nice idea.

When the user changes the language

sendBroadcast(new Intent("Language.changed"));

And in the parent activity

public class AppActivity extends Activity {

     * The receiver that will handle the change of the language.
    private BroadcastReceiver mLangaugeChangedReceiver;

    protected void onCreate(final Bundle savedInstanceState) {

        // ...
        // Other code here
        // ...

        // Define receiver
        mLangaugeChangedReceiver = new BroadcastReceiver() {

            public void onReceive(final Context context, final Intent intent) {

        // Register receiver
        registerReceiver(mLangaugeChangedReceiver, new IntentFilter("Language.changed"));

    protected void onDestroy() {

        // ...
        // Other cleanup code here
        // ...

        // Unregister receiver
        if (mLangaugeChangedReceiver != null) {
            try {
                mLangaugeChangedReceiver = null;
            } catch (final Exception e) {}

This will also refresh the activity which changed the language (if it subclasses the above activity).

This will make you lose any data, but if it is important you should already have taken care of this using Actvity.onSaveInstanceState() and Actvity.onRestoreInstanceState() (or similar).

Let me know your thoughts about this.


Javascript / Chrome - How to copy an object from the webkit inspector as code

If you've sent the object over a request you can copy it from the Chrome -> Network tab.

Request Payload - > View Source

enter image description here

enter image description here

Python Pandas Replacing Header with Top Row

header = table_df.iloc[0]
table_df.drop([0], axis =0, inplace=True)
table_df.columns = header

Do a "git export" (like "svn export")?

i have the following utility function in my .bashrc file: it creates an archive of the current branch in a git repository.

function garchive()
  if [[ "x$1" == "x-h" || "x$1" == "x" ]]; then
    cat <<EOF
Usage: garchive <archive-name>
create zip archive of the current branch into <archive-name>
    local oname=$1
    set -x
    local bname=$(git branch | grep -F "*" | sed -e 's#^*##')
    git archive --format zip --output ${oname} ${bname}
    set +x

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

Regex: Specify "space or start of string" and "space or end of string"

Here's what I would use:


In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.

This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b approach does.

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]


I suggest you have a look here for some basics:

How to close off a Git Branch?

We request that the developer asking for the pull request state that they would like the branch deleted. Most of the time this is the case. There are times when a branch is needed (e.g. copying the changes to another release branch).

My fingers have memorized our process:

git checkout <feature-branch>
git pull
git checkout <release-branch>
git pull
git merge --no-ff <feature-branch>
git push
git tag -a branch-<feature-branch> -m "Merge <feature-branch> into <release-branch>"
git push --tags
git branch -d <feature-branch>
git push origin :<feature-branch>

A branch is for work. A tag marks a place in time. By tagging each branch merge we can resurrect a branch if that is needed. The branch tags have been used several times to review changes.

How to correctly get image from 'Resources' folder in NetBeans

Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use

    String pathToImageSortBy = "resources/testDataIcons/filling.png";
    ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

But correct way was use name of my project in path to resource

String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

Checking cin input stream produces an integer

I prefer to use <limits> to check for an int until it is passed.

#include <iostream>
#include <limits> //std::numeric_limits

using std::cout, std::endl, std::cin;

int main() {
    int num;
    while(!(cin >> num)){  //check the Input format for integer the right way
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "Invalid input.  Reenter the number: ";

    cout << "output= " << num << endl;

    return 0;

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    python_dict = literal_eval("{'a': 1}")
  2. json.loads but it would require your string to use double quotes:

    import json
    python_dict = json.loads('{"a": 1}')

SQL MAX of multiple columns?

I do not know if it is on SQL, etc... on M$ACCESS help there is a function called MAXA(Value1;Value2;...) that is supposed to do such.

Hope can help someone.

P.D.: Values can be columns or calculated ones, etc.

Trying to add adb to PATH variable OSX

Alternative: Install adb the easy way

If you don't want to have to worry about your path or updating adb manually, you can use homebrew instead.

brew cask install android-platform-tools

How do I set an ASP.NET Label text from code behind on page load?

protected void Page_Load(object sender, EventArgs e)
    myLabel.Text = "My text";

this is the base of ASP.Net, thinking in controls, not html flow.

Consider following a course, or reading a beginner book... and first, forget what you did in php :)

Why dividing two integers doesn't get a float?

Specifically, this is not rounding your result, it's truncating toward zero. So if you divide -3/2, you'll get -1 and not -2. Welcome to integral math! Back before CPUs could do floating point operations or the advent of math co-processors, we did everything with integral math. Even though there were libraries for floating point math, they were too expensive (in CPU instructions) for general purpose, so we used a 16 bit value for the whole portion of a number and another 16 value for the fraction.

EDIT: my answer makes me think of the classic old man saying "when I was your age..."

Datatable to html Table

If your'e using Web Forms then Grid View can work very nicely for this

The code looks a little like this.

aspx page.

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name,Size,Quantity,Amount,Duration"></asp:GridView>

You can either input the data manually or use the source method in the code side

public class Room
    public string Name
    public double Size {get; set;}
    public int Quantity {get; set;}
    public double Amount {get; set;}
    public int Duration {get; set;}

protected void Page_Load(object sender, EventArgs e)
    if(!IsPostBack)//this is so you can keep any data you want for the list
        List<Room> rooms=new List<Room>();
        //then use the rooms.Add() to add the rooms you need.

Personally I like MVC4 the client side code ends up much lighter than Web Forms. It is similar to the above example with using a class but you use a view and Controller instead.

The View would look like this.

@model YourProject.Model.IEnumerable<Room>

        <td>@Html.LabelFor(model => model.Name)</td>
        <td>@Html.LabelFor(model => model.Size)</td>
        <td>@Html.LabelFor(model => model.Quantity)</td>
        <td>@Html.LabelFor(model => model.Amount)</td>
        <td>@Html.LabelFor(model => model.Duration)</td>
foreach(item in model)

The controller might look something like this.

public ActionResult Index()
    List<Room> rooms=new List<Room>();
    //again add the items you need

    return View(rooms);

Hope this helps :)

Convert hex color value ( #ffffff ) to integer value

Based on CQM's answer and on ovokerie-ogbeta's answer to another question I've come up with this solution:

if (colorAsString.length() == 4) { // #XXX
    colorAsString = colorAsString.replaceAll("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])", "#$1$1$2$2$3$3");

int color = Color.parseColor(colorAsString);

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

Instead of exceptions, just use:

if (Build.VERSION.SDK_INT >= 11)

and use


to suppress the warnings.

Resetting Select2 value in dropdown with reset button

For me it works only with any of these solutions

$(this).select2('val', null);


$(this).select2('val', '');

CASE statement in SQLite query

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END


    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2

Check out the documentation (The CASE expression):

XAMPP - Apache could not start - Attempting to start Apache service

For me it wasn't a port or service issue; I had to re-run the XAMPP setup script. Although this didn't directly fix the issue for me, the script was much more verbose than the XAMPP log, pointing me in the right direction to actually solve the problem.

From the XAMPP GUI, click on Shell, type set, press Tab to autocomplete to the setup_xampp.bat file, and then press Enter to run it.

In my case I got the following output:

[ERROR]: Test php.exe failed !!!
[ERROR]: Perhaps the Microsoft C++ 2008 runtime package is not installed.
[ERROR]: Please try to install the MS VC++ 2008 Redistributable Package from the Mircrosoft page first

This particular error is misleading. Although it specifies the Visual C++ 2008 Redistributable Package, PHP 7.4.x requires the Visual C++ 2019 Redistributable Package.

After installing that and following the prompt to restart, sure enough I'm now able to start Apache as normal.

How to retrieve SQL result column value using column name in Python?

This post is old but may come up via searching.

Now you can use mysql.connector to retrive a dictionary as shown here:

Here is the example on the mysql site:

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe:")
for row in cursor:
    print("* {Name}".format(Name=row['Name']))

Where are static variables stored in C and C++?

static variable stored in data segment or code segment as mentioned before.
You can be sure that it will not be allocated on stack or heap.
There is no risk for collision since static keyword define the scope of the variable to be a file or function, in case of collision there is a compiler/linker to warn you about.
A nice example

CSS: fixed to bottom and centered

You should use a sticky footer solution such as this one :

* {
    margin: 0;
html, body {
    height: 100%;
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
.footer, .push {
    height: 142px; /* .push must be the same height as .footer */

There are others like this;

* {margin:0;padding:0;} 

/* must declare 0 margins on everything, also for main layout components use padding, not 
vertical margins (top and bottom) to add spacing, else those margins get added to total height 
and your footer gets pushed down a bit more, creating vertical scroll bars in the browser */

html, body, #wrap {height: 100%;}

body > #wrap {height: auto; min-height: 100%;}

#main {padding-bottom: 150px;}  /* must be same height as the footer */

#footer {position: relative;
    margin-top: -150px; /* negative value of footer height */
    height: 150px;

.clearfix:after {content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;}
.clearfix {display: inline-block;}
/* Hides from IE-mac \*/
* html .clearfix { height: 1%;}
.clearfix {display: block;}

with the html:

<div id="wrap">

    <div id="main" class="clearfix">



<div id="footer">


Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:


Haskell: Converting Int to String

Anyone who is just starting with Haskell and trying to print an Int, use:

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)

How to remove decimal values from a value of type 'double' in Java

Nice and simple. Add this snippet in whatever you're outputting to:

String.format("%.0f", percentageValue)

Capturing mobile phone traffic on Wireshark

For Android, I previously used tPacketCapture but it didn't work well for an app streaming some video. I'm now using Shark. You need to be root to use it though.

It uses TCPDump (check the arguments you can pass) and creates a pcap file that can be read by Wireshark. The default arguments are usually good enough for me.

java - path to trustStore - set property doesn't work?

Alternatively, if using for specifying the location of your truststore does not work ( as it did in my case for two way authentication ), you can also use SSLContextBuilder as shown in the example below. This example also includes how to create a httpclient as well to show how the SSL builder would work.

SSLContextBuilder sslcontextbuilder = SSLContexts.custom();

            new File("C:\\path to\\truststore.jks"), //path to jks file
            "password".toCharArray(), //enters in the truststore password for use
            new TrustSelfSignedStrategy() //will trust own CA and all self-signed certs

SSLContext sslcontext =; //load trust store

SSLConnectionSocketFactory sslsockfac = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.getDefaultHostnameVerifier());

CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsockfac).build(); //sets up a httpclient for use with ssl socket factory 

try { 
        HttpGet httpget = new HttpGet("https://localhost:8443"); //I had a tomcat server running on localhost which required the client to have their trust cert

        System.out.println("Executing request " + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();


        } finally {
    } finally {

Beginner question: returning a boolean value from a function in Python

Have your tried using the 'return' keyword?

def rps():
    return True

document.getElementByID is not a function

I've modified your script to work with jQuery, if you wish to do so.

    //To add a task when the user hits the return key
          if(evt.keyCode == 13)
             add_task($(this), evt);
    //To add a task when the user clicks on the submit button

function add_task(textBox, evt){
  var taskText = textBox.val();
  $("<li />").text(taskText).appendTo("#tasks");

Unstaged changes left after git reset --hard

You can stash away your changes, then drop the stash:

git stash
git stash drop

How do you make websites with Java?

You are asking a few different questions...

  • How can I create websites with Java?

The simplest way to start making websites with Java is to use JSP. JSP stands for Java Server Pages, and it allows you to embed HTML in Java code files for dynamic page creation. In order to compile and serve JSPs, you will need a Servlet Container, which is basically a web server that runs Java classes. The most popular basic Servlet Container is called Tomcat, and it's provided free by The Apache Software Foundation. Follow the tutorial that cletus provided here.

Once you have Tomcat up and running, and have a basic understanding of how to deploy JSPs, you'll probably want to start creating your own JSPs. I always like IBM developerWorks tutorials. They have a JSP tutorial here that looks alright (though a bit dated).

You'll find out that there is a lot more to Java web development than JSPs, but these tutorials will get you headed in the right direction.

  • PHP vs. Java

This is a pretty subjective question. PHP and Java are just tools, and in the hands of a bad programmer, any tool is useless. PHP and Java both have their strengths and weaknesses, and the discussion of them is probably outside of the scope of this post. I'd say that if you already know Java, stick with Java.

  • File I/O vs. MySQL

MySQL is better suited for web applications, as it is designed to handle many concurrent users. You should know though that Java can use MySQL just as easily as PHP can, through JDBC, Java's database connectivity framework.

How to permanently set $PATH on Linux/Unix?

Zues77 has the right idea. The OP didn't say "how can i hack my way through this". OP wanted to know how to permanently append to $PATH:

sudo nano /etc/profile

This is where it is set for everything and is the best place to change it for all things needing $PATH

How to check if a windows form is already open, and close it if it is?

* Hope This will work for u

System.Windows.Forms.Form f1 = System.Windows.Forms.Application.OpenForms["Order"];
//open Form
//not open

Why can't variables be declared in a switch statement?

If your code says "int newVal=42" then you would reasonably expect that newVal is never uninitialised. But if you goto over this statement (which is what you're doing) then that's exactly what happens - newVal is in-scope but has not been assigned.

If that is what you really meant to happen then the language requires to make it explicit by saying "int newVal; newVal = 42;". Otherwise you can limit the scope of newVal to the single case, which is more likely what you wanted.

It may clarify things if you consider the same example but with "const int newVal = 42;"

Where does forever store console.log output?

Help is your best saviour, there is a logs action that you can call to check logs for all running processes.

forever --help

Shows the commands

logs                Lists log files for all forever processes
logs <script|index> Tails the logs for <script|index>

Sample output of the above command, for three processes running. console.log output's are stored in these logs.

info:    Logs for running Forever processes
data:        script    logfile
data:    [0] server.js /root/.forever/79ao.log
data:    [1] server.js /root/.forever/ZcOk.log
data:    [2] server.js /root/.forever/L30K.log

Daemon not running. Starting it now on port 5037

Reference link:

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

Getting a directory name from a filename

I'm so surprised no one has mentioned the standard way in Posix

Please use basename / dirname constructs.

man basename

How to unstage large number of files without deleting the content

Use git reset HEAD to reset the index without removing files. (If you only want to reset a particular file in the index, you can use git reset HEAD -- /path/to/file to do so.)

The pipe operator, in a shell, takes the stdout of the process on the left and passes it as stdin to the process on the right. It's essentially the equivalent of:

$ proc1 > proc1.out
$ proc2 < proc1.out
$ rm proc1.out

but instead it's $ proc1 | proc2, the second process can start getting data before the first is done outputting it, and there's no actual file involved.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

Had the same issue, in my case the cause was that the web.config file was missing in the virtual dir folder.

How to stop app that node.js express 'npm start'

This is a mintty version problem alternatively use cmd. To kill server process just run this command:

    taskkill -F -IM node.exe

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;

Then your @POST method would look like the following:

@POST @Consumes("application/json")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35


Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


The parameters would be annotated using @FormParam:

public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25


The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
public void create(final MultivaluedMap<String, String> formParams) {

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.

HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.

HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.

As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

Angular2 *ngIf check object array length in template

<div class="row" *ngIf="teamMembers?.length > 0">

This checks first if teamMembers has a value and if teamMembers doesn't have a value, it doesn't try to access length of undefined because the first part of the condition already fails.

Multiple contexts with the same path error running web service in Eclipse using Tomcat

Search for the server.xml file and check your <Context> tags, probably there are multiple definitions for the same path. Remove the duplicates and it should work for you.

Check out the answer here.

Auto-format the xml file (control + shift + f) since the second <Context> tag may be on the same line, but outside the viewport and really far away from the visible one.

Java 'file.delete()' Is not Deleting Specified File

Since the directory is not empty, file.delete() returns false, always.

I used


which is available in Kotlin and would delete the completely directly and return the boolean response just as file.delete() does.

Calculating Page Table Size

In 32 bit virtual address system we can have 2^32 unique address, since the page size given is 4KB = 2^12, we will need (2^32/2^12 = 2^20) entries in the page table, if each entry is 4Bytes then total size of the page table = 4 * 2^20 Bytes = 4MB

How to reload .bashrc settings without logging out and back in again?


source ~/.bashrc

or, in shorter form:

. ~/.bashrc

What's HTML character code 8203?

It's the Unicode Character 'ZERO WIDTH SPACE' (U+200B).

this character is intended for line break control; it has no width, but its presence between two characters does not prevent increased letter spacing in justification

As per the given code sample, the entity is entirely superfluous in this context. It must be inserted by some accident, most likely by a buggy editor trying to do smart things with whitespace or highlighting, or an enduser using a keyboard language wherein this character is natively been used, such as Arabic.

How can I connect to MySQL on a WAMP server?

Change localhost:8080 to localhost:3306.

Unstage a deleted file in git

I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.

To undo the two deleted files I had to unstage all of the files:

git reset HEAD .

At that point I was able to do the checkout of the deleted items:

git checkout -- WorkingFolder/FileName.ext

Finally I was able to restage the rest of the files and continue with my commit.

Automatic login script for a website on windows machine?

From the term "automatic login" I suppose security (password protection) is not of key importance here.

The guidelines for solution could be to use a JavaScript bookmark (idea borrowed form a nice game published on M&M's DK site).

The idea is to create a javascript file and store it locally. It should do the login data entering depending on current site address. Just an example using jQuery:

// dont forget to include jQuery code
// preferably with .noConflict() in order not to break the site scripts
if (window.location.indexOf("") > -1) {
    // Lets login to Gmail
    jQuery("#Email").val("[email protected]");

Now save this as say login.js

Then create a bookmark (in any browser) with this (as an) url:

javascript:document.write("<script type='text/javascript' src='file:///path/to/login.js'></script>");

Now when you go to Gmail and click this bookmark you will get automatically logged in by your script.

Multiply the code blocks in your script, to add more sites in the similar manner. You could even combine it with functionality to open more sites, but that may get the script inclusion more complicated.

Note: This only illustrates an idea and needs lots of further work, it's not a complete solution.

How to import a module given its name as string?

You can use exec:

exec("import myapp.commands.%s" % command)

Merge PDF files with PHP

I have tried similar issue and works fine, try it. It can handle different orientations between PDFs.

    // array to hold list of PDF files to be merged
    $files = array("a.pdf", "b.pdf", "c.pdf");
    $pageCount = 0;
    // initiate FPDI
    $pdf = new FPDI();

    // iterate through the files
    foreach ($files AS $file) {
        // get the page count
        $pageCount = $pdf->setSourceFile($file);
        // iterate through all pages
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
            // import a page
            $templateId = $pdf->importPage($pageNo);
            // get the size of the imported page
            $size = $pdf->getTemplateSize($templateId);

            // create a page (landscape or portrait depending on the imported page size)
            if ($size['w'] > $size['h']) {
                $pdf->AddPage('L', array($size['w'], $size['h']));
            } else {
                $pdf->AddPage('P', array($size['w'], $size['h']));

            // use the imported page

            $pdf->SetXY(5, 5);
            $pdf->Write(8, 'Generated by FPDI');

When should I use a trailing slash in my URL?

Who says a file name needs an extension?? take a look on a *nix machine sometime...
I agree with your friend, no trailing slash.

ExpressionChangedAfterItHasBeenCheckedError Explained

A solution that worked for me using rxjs

import { startWith, tap, delay } from 'rxjs/operators';

// Data field used to populate on the html
dataSource: any;


ngAfterViewInit() {
          tap((res) => this.dataSource = res)

Showing all errors and warnings

Set these on php.ini:

;display_startup_errors = On
display_errors =on
html_errors= on

From your PHP page, use a suitable filter for error reporting.


Filers can be made according to requirements.


How would you count occurrences of a string (actually a char) within a string?

            var conditionalStatement = conditionSetting.Value;

            //order of replace matters, remove == before =, incase of ===
            conditionalStatement = conditionalStatement.Replace("==", "~").Replace("!=", "~").Replace('=', '~').Replace('!', '~').Replace('>', '~').Replace('<', '~').Replace(">=", "~").Replace("<=", "~");

            var listOfValidConditions = new List<string>() { "!=", "==", ">", "<", ">=", "<=" };

            if (conditionalStatement.Count(x => x == '~') != 1)
                result.InvalidFieldList.Add(new KeyFieldData(batch.DECurrentField, "The IsDoubleKeyCondition does not contain a supported conditional statement. Contact System Administrator."));
                result.Status = ValidatorStatus.Fail;
                return result;

Needed to do something similar to test conditional statements from a string.

Replaced what i was looking for with a single character and counted the instances of the single character.

Obviously the single character you're using will need to be checked to not exist in the string before this happens to avoid incorrect counts.

Pan & Zoom Image

@Anothen and @Number8 - The Vector class is not available in Silverlight, so to make it work we just need to keep a record of the last position sighted the last time the MouseMove event was called, and compare the two points to find the difference; then adjust the transform.


    <Border Name="viewboxBackground" Background="Black">
            <Viewbox Name="viewboxMain">
                <!--contents go here-->


    public Point _mouseClickPos;
    public bool bMoving;

    public MainPage()
        viewboxMain.RenderTransform = new CompositeTransform();

    void MouseMoveHandler(object sender, MouseEventArgs e)

        if (bMoving)
            //get current transform
            CompositeTransform transform = viewboxMain.RenderTransform as CompositeTransform;

            Point currentPos = e.GetPosition(viewboxBackground);
            transform.TranslateX += (currentPos.X - _mouseClickPos.X) ;
            transform.TranslateY += (currentPos.Y - _mouseClickPos.Y) ;

            viewboxMain.RenderTransform = transform;

            _mouseClickPos = currentPos;

    void MouseClickHandler(object sender, MouseButtonEventArgs e)
        _mouseClickPos = e.GetPosition(viewboxBackground);
        bMoving = true;

    void MouseReleaseHandler(object sender, MouseButtonEventArgs e)
        bMoving = false;

Also note that you don't need a TransformGroup or collection to implement pan and zoom; instead, a CompositeTransform will do the trick with less hassle.

I'm pretty sure this is really inefficient in terms of resource usage, but at least it works :)

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

This is purely driver registration/deregistration issue in mysql`s driver or tomcats webapp-classloader. Copy mysql driver into tomcats lib folder (so its loaded by jvm directly, not by tomcat), and message will be gone. That makes mysql jdbc driver to be unloaded only at JVM shutdown, and noone cares about memory leaks then.

eloquent laravel: How to get a row count from a ->get()

also, you can fetch all data and count in the blade file. for example:

your code in the controller

$posts = Post::all();
return view('post', compact('posts'));

your code in the blade file.

{{ $posts->count() }}

finally, you can see the total of your posts.

Accessing MP3 metadata with Python

What you're after is the ID3 module. It's very simple and will give you exactly what you need. Just copy the file into your site-packages directory and you'll be able to do something like the following:

from ID3 import *
  id3info = ID3('file.mp3')
  print id3info
  # Change the tags
  id3info['TITLE'] = "Green Eggs and Ham"
  id3info['ARTIST'] = "Dr. Seuss"
  for k, v in id3info.items():
    print k, ":", v
except InvalidTagError, message:
  print "Invalid ID3 tag:", message

SQL Server database backup restore on lower version

Another way to do this is to use "Copy Database" feature:

Find by right clicking the source database > "Tasks" > "Copy Database".

You can copy the database to a lower version of SQL Server Instance. This worked for me from a SQL Server 2008 R2 (SP1) - 10.50.2789.0 to Microsoft SQL Server 2008 (SP2) - 10.0.3798.0

Create ArrayList from array

new ArrayList<T>(Arrays.asList(myArray));

Make sure that myArray is the same type as T. You'll get a compiler error if you try to create a List<Integer> from an array of int, for example.

Auto line-wrapping in SVG text

Building on @Mike Gledhill's code, I've taken it a step further and added more parameters. If you have a SVG RECT and want text to wrap inside it, this may be handy:

function wraptorect(textnode, boxObject, padding, linePadding) {

    var x_pos = parseInt(boxObject.getAttribute('x')),
    y_pos = parseInt(boxObject.getAttribute('y')),
    boxwidth = parseInt(boxObject.getAttribute('width')),
    fz = parseInt(window.getComputedStyle(textnode)['font-size']);  // We use this to calculate dy for each TSPAN.

    var line_height = fz + linePadding;

// Clone the original text node to store and display the final wrapping text.

   var wrapping = textnode.cloneNode(false);        // False means any TSPANs in the textnode will be discarded
   wrapping.setAttributeNS(null, 'x', x_pos + padding);
   wrapping.setAttributeNS(null, 'y', y_pos + padding);

// Make a copy of this node and hide it to progressively draw, measure and calculate line breaks.

   var testing = wrapping.cloneNode(false);
   testing.setAttributeNS(null, 'visibility', 'hidden');  // Comment this out to debug

   var testingTSPAN = document.createElementNS(null, 'tspan');
   var testingTEXTNODE = document.createTextNode(textnode.textContent);

   var tester = document.getElementsByTagName('svg')[0].appendChild(testing);

   var words = textnode.textContent.split(" ");
   var line = line2 = "";
   var linecounter = 0;
   var testwidth;

   for (var n = 0; n < words.length; n++) {

      line2 = line + words[n] + " ";
      testing.textContent = line2;
      testwidth = testing.getBBox().width;

      if ((testwidth + 2*padding) > boxwidth) {

        testingTSPAN = document.createElementNS('', 'tspan');
        testingTSPAN.setAttributeNS(null, 'x', x_pos + padding);
        testingTSPAN.setAttributeNS(null, 'dy', line_height);

        testingTEXTNODE = document.createTextNode(line);

        line = words[n] + " ";
      else {
        line = line2;

    var testingTSPAN = document.createElementNS('', 'tspan');
    testingTSPAN.setAttributeNS(null, 'x', x_pos + padding);
    testingTSPAN.setAttributeNS(null, 'dy', line_height);

    var testingTEXTNODE = document.createTextNode(line);



    return linecounter;

document.getElementById('original').onmouseover = function () {

    var container = document.getElementById('destination');
    var numberoflines = wraptorect(this,container,20,1);
    console.log(numberoflines);  // In case you need it


json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

Because it's not actually a dictionary; it's another mapping type that looks like a dictionary. Use type() to verify. Pass it to dict() to get a real dictionary from it.

Count all occurrences of a string in lots of files with grep

Something different than all the previous answers:

perl -lne '$count++ for m/<pattern>/g;END{print $count}' *

Reading a date using DataReader

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Library
    public partial class Form1 : Form
        public Form1()

        private void Form1_Load(object sender, EventArgs e)


        private void textBox1_TextChanged(object sender, EventArgs e)


        private void button1_Click(object sender, EventArgs e)
            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
            string query = "INSERT INTO [Table] (BookName , AuthorName , Category) VALUES('" + textBox1.Text.ToString() + "' , '" + textBox2.Text.ToString() + "' , '" + textBox3.Text.ToString() + "')";
            SqlCommand com = new SqlCommand(query, con);
            MessageBox.Show("Entry Added");

        private void button3_Click(object sender, EventArgs e)
            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
            string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "' OR AuthorName='" + textBox2.Text.ToString() + "'";
            string query1 = "SELECT BookStatus FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
            string query2 = "SELECT DateOfReturn FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
            SqlCommand com = new SqlCommand(query, con);
            SqlDataReader dr, dr1,dr2;
            dr = com.ExecuteReader();

            if (dr.Read())
                SqlCommand com1 = new SqlCommand(query1, con);
                dr1 = com1.ExecuteReader();
                string i = dr1["BookStatus"].ToString();
                if (i =="1" )
                    SqlCommand com2 = new SqlCommand(query2, con);
                    dr2 = com2.ExecuteReader();

                        MessageBox.Show("This book is already issued\n " + "Book will be available by "+ dr2["DateOfReturn"] );

                    dr = com.ExecuteReader();
                   MessageBox.Show("BookFound\n" + "BookName=" + dr["BookName"] + "\n AuthorName=" + dr["AuthorName"]);
                MessageBox.Show("This Book is not available in the library");

        private void button2_Click(object sender, EventArgs e)
            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
            string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "'";
            string dateofissue1 = DateTime.Today.ToString("dd-MM-yyyy");
            string dateofreturn = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
            string query1 = "update [Table] set BookStatus=1,DateofIssue='"+ dateofissue1 +"',DateOfReturn='"+ dateofreturn +"' where BookName='" + textBox1.Text.ToString() + "'";
            SqlCommand com = new SqlCommand(query, con);
            SqlDataReader dr;
            dr = com.ExecuteReader();
            if (dr.Read())
                string dateofissue = DateTime.Today.ToString("dd-MM-yyyy");
                textBox4.Text = dateofissue;
                textBox5.Text = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
                SqlCommand com1 = new SqlCommand(query1, con);
                MessageBox.Show("Book Isuued");
                MessageBox.Show("Book Not Found");


        private void button4_Click(object sender, EventArgs e)
            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
            string query1 = "update [Table] set BookStatus=0 WHERE BookName='"+textBox1.Text.ToString()+"'";
            SqlCommand com = new SqlCommand(query1, con);
            string today = DateTime.Today.ToString("dd-MM-yyyy");
            DateTime today1 = DateTime.Parse(today);
            string query = "SELECT dateofReturn from [Table] where BookName='" + textBox1.Text.ToString() + "'";
            SqlDataReader dr;
            SqlCommand cmd = new SqlCommand(query, con);
            dr = cmd.ExecuteReader();
            string DOR = dr["DateOfReturn"].ToString();
            DateTime dor = DateTime.Parse(DOR);
            TimeSpan ts = today1.Subtract(dor);
            string query2 = "update [Table] set DateOfIssue=NULL, DateOfReturn=NULL WHERE BookName='" + textBox1.Text.ToString() + "'";
            SqlCommand com2 = new SqlCommand(query2, con);
            int x = int.Parse(ts.Days.ToString());
            if (x > 0)
                int fine = x * 5;
                textBox6.Text = fine.ToString();
                MessageBox.Show("Book Received\nFine=" + fine);
                textBox6.Text = "0";
                MessageBox.Show("Book Received\nFine=0");

Is there a template engine for Node.js?

You should take a look at node-asyncEJS, which is explicitly designed to take the asynchronous nature of node.js into account. It even allows async code blocks inside of the template.

Here an example form the documentation:

    <% ctx.hello = "World";  %>
    <title><%= "Hello " + ctx.hello %></title>

    <h1><%? setTimeout(function () { res.print("Async Header"); res.finish(); }, 2000)  %></h1>
    <p><%? setTimeout(function () { res.print("Body"); res.finish(); }, 1000)  %></p>


How can I reorder my divs using only CSS?

Little late to the party, but you can also do this:

<div style="height: 500px; width: 500px;">

<div class="bottom" style="height: 250px; width: 500px; background: red; margin-top: 250px;"></div>

<div class="top" style="height: 250px; width: 500px; background: blue; margin-top: -500px;"></div>

AngularJS - Multiple ng-view in single template

You can have just one ng-view.

You can change its content in several ways: ng-include, ng-switch or mapping different controllers and templates through the routeProvider.

What are the benefits of using C# vs F# or F# vs C#?

F# is not yet-another-programming-language if you are comparing it to C#, C++, VB. C#, C, VB are all imperative or procedural programming languages. F# is a functional programming language.

Two main benefits of functional programming languages (compared to imperative languages) are 1. that they don't have side-effects. This makes mathematical reasoning about properties of your program a lot easier. 2. that functions are first class citizens. You can pass functions as parameters to another functions just as easily as you can other values.

Both imperative and functional programming languages have their uses. Although I have not done any serious work in F# yet, we are currently implementing a scheduling component in one of our products based on C# and are going to do an experiment by coding the same scheduler in F# as well to see if the correctness of the implementation can be validated more easily than with the C# equivalent.

How to convert an int value to string in Go?

ok,most of them have shown you something good. Let'me give you this:

// ToString Change arg to string
func ToString(arg interface{}, timeFormat ...string) string {
    if len(timeFormat) > 1 {
        log.SetFlags(log.Llongfile | log.LstdFlags)
        log.Println(errors.New(fmt.Sprintf("timeFormat's length should be one")))
    var tmp = reflect.Indirect(reflect.ValueOf(arg)).Interface()
    switch v := tmp.(type) {
    case int:
        return strconv.Itoa(v)
    case int8:
        return strconv.FormatInt(int64(v), 10)
    case int16:
        return strconv.FormatInt(int64(v), 10)
    case int32:
        return strconv.FormatInt(int64(v), 10)
    case int64:
        return strconv.FormatInt(v, 10)
    case string:
        return v
    case float32:
        return strconv.FormatFloat(float64(v), 'f', -1, 32)
    case float64:
        return strconv.FormatFloat(v, 'f', -1, 64)
    case time.Time:
        if len(timeFormat) == 1 {
            return v.Format(timeFormat[0])
        return v.Format("2006-01-02 15:04:05")
    case jsoncrack.Time:
        if len(timeFormat) == 1 {
            return v.Time().Format(timeFormat[0])
        return v.Time().Format("2006-01-02 15:04:05")
    case fmt.Stringer:
        return v.String()
    case reflect.Value:
        return ToString(v.Interface(), timeFormat...)
        return ""

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;


What does the Visual Studio "Any CPU" target mean?

Any CPU means that it will work on any platform. This is because managed code is similar to Java. Think of it as being compiled to a byte code that is interpreted by the .NET Framework at run-time.

C++ does not have this option because it is compiled to machine code that is platform specific.

Python Traceback (most recent call last)

You are using Python 2 for which the input() function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError exception.

To fix the problem, in Python 2, you can use raw_input(). This returns the string entered by the user and does not attempt to evaluate it.

Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

How do I iterate over a JSON structure?

Copied and pasted from, there is no need for the JQuery overhead.

var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
    text += person[x];

RESULT: John Doe 25

Array.Add vs +=

When using the $array.Add()-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.

$array += $element creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array-variable

You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:

    $a += 200

Source: about_Arrays

+= is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:

$arr = 1..3    #Array
$arr += (4..5) #Combine with another array in a single write-operation


If that's not possible, consider using a more efficient collection like List or ArrayList (see the other answer).

Can I specify maxlength in css?


maxlength is for behavior.

CSS is for styling.

That is why.

Use the auto keyword in C++ STL

This is new item in the language which I think we are going to be struggling with for years to come. The 'auto' of the start presents not only readability problem , from now on when you encounter it you will have to spend considerable time trying to figure out wtf it is(just like the time that intern named all variables xyz :)), but you also will spend considerable time cleaning after easily excitable programmers , like the once who replied before me. Example from above , I can bet $1000 , will be written "for (auto it : s)", not "for (auto& it : s)", as a result invoking move semantics where you list expecting it, modifying your collection underneath .

Another example of the problem is your question itself. You clearly don't know much about stl iterators and you trying to overcome that gap through usage of the magic of 'auto', as a result you create the code that might be problematic later on

How do you round a number to two decimal places in C#?

  public double RoundDown(double number, int decimalPlaces)
            return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);

How to add a custom HTTP header to every WCF call?

A bit late to the party but Juval Lowy addresses this exact scenario in his book and the associated ServiceModelEx library.

Basically he defines ClientBase and ChannelFactory specialisations that allow specifying type-safe header values. I suggesst downloading the source and looking at the HeaderClientBase and HeaderChannelFactory classes.


Default background color of SVG root element

SVG 1.2 Tiny has viewport-fill I'm not sure how widely implemented this property is though as most browsers are targetting SVG 1.1 at this time. Opera implements it FWIW.

A more cross-browser solution currently would be to stick a <rect> element with width and height of 100% and fill="red" as the first child of the <svg> element, for example:

<rect width="100%" height="100%" fill="red"/>

Difference between database and schema

Schema says what tables are in database, what columns they have and how they are related. Each database has its own schema.

List<Object> and List<?>

List<Object> object = new List<Object>();

You cannot do this because List is an interface and you cannot create object of any interface or in other word you cannot instantiate any interface. Moreover, you can assign any object of class which implements List to its reference variable. For example you can do this:

list<Object> object = new ArrayList<Object>();

Here ArrayList is a class which implements List, you can use any class which implements List.

Find duplicate characters in a String and count the number of occurances using Java

public static void findDuplicate(String letter)

    for(int i=0; i<letter.length();i++)
        for( int j=i+1; j<letter.length();j++)


The OUTPUT is : A

invalid conversion from 'const char*' to 'char*'

string::c.str() returns a string of type const char * as seen here

A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str());

While the above may work, it is undefined behaviour, and unsafe.

Here's a nicer solution using templates:

char * my_argument = const_cast<char*> ( ...c_str() );

Multiprocessing a for loop?


with Pool() as pool:, [name + '.fits' for name in datainput])

How can I get the ID of an element using jQuery?


Using above code you can get id.

Is true == 1 and false == 0 in JavaScript?

From the ECMAScript specification, Section 11.9.3 The Abstract Equality Comparison Algorithm:

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  • If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

Thus, in, if (1 == true), true gets coerced to a Number, i.e. Number(true), which results in the value of 1, yielding the final if (1 == 1) which is true.

if (0 == false) is the exact same logic, since Number(false) == 0.

This doesn't happen when you use the strict equals operator === instead:

11.9.6 The Strict Equality Comparison Algorithm

The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  • If Type(x) is different from Type(y), return false.

How to copy a row from one SQL Server table to another

SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >

How can INSERT INTO a table 300 times within a loop in SQL?

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1

How to implement an android:background that doesn't stretch?

You can create an xml bitmap and use it as background for the view. To prevent stretching you can specify android:gravity attribute.

for example:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android=""
    android:tileMode="disabled" android:gravity="top" >

There are a lot of options you can use to customize the rendering of the image

R - Markdown avoiding package loading messages

My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.

{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables

#data wrangling

#text processing

How to store command results in a shell variable?

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

So you can directly do:

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

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

Undefined reference to pthread_create in Linux

In Visual Studio 2019 specify -pthread in the property pages for the project under:

Linker -> Command Line -> Additional Options

Type in -pthread in the textbox.

Set background color of WPF Textbox in C# code

If you want to set the background using a hex color you could do this:

var bc = new BrushConverter();

myTextBox.Background = (Brush)bc.ConvertFrom("#FFXXXXXX");

Or you could set up a SolidColorBrush resource in XAML, and then use findResource in the code-behind:

<SolidColorBrush x:Key="BrushFFXXXXXX">#FF8D8A8A</SolidColorBrush>
myTextBox.Background = (Brush)Application.Current.MainWindow.FindResource("BrushFFXXXXXX");

How can I send large messages with Kafka (over 15MB)?

For people using landoop kafka: You can pass the config values in the environment variables like:

docker run -d --rm -p 2181:2181 -p 3030:3030 -p 8081-8083:8081-8083  -p 9581-9585:9581-9585 -p 9092:9092
 -e KAFKA_TOPIC_MAX_MESSAGE_BYTES=15728640 -e KAFKA_REPLICA_FETCH_MAX_BYTES=15728640  landoop/fast-data-dev:latest `

And if you're usind rdkafka then pass the message.max.bytes in the producer config like:

  const producer = new Kafka.Producer({
        '': 'localhost:9092',
        'message.max.bytes': '15728640',
        'dr_cb': true

Similarly, for the consumer,

  const kafkaConf = {
   "": "librd-test",
   ... .. }                                                                                                                                                                                                                                                      

Database Diagram Support Objects cannot be Installed ... no valid owner

right click on your Database , then select properties . select the option in compatibility levels choose sql 2005[90] instead of 2008 if you are working with Microsoft sql 2008. then select the file and write ( sa ) in owner`s textbox. it will work probably

Android, Java: HTTP POST Request

Here's an example previously found at (the site is currently not maintained anymore).

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block

So, you can add your parameters as BasicNameValuePair.

An alternative is to use (Http)URLConnection. See also Using to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.

PHP memcached Fatal error: Class 'Memcache' not found

There are two extensions for memcached in PHP, "memcache" and "memcached".

It looks like you're trying to use one ("memcache"), but the other is installed ("memcached").

Difference between $(document.body) and $('body')

They refer to the same element, the difference is that when you say document.body you are passing the element directly to jQuery. Alternatively, when you pass the string 'body', the jQuery selector engine has to interpret the string to figure out what element(s) it refers to.

In practice either will get the job done.

If you are interested, there is more information in the documentation for the jQuery function.

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.

What does "javascript:void(0)" mean?

It means it’ll do nothing. It’s an attempt to have the link not ‘navigate’ anywhere. But it’s not the right way.

You should actually just return false in the onclick event, like so:

<a href="#" onclick="return false;">hello</a>

Typically it’s used if the link is doing some ‘JavaScript-y’ thing. Like posting an AJAX form, or swapping an image, or whatever. In that case you just make whatever function is being called return false.

To make your website completely awesome, however, generally you’ll include a link that does the same action, if the person browsing it chooses not to run JavaScript.

<a href="backup_page_displaying_image.aspx"
   onclick="return coolImageDisplayFunction();">hello</a>

How to call a web service from jQuery

In Java, this return value fails with jQuery Ajax GET:

return Response.status(200).entity(pojoObj).build();

But this works:

ResponseBuilder rb = Response.status(200).entity(pojoObj);
return rb.header("Access-Control-Allow-Origin", "*").build();


Full class:

public class PasswordStorage {
    @Produces({ MediaType.APPLICATION_JSON })
    public Response getRole() {
        Contact pojoObj= new Contact();

        ResponseBuilder rb = Response.status(200).entity(pojoObj);
        return rb.header("Access-Control-Allow-Origin", "*").build();

        //Fails jQuery: return Response.status(200).entity(pojoObj).build();

Goal Seek Macro with Goal as a Formula

GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.

The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.

I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).

For the test, I set:

  the GoalSeek cell  H18 = (G18^3)+(3*G18^2)+6
  the Goal cell      H32 =  11
  the ChangingCell   G18 =  0 

The code was:

Sub GSeek()
    With Worksheets("Sheet1")
        .Range("H18").GoalSeek _
        Goal:=.Range("H32").Value, _
    End With
End Sub

And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

You need to include xmlbeans-xxx.jar and if you have downloaded the POI binary zip, you will get the xmlbeans-xxx.jar in ooxml-lib folder (eg: \poi-3.11\ooxml-lib)

This jar is used for XML binding which is applicable for .xlsx files.

PHP error: Notice: Undefined index:

Try this:

$month = ( isset($_POST['month']) ) ? $_POST['month'] : '';

$op = ( isset($_POST['op']) ) ? $_POST['op'] : '';

How to tell if a JavaScript function is defined

For global functions you can use this one instead of eval suggested in one of the answers.

var global = (function (){
    return this;

if (typeof(global.f) != "function")
    global.f = function f1_shim (){
        // commonly used by polyfill libs

You can use global.f instanceof Function as well, but afaik. the value of the Function will be different in different frames, so it will work only with a single frame application properly. That's why we usually use typeof instead. Note that in some environments there can be anomalies with typeof f too, e.g. by MSIE 6-8 some of the functions for example alert had "object" type.

By local functions you can use the one in the accepted answer. You can test whether the function is local or global too.

if (typeof(f) == "function")
    if (global.f === f)
        console.log("f is a global function");
        console.log("f is a local function");

To answer the question, the example code is working for me without error in latest browers, so I am not sure what was the problem with it:

function something_cool(text, callback) {
    if( callback != null ) callback();

Note: I would use callback !== undefined instead of callback != null, but they do almost the same.

How to prevent long words from breaking my div?

For compatibility with IE 8+ use:

-ms-word-break: break-all;
     word-break: break-all;

     /* Non standard for webkit */
     word-break: break-word;

-webkit-hyphens: auto;
   -moz-hyphens: auto;
        hyphens: auto;

See it here

All I had to do was apply this to the style of the div container with a set width.

Tab space instead of multiple non-breaking spaces ("nbsp")?

Only "pre" tag:

<pre>Name:      Waleed Hasees
Age:        33y
Address:    Palestine / Jein</pre>

You can apply any CSS class on this tag.

Oracle Not Equals Operator

They are the same (as is the third form, ^=).

Note, though, that they are still considered different from the point of view of the parser, that is a stored outline defined for a != won't match <> or ^=.

This is unlike PostgreSQL where the parser treats != and <> yet on parsing stage, so you cannot overload != and <> to be different operators.

How to properly use unit-testing's assertRaises() with NoneType objects?

The problem is the TypeError gets raised 'before' assertRaises gets called since the arguments to assertRaises need to be evaluated before the method can be called. You need to pass a lambda expression like:

self.assertRaises(TypeError, lambda: self.testListNone[:1])

How to store an array into mysql?

You can use the php serialize function to store array in MySQL.


$array = array("Name"=>"Shubham","Age"=>"17","website"=>"");

$string_array = serialize($array);

echo $string_array;


It’s output will be :


And then you can use the php unserialize function to decode the data.

I think you should visit this page on storing array in mysql.