Programs & Examples On #Request queueing

Raising a number to a power in Java

You should use below method-

Math.pow(double a, double b)

Returns the value of the first argument raised to the power of the second argument.

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result


CASE value WHEN [compare_value] THEN result 
[WHEN [compare_value] THEN result ...] 
[ELSE result] 

Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]

mysql> SELECT CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END; 
| CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
| this is false                                               | 

I am use:

SELECT  act.*,
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
        WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
    END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = AND  lises.session_date >= now()
LEFT JOIN session AS ses ON  ses.activity_id = AND  ses.session_date >= now()

Is it possible to CONTINUE a loop from an exception?

In the construct you have provided, you don't need a CONTINUE. Once the exception is handled, the statement after the END is performed, assuming your EXCEPTION block doesn't terminate the procedure. In other words, it will continue on to the next iteration of the user_rec loop.

You also need to SELECT INTO a variable inside your BEGIN block:

SELECT attr INTO v_attr FROM attribute_table...

Obviously you must declare v_attr as well...

How do you debug MySQL stored procedures?

MySql Connector/NET also includes a stored procedure debugger integrated in visual studio as of version 6.6, You can get the installer and the source here:

Some documentation / screenshots:

You can follow the annoucements here:,561817,561817#msg-561817

UPDATE: The MySql for Visual Studio was split from Connector/NET into a separate product, you can pick it (including the debugger) from here (still free & open source).

DISCLAIMER: I was the developer who authored the Stored procedures debugger engine for MySQL for Visual Studio product.

How can I link to a specific glibc version?

In my opinion, the laziest solution (especially if you don't rely on latest bleeding edge C/C++ features, or latest compiler features) wasn't mentioned yet, so here it is:

Just build on the system with the oldest GLIBC you still want to support.

This is actually pretty easy to do nowadays with technologies like chroot, or KVM/Virtualbox, or docker, even if you don't really want to use such an old distro directly on any pc. In detail, to make a maximum portable binary of your software I recommend following these steps:

  1. Just pick your poison of sandbox/virtualization/... whatever, and use it to get yourself a virtual older Ubuntu LTS and compile with the gcc/g++ it has in there by default. That automatically limits your GLIBC to the one available in that environment.

  2. Avoid depending on external libs outside of foundational ones: like, you should dynamically link ground-level system stuff like glibc, libGL, libxcb/X11/wayland things, libasound/libpulseaudio, possibly GTK+ if you use that, but otherwise preferrably statically link external libs/ship them along if you can. Especially mostly self-contained libs like image loaders, multimedia decoders, etc can cause less breakage on other distros (breakage can be caused e.g. if only present somewhere in a different major version) if you statically ship them.

With that approach you get an old-GLIBC-compatible binary without any manual symbol tweaks, without doing a fully static binary (that may break for more complex programs because glibc hates that, and which may cause licensing issues for you), and without setting up any custom toolchain, any custom glibc copy, or whatever.

Get Maven artifact version at runtime

A simple solution which is Maven compatible and works for any (thus also third party) class:

    private static Optional<String> getVersionFromManifest(Class<?> clazz) {
        try {
            File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI());
            if (file.isFile()) {
                JarFile jarFile = new JarFile(file);
                Manifest manifest = jarFile.getManifest();
                Attributes attributes = manifest.getMainAttributes();
                final String version = attributes.getValue("Bundle-Version");
                return Optional.of(version);
        } catch (Exception e) {
            // ignore
        return Optional.empty();

How do I efficiently iterate over each entry in a Java Map?

Iterating a Map is very easy.

for(Object key: map.keySet()){
   Object value= map.get(key);
   //Do your stuff

For instance, you have a Map<String, int> data;

for(Object key: data.keySet()){
  int value= data.get(key);

PowerShell and the -contains operator

-Contains is actually a collection operator. It is true if the collection contains the object. It is not limited to strings.

-match and -imatch are regular expression string matchers, and set automatic variables to use with captures.

-like, -ilike are SQL-like matchers.

"Debug certificate expired" error in Eclipse Android plugins

In Windows debug.keystore file is localtes at C:\Users\%Username%\.android folder. This file is created when you install your android SDK and is valid only for a year. After this perod you will start getting this error Error getting final archive: Debug certificate expired on xx/xx/xxxx.

To remove this error simply delete the file and run the program again. In my Eclipse I have enabled Project->Build Automatically so it directly worked but in case you have disabled it you will need to clean the project Project->Clean.. select your project and press ok. Then you will need to build it manually. 3rd click on your project and select Build project.(Note - You will only see this option if you have diabled Build Automatically feature in your Projects Menu)

How to clear all inputs, selects and also hidden fields in a form using jQuery?

To clear all inputs, including hidden fields, using JQuery:

// Behold the power of JQuery.

Selects are harder, because they have a fixed list. Do you want to clear that list, or just the selection.

Could be something like

$('option').attr('selected', false);

Difference between parameter and argument

They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

How to make the first option of <select> selected with jQuery

$("#target").val($("#target option:first").val());

MySQL order by before group by

What you are going to read is rather hacky, so don't try this at home!

In SQL in general the answer to your question is NO, but because of the relaxed mode of the GROUP BY (mentioned by @bluefeet), the answer is YES in MySQL.

Suppose, you have a BTREE index on (post_status, post_type, post_author, post_date). How does the index look like under the hood?

(post_status='publish', post_type='post', post_author='user A', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user A', post_date='2012-12-31') (post_status='publish', post_type='post', post_author='user B', post_date='2012-10-01') (post_status='publish', post_type='post', post_author='user B', post_date='2012-12-01')

That is data is sorted by all those fields in ascending order.

When you are doing a GROUP BY by default it sorts data by the grouping field (post_author, in our case; post_status, post_type are required by the WHERE clause) and if there is a matching index, it takes data for each first record in ascending order. That is the query will fetch the following (the first post for each user):

(post_status='publish', post_type='post', post_author='user A', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user B', post_date='2012-10-01')

But GROUP BY in MySQL allows you to specify the order explicitly. And when you request post_user in descending order, it will walk through our index in the opposite order, still taking the first record for each group which is actually last.

That is

WHERE wp_posts.post_status='publish' AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author DESC

will give us

(post_status='publish', post_type='post', post_author='user B', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user A', post_date='2012-12-31')

Now, when you order the results of the grouping by post_date, you get the data you wanted.

SELECT wp_posts.*
FROM wp_posts
WHERE wp_posts.post_status='publish' AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author DESC
ORDER BY wp_posts.post_date DESC;


This is not what I would recommend for this particular query. In this case, I would use a slightly modified version of what @bluefeet suggests. But this technique might be very useful. Take a look at my answer here: Retrieving the last record in each group

Pitfalls: The disadvantages of the approach is that

  • the result of the query depends on the index, which is against the spirit of the SQL (indexes should only speed up queries);
  • index does not know anything about its influence on the query (you or someone else in future might find the index too resource-consuming and change it somehow, breaking the query results, not only its performance)
  • if you do not understand how the query works, most probably you'll forget the explanation in a month and the query will confuse you and your colleagues.

The advantage is performance in hard cases. In this case, the performance of the query should be the same as in @bluefeet's query, because of amount of data involved in sorting (all data is loaded into a temporary table and then sorted; btw, his query requires the (post_status, post_type, post_author, post_date) index as well).

What I would suggest:

As I said, those queries make MySQL waste time sorting potentially huge amounts of data in a temporary table. In case you need paging (that is LIMIT is involved) most of the data is even thrown off. What I would do is minimize the amount of sorted data: that is sort and limit a minimum of data in the subquery and then join back to the whole table.

FROM wp_posts
  SELECT max(post_date) post_date, post_author
  FROM wp_posts
  WHERE post_status='publish' AND post_type='post'
  GROUP BY post_author
  ORDER BY post_date DESC
) p2 USING (post_author, post_date)
WHERE post_status='publish' AND post_type='post';

The same query using the approach described above:

  SELECT post_id
  FROM wp_posts
  WHERE post_status='publish' AND post_type='post'
  GROUP BY post_author DESC
  ORDER BY post_date DESC
) as ids
JOIN wp_posts USING (post_id);

All those queries with their execution plans on SQLFiddle.

Why is HttpContext.Current null?

try to implement Application_AuthenticateRequest instead of Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start (which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current object yet).

hope that helps.

Converting 'ArrayList<String> to 'String[]' in Java

In Java 8, it can be done using

String[] arrayFromList =[]::new);

how to add value to combobox item

If you want to use SelectedValue then your combobox must be databound.

To set up the combobox:

ComboBox1.DataSource = GetMailItems()
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"

To get the data:

Function GetMailItems() As List(Of MailItem)

    Dim mailItems = New List(Of MailItem)

    Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)
    Command.CommandTimeout = 30
    Reader = Command.ExecuteReader()

    If Reader.HasRows = True Then
        While Reader.Read()
            mailItems.Add(New MailItem(Reader("ID"), Reader("name")))
        End While
    End If

    Return mailItems

End Function

Public Class MailItem

    Public Sub New(ByVal id As Integer, ByVal name As String)
        mID = id
        mName = name
    End Sub

    Private mID As Integer
    Public Property ID() As Integer
            Return mID
        End Get
        Set(ByVal value As Integer)
            mID = value
        End Set
    End Property

    Private mName As String
    Public Property Name() As String
            Return mName
        End Get
        Set(ByVal value As String)
            mName = value
        End Set
    End Property

End Class

Reading a plain text file in Java

This is basically the exact same as Jesus Ramos' answer, except with File instead of FileReader plus iteration to step through the contents of the file.

Scanner in = new Scanner(new File("filename.txt"));

while (in.hasNext()) { // Iterates each line in the file
    String line = in.nextLine();
    // Do something with line

in.close(); // Don't forget to close resource leaks

... throws FileNotFoundException

What's the fastest way to convert String to Number in JavaScript?

I find that num * 1 is simple, clear, and works for integers and floats...

jQuery AJAX submit form


fetch(form.action,{method:'post', body: new FormData(form)});

function send(e,form) {_x000D_
  fetch(form.action,{method:'post', body: new FormData(form)});_x000D_
  console.log('We submit form asynchronously (AJAX)');_x000D_
<form method="POST" action="myapi/send" onsubmit="send(event,this)" name="orderproductForm">_x000D_
    <input hidden name="csrfToken" value="$0meh@$h">_x000D_
    <input name="email" value="[email protected]">_x000D_
    <input name="phone" value="123-456-666">_x000D_
    <input type="submit">    _x000D_
Look on Chrome Console > Network after/before 'submit'

Getting Excel to refresh data on sheet from within VBA

After a data connection update, some UDF's were not executing. Using a subroutine, I was trying to recalcuate a single column with:


But above statement had no effect. None of above solutions helped, except kambeeks suggestion to replace formulas worked and was fast if manual recalc turned on during update. Below code solved my problem, even if not exactly responsible to OP "kluge" comment, it provided a fast/reliable solution to force recalculation of user-specified cells.

Application.Calculation = xlManual
For Each mycell In Sheets("mysheet").Range("D9:D750").Cells
    mycell.Formula = mycell.Formula
Application.Calculation = xlAutomatic

displaying a string on the textview when clicking a button in android

Just check your code in .java class

You had written below line


before initializing the mybtn object I mean

mybtn = (Button)findViewById(;

just switch this two line or put that line "mybtn.setOnClickListener(this)" after initializing your mybtn object and you will get the answer what you want..

Sharing link on WhatsApp from mobile website (not application) for Android

Switch the whatsapp share links according to the platform whether desktop or mobile.

This works with or without providing the phone number in the link.

For Mobile

   vm.LinkTextToShare = '' + encodeURIComponent(window.location.href) ;,"_blank");

For Desktop

   vm.LinkTextToShare = '' + encodeURIComponent(window.location.href) ;,"_blank");

Array initializing in Scala

To initialize an array filled with zeros, you can use:

> Array.fill[Byte](5)(0)
Array(0, 0, 0, 0, 0)

This is equivalent to Java's new byte[5].

How to get an element's top position relative to the browser's viewport?

The existing answers are now outdated. The native getBoundingClientRect() method has been around for quite a while now, and does exactly what the question asks for. Plus it is supported across all browsers (including IE 5, it seems!)

From MDN page:

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

You use it like so:

var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport, i.e. the window
var top =;
var left = viewportOffset.left;

show more/Less text with just HTML and JavaScript

Try to toggle height.

function toggleTextArea()
  var limitedHeight = '40px';
  var targetEle = document.getElementById("textarea"); = ( === '') ? limitedHeight : '';

C# - using List<T>.Find() with custom objects

You can use find with a Predicate as follows:

list.Find(x => x.Id == IdToFind);

This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).

jQuery ajax upload file in mvc

I have a sample like this on vuejs version: v2.5.2

<form action="url" method="post" enctype="multipart/form-data">
    <div class="col-md-6">
        <input type="file" class="image_0" name="FilesFront" ref="FilesFront" />
    <div class="col-md-6">
        <input type="file" class="image_1" name="FilesBack" ref="FilesBack" />
Vue.component('v-bl-document', {
    template: '#document-item-template',
    props: ['doc'],
    data: function () {
        return {
            document: this.doc
    methods: {
        submit: function () {

            var data = new FormData();
            var _doc = this.document;
            Object.keys(_doc).forEach(function (key) {
                data.append(key, _doc[key]);
            var _refs = this.$refs;
            Object.keys(_refs).forEach(function (key) {
                data.append(key, _refs[key].files[0]);

                type: "POST",
                data: data,
                url: url,
                cache: false,
                contentType: false,
                processData: false,
                success: function (result) {
                    //do something


Replace whitespaces with tabs in linux

You can also use astyle. I found it quite useful and it has several options too:

Tab and Bracket Options:
   If  no  indentation  option is set, the default option of 4 spaces will be used. Equivalent to -s4 --indent=spaces=4.  If no brackets option is set, the
   brackets will not be changed.

   --indent=spaces, --indent=spaces=#, -s, -s#
          Indent using # spaces per indent. Between 1 to 20.  Not specifying # will result in a default of 4 spaces per indent.

   --indent=tab, --indent=tab=#, -t, -t#
          Indent using tab characters, assuming that each tab is # spaces long.  Between 1 and 20. Not specifying # will result in a default assumption  of
          4 spaces per tab.`

How to fill a Javascript object literal with many static key/value pairs efficiently?

The syntax you wrote as first is not valid. You can achieve something using the follow:

var map =  {"aaa": "rrr", "bbb": "ppp" /* etc */ };

Avoid trailing zeroes in printf()

Why not just do this?

double f = 359.01335;
printf("%g", round(f * 1000.0) / 1000.0);

how to convert binary string to decimal?

I gathered all what others have suggested and created following function which has 3 arguments, the number and the base which that number has come from and the base which that number is going to be on:

changeBase(1101000, 2, 10) => 104

Run Code Snippet to try it yourself:

function changeBase(number, fromBase, toBase) {_x000D_
                        if (fromBase == 10)_x000D_
                            return (parseInt(number)).toString(toBase)_x000D_
                        else if (toBase == 10)_x000D_
                            return parseInt(number, fromBase);_x000D_
                            var numberInDecimal = parseInt(number, fromBase);_x000D_
                            return (parseInt(numberInDecimal)).toString(toBase);_x000D_
  var number = $("#txtNumber").val(),_x000D_
  fromBase = $("#txtFromBase").val(),_x000D_
  toBase = $("#txtToBase").val();_x000D_
  $("#lblResult").text(changeBase(number, fromBase, toBase));_x000D_
  padding: 20px;_x000D_
<script src=""></script>_x000D_
<input id="txtNumber" type="text" placeholder="Number" />_x000D_
<input id="txtFromBase" type="text" placeholder="From Base" />_x000D_
<input id="txtToBase" type="text" placeholder="To Base" />_x000D_
<input id="btnConvert" type="button" value="Convert" />_x000D_
<span id="lblResult"></span>_x000D_
<p>Hint: <br />_x000D_
Try 110, 2, 10 and it will return 6; (110)<sub>2</sub> = 6<br />_x000D_
or 2d, 16, 10 => 45 meaning: (2d)<sub>16</sub> = 45<br />_x000D_
or 45, 10, 16 => 2d meaning: 45 = (2d)<sub>16</sub><br />_x000D_
or 2d, 2, 16 => 2d meaning: (101101)<sub>2</sub> = (2d)<sub>16</sub><br />_x000D_

FYI: If you want to pass 2d as hex number, you need to send it as a string so it goes like this: changeBase('2d', 16, 10)

load and execute order of scripts

If you aren't dynamically loading scripts or marking them as defer or async, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.

Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.

There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.

When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.

A script tag with async may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async is that it can run anytime and that time is not predictable.

A script tag with defer waits until the entire parser is done and then runs all scripts marked with defer in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer or async.

Here's a quote from that article:

script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.

The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.

A quote from the HTML5 spec:

Then, the first of the following options that describes the situation must be followed:

If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

Remove the first element from this list of scripts that will execute in order as soon as possible.

If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.

What about Javascript module scripts, type="module"?

Javascript now has support for module loading with syntax like this:

<script type="module">
  import {addTextToBody} from './utils.mjs';

  addTextToBody('Modules are pretty cool.');

Or, with src attribute:

<script type="module" src="">

All scripts with type="module" are automatically given the defer attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.

Module scripts can also be given the async attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async script in any particular order relative to other scripts.

There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.

How to start IIS Express Manually

Or you simply manage it like full IIS by using Jexus Manager for IIS Express, an open source project I work on

Jexus Manager for IIS Express

Start a site and the process will be launched for you.

How do I copy a version of a single file from one git branch to another?

Run this from the branch where you want the file to end up:

git checkout otherbranch myfile.txt

General formulas:

git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>

Some notes (from comments):

  • Using the commit hash you can pull files from any commit
  • This works for files and directories
  • overwrites the file myfile.txt and mydir
  • Wildcards don't work, but relative paths do
  • Multiple paths can be specified

an alternative:

git show commit_id:path/to/file > path/to/file

Best way to split string into lines

Slightly twisted, but an iterator block to do it:

public static IEnumerable<string> Lines(this string Text)
    int cIndex = 0;
    int nIndex;
    while ((nIndex = Text.IndexOf(Environment.NewLine, cIndex + 1)) != -1)
        int sIndex = (cIndex == 0 ? 0 : cIndex + 1);
        yield return Text.Substring(sIndex, nIndex - sIndex);
        cIndex = nIndex;
    yield return Text.Substring(cIndex + 1);

You can then call:

var result = input.Lines().ToArray();

Asynchronously wait for Task<T> to complete with timeout

How about this:

int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
    // task completed within timeout
} else { 
    // timeout logic

And here's a great blog post "Crafting a Task.TimeoutAfter Method" (from MS Parallel Library team) with more info on this sort of thing.

Addition: at the request of a comment on my answer, here is an expanded solution that includes cancellation handling. Note that passing cancellation to the task and the timer means that there are multiple ways cancellation can be experienced in your code, and you should be sure to test for and be confident you properly handle all of them. Don't leave to chance various combinations and hope your computer does the right thing at runtime.

int timeout = 1000;
var task = SomeOperationAsync(cancellationToken);
if (await Task.WhenAny(task, Task.Delay(timeout, cancellationToken)) == task)
    // Task completed within timeout.
    // Consider that the task may have faulted or been canceled.
    // We re-await the task so that any exceptions/cancellation is rethrown.
    await task;

    // timeout/cancellation logic

Calling a function when ng-repeat has finished

I'm very surprised not to see the most simple solution among the answers to this question. What you want to do is add an ngInit directive on your repeated element (the element with the ngRepeat directive) checking for $last (a special variable set in scope by ngRepeat which indicates that the repeated element is the last in the list). If $last is true, we're rendering the last element and we can call the function we want.

ng-init="$last && test()"

The complete code for your HTML markup would be:

<div ng-app="testApp" ng-controller="myC">
    <p ng-repeat="t in ta" ng-init="$last && test()">{{t}}</p>

You don't need any extra JS code in your app besides the scope function you want to call (in this case, test) since ngInit is provided by Angular.js. Just make sure to have your test function in the scope so that it can be accessed from the template:

$scope.test = function test() {
    console.log("test executed");

Closing database connections in Java

Yes, you need to close Connection. Otherwise, the database client will typically keep the socket connection and other resources open.

How to get all of the IDs with jQuery?

//but i cannot really get the id and assign it to an array that is not with in the scope?(or can I)

Yes, you can!

var IDs = [];
$("#mydiv").find("span").each(function(){ IDs.push(; });

This is the beauty of closures.

Note that while you were on the right track, sighohwell and cletus both point out more reliable and concise ways of accomplishing this, taking advantage of attribute filters (to limit matched elements to those with IDs) and jQuery's built-in map() function:

var IDs = $("#mydiv span[id]")         // find spans with ID attribute
  .map(function() { return; }) // convert to set of IDs
  .get(); // convert to instance of Array (optional)

How to find the files that are created in the last hour in unix

If the dir to search is srch_dir then either

$ find srch_dir -cmin -60 # change time


$ find srch_dir -mmin -60 # modification time


$ find srch_dir -amin -60 # access time

shows files created, modified or accessed in the last hour.

correction :ctime is for change node time (unsure though, please correct me )

How to redirect cin and cout to files?

assuming your compiles prog name is x.exe and $ is the system shell or prompt

$ x <infile >outfile 

will take input from infile and will output to outfile .

Login to remote site with PHP cURL

Panama Jack Example not work for me - Give Fatal error: Call to undefined function build_unique_path(). I used this code - (more simple - my opinion) :

// options
$login_email = '[email protected]';
$login_pass = 'alabala4807';
$cookie_file_path = "/tmp/cookies.txt";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";

// begin script
$ch = curl_init();

// extra headers
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";

// basic curl options for all requests
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);

// set first URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// execute session to get cookies and required form inputs
$content = curl_exec($ch);

// grab the hidden inputs from the form required to login
$fields = getFormFields($content);
$fields['email'] = $login_email;
$fields['password'] = $login_pass;

// set postfields using what we extracted from the form
$POSTFIELDS = http_build_query($fields);
// change URL to login URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// set post options
curl_setopt($ch, CURLOPT_POST, 1);

// perform login
$result = curl_exec($ch);

print $result;

function getFormFields($data)
if (preg_match('/()/is', $data, $matches)) {
$inputs = getInputs($matches[1]);

return $inputs;
} else {
die('didnt find login form');

function getInputs($form)
$inputs = array();
$elements = preg_match_all("/(]+>)/is", $form, $matches);
if ($elements > 0) {
for($i = 0;$i $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];

$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];

$inputs[$name] = $value;

return $inputs;


//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, $grab_url);
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);


Extracting time from POSIXct

The time_t value for midnight GMT is always divisible by 86400 (24 * 3600). The value for seconds-since-midnight GMT is thus time %% 86400.

The hour in GMT is (time %% 86400) / 3600 and this can be used as the x-axis of the plot:

plot((as.numeric(times) %% 86400)/3600, val)

enter image description here

To adjust for a time zone, adjust the time before taking the modulus, by adding the number of seconds that your time zone is ahead of GMT. For example, US central daylight saving time (CDT) is 5 hours behind GMT. To plot against the time in CDT, the following expression is used:

plot(((as.numeric(times) - 5*3600) %% 86400)/3600, val)

Passing parameters to addTarget:action:forControlEvents

This fixed my problem but it crashed unless I changed



action:@selector(switchToNewsDetails: forEvent:)              

Entity Framework - Generating Classes

EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull :

How to set a time zone (or a Kind) of a DateTime value?

You can try this as well, it is easy to implement

TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);

Change the text to which standard time you want to change.

Use TimeZone feature of C# to implement.

How do I mock a service that returns promise in AngularJS Jasmine unit test?

using sinon :

const mockAction = sinon.stub(MyService.prototype,'actionBeingCalled')

Known that, httpPromise can be :

const httpPromise = (code) => new Promise((resolve, reject) =>
  (code >= 200 && code <= 299) ? resolve({ code }) : reject({ code, error:true })

In Java, remove empty elements from a list of Strings

If you get UnsupportedOperationException from using one of ther answer above and your List is created from Arrays.asList(), it is because you can't edit such List.

To fix, wrap the Arrays.asList() inside new LinkedList<String>():

    List<String> list = new LinkedList<String>(Arrays.asList(split));

Source is from this answer.

How can I show the table structure in SQL Server query?

In SQL Server, you can use this query:

USE Database_name


And do not forget to replace Database_name and Table_name with the exact names of your database and table names.

What primitive data type is time_t?

Unfortunately, it's not completely portable. It's usually integral, but it can be any "integer or real-floating type".

How to create an alert message in jsp page after submit process is complete

You can also create a new jsp file sayng that form is submited and in your main action file just write its file name

Eg. Your form is submited is in a file succes.jsp Then your action file will have


List directory tree structure in python?

List directory tree structure in Python?

We usually prefer to just use GNU tree, but we don't always have tree on every system, and sometimes Python 3 is available. A good answer here could be easily copy-pasted and not make GNU tree a requirement.

tree's output looks like this:

$ tree
+-- package
¦   +--
¦   +--
¦   +-- subpackage
¦   ¦   +--
¦   ¦   +--
¦   ¦   +--
¦   +-- subpackage2
¦       +--
¦       +--
¦       +--
+-- package2

4 directories, 9 files

I created the above directory structure in my home directory under a directory I call pyscratch.

I also see other answers here that approach that sort of output, but I think we can do better, with simpler, more modern code and lazily evaluating approaches.

Tree in Python

To begin with, let's use an example that

  • uses the Python 3 Path object
  • uses the yield and yield from expressions (that create a generator function)
  • uses recursion for elegant simplicity
  • uses comments and some type annotations for extra clarity
from pathlib import Path

# prefix components:
space =  '    '
branch = '¦   '
# pointers:
tee =    '+-- '
last =   '+-- '

def tree(dir_path: Path, prefix: str=''):
    """A recursive generator, given a directory Path object
    will yield a visual tree structure line by line
    with each line prefixed by the same characters
    contents = list(dir_path.iterdir())
    # contents each get pointers that are +-- with a final +-- :
    pointers = [tee] * (len(contents) - 1) + [last]
    for pointer, path in zip(pointers, contents):
        yield prefix + pointer +
        if path.is_dir(): # extend the prefix and recurse:
            extension = branch if pointer == tee else space 
            # i.e. space because last, +-- , above so no more |
            yield from tree(path, prefix=prefix+extension)

and now:

for line in tree(Path.home() / 'pyscratch'):


+-- package
¦   +--
¦   +--
¦   +-- subpackage
¦   ¦   +--
¦   ¦   +--
¦   ¦   +--
¦   +-- subpackage2
¦       +--
¦       +--
¦       +--
+-- package2

We do need to materialize each directory into a list because we need to know how long it is, but afterwards we throw the list away. For deep and broad recursion this should be lazy enough.

The above code, with the comments, should be sufficient to fully understand what we're doing here, but feel free to step through it with a debugger to better grock it if you need to.

More features

Now GNU tree gives us a couple of useful features that I'd like to have with this function:

  • prints the subject directory name first (does so automatically, ours does not)
  • prints the count of n directories, m files
  • option to limit recursion, -L level
  • option to limit to just directories, -d

Also, when there is a huge tree, it is useful to limit the iteration (e.g. with islice) to avoid locking up your interpreter with text, as at some point the output becomes too verbose to be useful. We can make this arbitrarily high by default - say 1000.

So let's remove the previous comments and fill out this functionality:

from pathlib import Path
from itertools import islice

space =  '    '
branch = '¦   '
tee =    '+-- '
last =   '+-- '
def tree(dir_path: Path, level: int=-1, limit_to_directories: bool=False,
         length_limit: int=1000):
    """Given a directory Path object print a visual tree structure"""
    dir_path = Path(dir_path) # accept string coerceable to Path
    files = 0
    directories = 0
    def inner(dir_path: Path, prefix: str='', level=-1):
        nonlocal files, directories
        if not level: 
            return # 0, stop iterating
        if limit_to_directories:
            contents = [d for d in dir_path.iterdir() if d.is_dir()]
            contents = list(dir_path.iterdir())
        pointers = [tee] * (len(contents) - 1) + [last]
        for pointer, path in zip(pointers, contents):
            if path.is_dir():
                yield prefix + pointer +
                directories += 1
                extension = branch if pointer == tee else space 
                yield from inner(path, prefix=prefix+extension, level=level-1)
            elif not limit_to_directories:
                yield prefix + pointer +
                files += 1
    iterator = inner(dir_path, level=level)
    for line in islice(iterator, length_limit):
    if next(iterator, None):
        print(f'... length_limit, {length_limit}, reached, counted:')
    print(f'\n{directories} directories' + (f', {files} files' if files else ''))

And now we can get the same sort of output as tree:

tree(Path.home() / 'pyscratch')


+-- package
¦   +--
¦   +--
¦   +-- subpackage
¦   ¦   +--
¦   ¦   +--
¦   ¦   +--
¦   +-- subpackage2
¦       +--
¦       +--
¦       +--
+-- package2

4 directories, 9 files

And we can restrict to levels:

tree(Path.home() / 'pyscratch', level=2)


+-- package
¦   +--
¦   +--
¦   +-- subpackage
¦   +-- subpackage2
+-- package2

4 directories, 3 files

And we can limit the output to directories:

tree(Path.home() / 'pyscratch', level=2, limit_to_directories=True)


+-- package
¦   +-- subpackage
¦   +-- subpackage2
+-- package2

4 directories


In retrospect, we could have used path.glob for matching. We could also perhaps use path.rglob for recursive globbing, but that would require a rewrite. We could also use itertools.tee instead of materializing a list of directory contents, but that could have negative tradeoffs and would probably make the code even more complex.

Comments are welcome!

Set database from SINGLE USER mode to MULTI USER

just go to database properties and change SINGLE USER mode to MULTI USER

enter image description here

NOTE: if its not work for you then take Db backup and restore again and do above method again




Android: Pass data(extras) to a fragment

great answer by @Rarw. Try using a bundle to pass information from one fragment to another

How to select an element with 2 classes

You can chain class selectors without a space between them:

.a.b {
     color: #666;

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

How to use the toString method in Java?


public class Test {

    public static void main(String args[]) {

        ArrayList<Student> a = new ArrayList<Student>();
        a.add(new Student("Steve", 12, "Daniel"));
        a.add(new Student("Sachin", 10, "Tendulkar"));




    static void display(ArrayList<Student> stu) {

        stu.add(new Student("Yuvi", 12, "Bhajji"));




public class Student {

    public String name;

    public int id;

    public String email;

    Student() {


    Student(String name, int id, String email) { = name; = id; = email;


     public String toString(){           //using these toString to avoid the output like this [com.steve.test.Student@6e1408, com.steve.test.Student@e53108]
          return name+" "+id+" "+email;     

    public String getName(){

        return name;

    public void setName(String name){;

    public int getId(){

        return id;

    public void setId(int id){;

    public String getEmail(){

        return email;


    public void setEmail(String email){;


[Steve 12 Daniel, Sachin 10 Tendulkar]

[Steve 12 Daniel, Sachin 10 Tendulkar, Yuvi 12 Bhajji]

If you are not used toString() in Pojo( class,you will get an output like [com.steve.test.Student@6e1408, com.steve.test.Student@e53108].To avoid these kind of issue we are using toString() method.

Set android shape color programmatically

Try this:

 public void setGradientColors(int bottomColor, int topColor) {
 GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]  
 {bottomColor, topColor});

for more detail check this link this

hope help.

Eclipse does not highlight matching variables

For others running into this without any of the above solutions working AND you have modified the default theme, you might want to check the highlight color for occurrences.

Preferences > General > Editors > Text Editors > Annotations

Then select Occurrences in the Annotation Types, and change the Color Box to something other than your background color in your editor. You can also change the Highlight to a outline box by Checking "Text as" and selecting "Box" from the drop-down box (which is easier to see various syntax colors then with the highlights)

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

Title_Authors is a look up two things join at a time project results and continue chaining

        DataClasses1DataContext db = new DataClasses1DataContext();
        var queryresults = from a in db.Authors                                          
                    join ba in db.Title_Authors                           
                    on a.Au_ID equals ba.Au_ID into idAuthor
                    from c in idAuthor
                    join t in db.Titles  
                    on c.ISBN equals t.ISBN 
                    select new { Author = a.Author1,Title= t.Title1 };

        foreach (var item in queryresults)

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 


if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

Regular expression negative lookahead

If you revise your regular expression like this:


...then it will match all inputs that contain drupal-6.14/ followed by sites followed by anything other than /all or /default. For example:


Changing ?= to ?! to match your original regex simply negates those matches:


So, this simply means that drupal-6.14/ now cannot be followed by sites followed by anything other than /all or /default. So now, these inputs will satisfy the regex:


But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/ is followed by anything other than sites as well. For example:


Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14 except those subdirectories of sites whose name begins with anything other than all or default.

'adb' is not recognized as an internal or external command, operable program or batch file

Follow path of you platform tools folder in android setup folder where you will found adb.exe


Check the screenshot for details

enter image description here

Convert hexadecimal string (hex) to a binary string

import java.util.*;
public class HexadeciamlToBinary
   public static void main()
       Scanner sc=new Scanner(;
       System.out.println("enter the hexadecimal number");
       String s=sc.nextLine();
       String p="";
       long n=0;
       int c=0;
       for(int i=s.length()-1;i>=0;i--)
         else if(s.charAt(i)=='B')
        else if(s.charAt(i)=='C')
        else if(s.charAt(i)=='D')
        else if(s.charAt(i)=='E')
        else if(s.charAt(i)=='F')
    String s1="",k="";
    for(int i=0;i<k.length();i++)
    System.out.println("The respective binary number is : "+s1);
        System.out.println("The respective binary number is : "+n);

Java 8 optional: ifPresent return object orElseThrow exception

Two options here:

Replace ifPresent with map and use Function instead of Consumer

private String getStringIfObjectIsPresent(Optional<Object> object) {
    return object
            .map(obj -> {
                String result = "result";
                //some logic with result and return it
                return result;

Use isPresent:

private String getStringIfObjectIsPresent(Optional<Object> object) {
    if (object.isPresent()) {
        String result = "result";
        //some logic with result and return it
        return result;
    } else {
        throw new MyCustomException();

How to declare a variable in SQL Server and use it in the same Stored Procedure

In sql 2012 (and maybe as far back as 2005), you should do this:

EXEC AddBrand @BrandName = 'Gucci', @CategoryId = 23

How to manually set an authenticated user in Spring Security / SpringMVC

The new filtering feature in Servlet 2.4 basically alleviates the restriction that filters can only operate in the request flow before and after the actual request processing by the application server. Instead, Servlet 2.4 filters can now interact with the request dispatcher at every dispatch point. This means that when a Web resource forwards a request to another resource (for instance, a servlet forwarding the request to a JSP page in the same application), a filter can be operating before the request is handled by the targeted resource. It also means that should a Web resource include the output or function from other Web resources (for instance, a JSP page including the output from multiple other JSP pages), Servlet 2.4 filters can work before and after each of the included resources. .

To turn on that feature you need:




return "forward:/login?j_username=" + registrationModel.getUserEmail()
        + "&j_password=" + registrationModel.getPassword();

jQuery: Uncheck other checkbox on one checked

I wanted to add an answer if the checkboxes are being generated in a loop. For example if your structure is like this (Assuming you are using server side constructs on your View, like a foreach loop):

<li id="checkboxlist" class="list-group-item card">
  <div class="checkbox checkbox-inline">
    <label><input type="checkbox" id="checkbox1">Checkbox 1</label>
    <label><input type="checkbox" id="checkbox2">Checkbox 2</label>

<li id="checkboxlist" class="list-group-item card">
  <div class="checkbox checkbox-inline">
    <label><input type="checkbox" id="checkbox1">Checkbox 1</label>
    <label><input type="checkbox" id="checkbox2">Checkbox 2</label>

Corresponding Jquery:

$(".list-group-item").each(function (i, li) {
  var currentli = $(li);
  $(currentli).find("#checkbox1").on('change', function () {

  $(currentli).find("#checkbox2").on('change', function () {
       $(currentli).find("#checkbox1").not(this).prop('checked', false);

Working DEMO:

Remove a marker from a GoogleMap

If you use Kotlin language you just add this code:

Create global variables of GoogleMap and Marker types.

I use variable marker to make variable marker value can change directly

private lateinit var map: GoogleMap
private lateinit var marker: Marker

And I use this function/method to add the marker on my map:

private fun placeMarkerOnMap(location: LatLng) {
    val markerOptions = MarkerOptions().position(location)
    val titleStr = getAddress(location)
    marker = map.addMarker(markerOptions)

After I create the function I place this code on the onMapReady() to remove the marker and create a new one:

map.setOnMapClickListener { location ->

It's bonus if you want to display the address location when you click the marker add this code to hide and show the marker address but you need a method to get the address location. I got the code from this post: How to get complete address from latitude and longitude?

map.setOnMarkerClickListener {marker ->
        if (marker.isInfoWindowShown){

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site


    url : '',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    success : function(data) {              
        alert('Data: '+data);
    error : function(request,error)
        alert("Request: "+JSON.stringify(request));

I hope be helpful!

App can't be opened because it is from an unidentified developer

In terminal type the command:

xattr -d [file path here]

Once you click enter it will no longer have that problem. Its annoying that apple adds a quarantine to files automatically. I do not know how to turn this off but there probably is a way...

How to float 3 divs side by side using CSS?

The modern way is to use the CSS flexbox, see support tables.

.container {_x000D_
  display: flex;_x000D_
.container > div {_x000D_
  flex: 1; /*grow*/_x000D_
<div class="container">_x000D_
  <div>Left div</div>_x000D_
  <div>Middle div</div>  _x000D_
  <div>Right div</div>_x000D_

You can also use CSS grid, see support tables.

.container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr 1fr; /* fraction*/_x000D_
<div class="container">_x000D_
  <div>Left div</div>_x000D_
  <div>Middle div</div>  _x000D_
  <div>Right div</div>_x000D_

How can you have SharePoint Link Lists default to opening in a new window?

The same instance for SP2010; the Links List webpart will not automatically open in a new window, rather user must manually rt click Link object and select Open in New Window.

The add/ insert Link option withkin SP2010 will allow a user to manually configure the link to open in a new window.

Maybe SP2012 release will adrress this...

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

How do I extract data from a DataTable?

The simplest way to extract data from a DataTable when you have multiple data types (not just strings) is to use the Field<T> extension method available in the System.Data.DataSetExtensions assembly.

var id = row.Field<int>("ID");         // extract and parse int
var name = row.Field<string>("Name");  // extract string

From MSDN, the Field<T> method:

Provides strongly-typed access to each of the column values in the DataRow.

This means that when you specify the type it will validate and unbox the object.

For example:

// iterate over the rows of the datatable
foreach (var row in table.AsEnumerable())  // AsEnumerable() returns IEnumerable<DataRow>
    var id = row.Field<int>("ID");                           // int
    var name = row.Field<string>("Name");                    // string
    var orderValue = row.Field<decimal>("OrderValue");       // decimal
    var interestRate = row.Field<double>("InterestRate");    // double
    var isActive = row.Field<bool>("Active");                // bool
    var orderDate = row.Field<DateTime>("OrderDate");        // DateTime

It also supports nullable types:

DateTime? date = row.Field<DateTime?>("DateColumn");

This can simplify extracting data from DataTable as it removes the need to explicitly convert or parse the object into the correct types.

'invalid value encountered in double_scalars' warning, possibly numpy

Sometimes NaNs or null values in data will generate this error with Numpy. If you are ingesting data from say, a CSV file or something like that, and then operating on the data using numpy arrays, the problem could have originated with your data ingest. You could try feeding your code a small set of data with known values, and see if you get the same result.

using sql count in a case statement

select sum(rsp_ind = 0) as `New`,
       sum(rsp_ind = 1) as `Accepted` 
from tb_a

How can I send an inner <div> to the bottom of its parent <div>?

You may not want absolute positioning because it breaks the reflow: in some circumstances, a better solution is to make the grandparent element display:table; and the parent element display:table-cell;vertical-align:bottom;. After doing this, you should be able to give the the child elements display:inline-block; and they will automagically flow towards the bottom of the parent.

The model backing the 'ApplicationDbContext' context has changed since the database was created

this comes because you add some property to one of your model and you did not update-Database . to solve this you have to remove it from model or you have to add-migration anyProperName with that properties and Update-database.

How does DISTINCT work when using JPA and Hibernate

I agree with kazanaki's answer, and it helped me. I wanted to select the whole entity, so I used

 select DISTINCT(c) from Customer c

In my case I have many-to-many relationship, and I want to load entities with collections in one query.

I used LEFT JOIN FETCH and at the end I had to make the result distinct.

ECMAScript 6 class destructor

You have to manually "destruct" objects in JS. Creating a destroy function is common in JS. In other languages this might be called free, release, dispose, close, etc. In my experience though it tends to be destroy which will unhook internal references, events and possibly propagates destroy calls to child objects as well.

WeakMaps are largely useless as they cannot be iterated and this probably wont be available until ECMA 7 if at all. All WeakMaps let you do is have invisible properties detached from the object itself except for lookup by the object reference and GC so that they don't disturb it. This can be useful for caching, extending and dealing with plurality but it doesn't really help with memory management for observables and observers. WeakSet is a subset of WeakMap (like a WeakMap with a default value of boolean true).

There are various arguments on whether to use various implementations of weak references for this or destructors. Both have potential problems and destructors are more limited.

Destructors are actually potentially useless for observers/listeners as well because typically the listener will hold references to the observer either directly or indirectly. A destructor only really works in a proxy fashion without weak references. If your Observer is really just a proxy taking something else's Listeners and putting them on an observable then it can do something there but this sort of thing is rarely useful. Destructors are more for IO related things or doing things outside of the scope of containment (IE, linking up two instances that it created).

The specific case that I started looking into this for is because I have class A instance that takes class B in the constructor, then creates class C instance which listens to B. I always keep the B instance around somewhere high above. A I sometimes throw away, create new ones, create many, etc. In this situation a Destructor would actually work for me but with a nasty side effect that in the parent if I passed the C instance around but removed all A references then the C and B binding would be broken (C has the ground removed from beneath it).

In JS having no automatic solution is painful but I don't think it's easily solvable. Consider these classes (pseudo):

function Filter(stream) {
    stream.on('data', function() {
        this.emit('data', data.toString().replace('somenoise', '')); // Pretend chunks/multibyte are not a problem.
Filter.prototype.__proto__ = EventEmitter.prototype;
function View(df, stream) {
    df.on('data', function(data) {
        stream.write(data.toUpper()); // Shout.

On a side note, it's hard to make things work without anonymous/unique functions which will be covered later.

In a normal case instantiation would be as so (pseudo):

var df = new Filter(stdin),
    v1 = new View(df, stdout),
    v2 = new View(df, stderr);

To GC these normally you would set them to null but it wont work because they've created a tree with stdin at the root. This is basically what event systems do. You give a parent to a child, the child adds itself to the parent and then may or may not maintain a reference to the parent. A tree is a simple example but in reality you may also find yourself with complex graphs albeit rarely.

In this case, Filter adds a reference to itself to stdin in the form of an anonymous function which indirectly references Filter by scope. Scope references are something to be aware of and that can be quite complex. A powerful GC can do some interesting things to carve away at items in scope variables but that's another topic. What is critical to understand is that when you create an anonymous function and add it to something as a listener to ab observable, the observable will maintain a reference to the function and anything the function references in the scopes above it (that it was defined in) will also be maintained. The views do the same but after the execution of their constructors the children do not maintain a reference to their parents.

If I set any or all of the vars declared above to null it isn't going to make a difference to anything (similarly when it finished that "main" scope). They will still be active and pipe data from stdin to stdout and stderr.

If I set them all to null it would be impossible to have them removed or GCed without clearing out the events on stdin or setting stdin to null (assuming it can be freed like this). You basically have a memory leak that way with in effect orphaned objects if the rest of the code needs stdin and has other important events on it prohibiting you from doing the aforementioned.

To get rid of df, v1 and v2 I need to call a destroy method on each of them. In terms of implementation this means that both the Filter and View methods need to keep the reference to the anonymous listener function they create as well as the observable and pass that to removeListener.

On a side note, alternatively you can have an obserable that returns an index to keep track of listeners so that you can add prototyped functions which at least to my understanding should be much better on performance and memory. You still have to keep track of the returned identifier though and pass your object to ensure that the listener is bound to it when called.

A destroy function adds several pains. First is that I would have to call it and free the reference:

df = v1 = v2 = null;

This is a minor annoyance as it's a bit more code but that is not the real problem. When I hand these references around to many objects. In this case when exactly do you call destroy? You cannot simply hand these off to other objects. You'll end up with chains of destroys and manual implementation of tracking either through program flow or some other means. You can't fire and forget.

An example of this kind of problem is if I decide that View will also call destroy on df when it is destroyed. If v2 is still around destroying df will break it so destroy cannot simply be relayed to df. Instead when v1 takes df to use it, it would need to then tell df it is used which would raise some counter or similar to df. df's destroy function would decrease than counter and only actually destroy if it is 0. This sort of thing adds a lot of complexity and adds a lot that can go wrong the most obvious of which is destroying something while there is still a reference around somewhere that will be used and circular references (at this point it's no longer a case of managing a counter but a map of referencing objects). When you're thinking of implementing your own reference counters, MM and so on in JS then it's probably deficient.

If WeakSets were iterable, this could be used:

function Observable() { = {open: new WeakSet(), close: new WeakSet()};
Observable.prototype.on = function(type, f) {[type].add(f);
Observable.prototype.emit = function(type, ...args) {[type].forEach(f => f(...args));
}; = function(type, f) {[type].delete(f);

In this case the owning class must also keep a token reference to f otherwise it will go poof.

If Observable were used instead of EventListener then memory management would be automatic in regards to the event listeners.

Instead of calling destroy on each object this would be enough to fully remove them:

df = v1 = v2 = null;

If you didn't set df to null it would still exist but v1 and v2 would automatically be unhooked.

There are two problems with this approach however.

Problem one is that it adds a new complexity. Sometimes people do not actually want this behaviour. I could create a very large chain of objects linked to each other by events rather than containment (references in constructor scopes or object properties). Eventually a tree and I would only have to pass around the root and worry about that. Freeing the root would conveniently free the entire thing. Both behaviours depending on coding style, etc are useful and when creating reusable objects it's going to be hard to either know what people want, what they have done, what you have done and a pain to work around what has been done. If I use Observable instead of EventListener then either df will need to reference v1 and v2 or I'll have to pass them all if I want to transfer ownership of the reference to something else out of scope. A weak reference like thing would mitigate the problem a little by transferring control from Observable to an observer but would not solve it entirely (and needs check on every emit or event on itself). This problem can be fixed I suppose if the behaviour only applies to isolated graphs which would complicate the GC severely and would not apply to cases where there are references outside the graph that are in practice noops (only consume CPU cycles, no changes made).

Problem two is that either it is unpredictable in certain cases or forces the JS engine to traverse the GC graph for those objects on demand which can have a horrific performance impact (although if it is clever it can avoid doing it per member by doing it per WeakMap loop instead). The GC may never run if memory usage does not reach a certain threshold and the object with its events wont be removed. If I set v1 to null it may still relay to stdout forever. Even if it does get GCed this will be arbitrary, it may continue to relay to stdout for any amount of time (1 lines, 10 lines, 2.5 lines, etc).

The reason WeakMap gets away with not caring about the GC when non-iterable is that to access an object you have to have a reference to it anyway so either it hasn't been GCed or hasn't been added to the map.

I am not sure what I think about this kind of thing. You're sort of breaking memory management to fix it with the iterable WeakMap approach. Problem two can also exist for destructors as well.

All of this invokes several levels of hell so I would suggest to try to work around it with good program design, good practices, avoiding certain things, etc. It can be frustrating in JS however because of how flexible it is in certain aspects and because it is more naturally asynchronous and event based with heavy inversion of control.

There is one other solution that is fairly elegant but again still has some potentially serious hangups. If you have a class that extends an observable class you can override the event functions. Add your events to other observables only when events are added to yourself. When all events are removed from you then remove your events from children. You can also make a class to extend your observable class to do this for you. Such a class could provide hooks for empty and non-empty so in a since you would be Observing yourself. This approach isn't bad but also has hangups. There is a complexity increase as well as performance decrease. You'll have to keep a reference to object you observe. Critically, it also will not work for leaves but at least the intermediates will self destruct if you destroy the leaf. It's like chaining destroy but hidden behind calls that you already have to chain. A large performance problem is with this however is that you may have to reinitialise internal data from the Observable everytime your class becomes active. If this process takes a very long time then you might be in trouble.

If you could iterate WeakMap then you could perhaps combine things (switch to Weak when no events, Strong when events) but all that is really doing is putting the performance problem on someone else.

There are also immediate annoyances with iterable WeakMap when it comes to behaviour. I mentioned briefly before about functions having scope references and carving. If I instantiate a child that in the constructor that hooks the listener 'console.log(param)' to parent and fails to persist the parent then when I remove all references to the child it could be freed entirely as the anonymous function added to the parent references nothing from within the child. This leaves the question of what to do about parent.weakmap.add(child, (param) => console.log(param)). To my knowledge the key is weak but not the value so weakmap.add(object, object) is persistent. This is something I need to reevaluate though. To me that looks like a memory leak if I dispose all other object references but I suspect in reality it manages that basically by seeing it as a circular reference. Either the anonymous function maintains an implicit reference to objects resulting from parent scopes for consistency wasting a lot of memory or you have behaviour varying based on circumstances which is hard to predict or manage. I think the former is actually impossible. In the latter case if I have a method on a class that simply takes an object and adds console.log it would be freed when I clear the references to the class even if I returned the function and maintained a reference. To be fair this particular scenario is rarely needed legitimately but eventually someone will find an angle and will be asking for a HalfWeakMap which is iterable (free on key and value refs released) but that is unpredictable as well (obj = null magically ending IO, f = null magically ending IO, both doable at incredible distances).

HTML5 pattern for formatting input box to take date mm/dd/yyyy?


This is pattern to enter the date for textbox in HTML5.
The first one[0-9]{1,2} will take only decimal number minimum 1 and maximum 2.
And other similarly.

Difference between multitasking, multithreading and multiprocessing?

Multitasking - This is basically multiprogramming in the context of a single-user interactive environment, in which the OS switches between several programs in main memory so as to give the illusion that several are running at once. Common scheduling algorithms used for multitasking are: Round-Robin, Priority Scheduling (multiple queues), Shortest-Process-Next.

MULTIPROCESSING is like the OS handling the different jobs in main memory in such a way that it gives its time to each and every job when other is busy for some task such as I/O operation. So as long as at least one job needs to execute, the cpu never sit idle. and here it is automatically handled by the OS,

How to take last four characters from a varchar?

Use the RIGHT() function:

SELECT RIGHT( '1234567890', 4 ); -- returns '7890'

CSS checkbox input styling

With CSS 2 you can do this:

input[type='checkbox'] { ... }

This should be pretty widely supported by now. See support for browsers

Parse HTML table to Python list?

If the HTML is not XML you can't do it with etree. But even then, you don't have to use an external library for parsing a HTML table. In python 3 you can reach your goal with HTMLParser from html.parser. I've the code of the simple derived HTMLParser class here in a github repo.

You can use that class (here named HTMLTableParser) the following way:

import urllib.request
from html_table_parser import HTMLTableParser

target = ''

# get website content
req = urllib.request.Request(url=target)
f = urllib.request.urlopen(req)
xhtml ='utf-8')

# instantiate the parser and feed it
p = HTMLTableParser()

The output of this is a list of 2D-lists representing tables. It looks maybe like this:

[[['   ', ' Anmelden ']],
 [['Land', 'Code', 'Für Kunden von'],
  ['Vereinigte Staaten', '40404', '(beliebig)'],
  ['Kanada', '21212', '(beliebig)'],
  ['3424486444', 'Vodafone'],
  ['  Zeige SMS-Kurzwahlen für andere Länder ']]]

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

Swift 5

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

//Delete or comment the below lines on your SceneDelegate.

//        guard let windowScene = (scene as? UIWindowScene) else { return }
//        window?.windowScene = windowScene
//        window?.makeKeyAndVisible()

        let viewController = ListVC()
        let navViewController = UINavigationController(rootViewController: viewController)
        window?.rootViewController = navViewController


How to use hex color values

You can use this extension on UIColor which converts Your String (Hexadecimal , RGBA) to UIColor and vice versa.

extension UIColor {

  //Convert RGBA String to UIColor object
  //"rgbaString" must be separated by space "0.5 0.6 0.7 1.0" 50% of Red 60% of Green 70% of Blue Alpha 100%
  public convenience init?(rgbaString : String){
      self.init(ciColor: CIColor(string: rgbaString))

  //Convert UIColor to RGBA String
  func toRGBAString()-> String {
    var r: CGFloat = 0
    var g: CGFloat = 0
    var b: CGFloat = 0
    var a: CGFloat = 0
    self.getRed(&r, green: &g, blue: &b, alpha: &a)
    return "\(r) \(g) \(b) \(a)"

  //return UIColor from Hexadecimal Color string
  public convenience init?(hexString: String) {  
    let r, g, b, a: CGFloat

    if hexString.hasPrefix("#") {
      let start = hexString.index(hexString.startIndex, offsetBy: 1)
      let hexColor = hexString.substring(from: start)

      if hexColor.characters.count == 8 {
        let scanner = Scanner(string: hexColor)
        var hexNumber: UInt64 = 0

        if scanner.scanHexInt64(&hexNumber) {
          r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
          g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
          b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
          a = CGFloat(hexNumber & 0x000000ff) / 255
          self.init(red: r, green: g, blue: b, alpha: a)

    return nil

  // Convert UIColor to Hexadecimal String
  func toHexString() -> String {
    var r: CGFloat = 0
    var g: CGFloat = 0
    var b: CGFloat = 0
    var a: CGFloat = 0
    self.getRed(&r, green: &g, blue: &b, alpha: &a)
    return String(
        format: "%02X%02X%02X",
        Int(r * 0xff),
        Int(g * 0xff),
        Int(b * 0xff))

Abstract variables in Java?

Use enums to force values as well to keep bound checks:

enum Speed {
    HIGH, LOW;
private abstract  class SuperClass {
    Speed speed;
    SuperClass(Speed speed) {
        this.speed = speed;
private class ChildClass extends SuperClass {
    ChildClass(Speed speed) {

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

The javascript library sugar.js ( has functions to format dates


Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')

How to get rid of underline for Link component of React Router?

I see you're using inline styles. textDecoration: 'none' is used in child, where in fact it should be used inside <Link> as such:

<Link to="first" style={{ textDecoration: 'none' }}>
  <MenuItem style={{ paddingLeft: 13 }}>Team 1</MenuItem>

<Link> will essentially return a standard <a> tag, which is why we apply textDecoration rule there.

I hope that helps

How to scanf only integer?

  1. You take scanf().
  2. You throw it in the bin.
  3. You use fgets() to get an entire line.
  4. You use strtol() to parse the line as an integer, checking if it consumed the entire line.
char *end;
char buf[LINE_MAX];

do {
     if (!fgets(buf, sizeof buf, stdin))

     // remove \n
     buf[strlen(buf) - 1] = 0;

     int n = strtol(buf, &end, 10);
} while (end != buf + strlen(buf));

How do I get a PHP class constructor to call its parent's parent's constructor?

Ok, Yet another ugly solution:

Create a function in Papa like:

protected function call2Granpa() {
     return parent::__construct();

Then in Kiddo you use:

parent::call2Granpa(); //instead of calling constructor in Papa.

I think it could work... I haven't test it, so I'm not sure if the objects are created correctly.

I used this approach but with non-constructor functions.

How do I iterate and modify Java Sets?

You can do what you want if you use an iterator object to go over the elements in your set. You can remove them on the go an it's ok. However removing them while in a for loop (either "standard", of the for each kind) will get you in trouble:

Set<Integer> set = new TreeSet<Integer>();

    //good way:
    Iterator<Integer> iterator = set.iterator();
    while(iterator.hasNext()) {
        Integer setElement =;
        if(setElement==2) {

    //bad way:
    for(Integer setElement:set) {
        if(setElement==2) {
            //might work or might throw exception, Java calls it indefined behaviour:

As per @mrgloom's comment, here are more details as to why the "bad" way described above is, well... bad :

Without getting into too much details about how Java implements this, at a high level, we can say that the "bad" way is bad because it is clearly stipulated as such in the Java docs:

stipulate, amongst others, that (emphasis mine):

"For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected" (...)

"Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception."

To go more into details: an object that can be used in a forEach loop needs to implement the "java.lang.Iterable" interface (javadoc here). This produces an Iterator (via the "Iterator" method found in this interface), which is instantiated on demand, and will contain internally a reference to the Iterable object from which it was created. However, when an Iterable object is used in a forEach loop, the instance of this iterator is hidden to the user (you cannot access it yourself in any way).

This, coupled with the fact that an Iterator is pretty stateful, i.e. in order to do its magic and have coherent responses for its "next" and "hasNext" methods it needs that the backing object is not changed by something else than the iterator itself while it's iterating, makes it so that it will throw an exception as soon as it detects that something changed in the backing object while it is iterating over it.

Java calls this "fail-fast" iteration: i.e. there are some actions, usually those that modify an Iterable instance (while an Iterator is iterating over it). The "fail" part of the "fail-fast" notion refers to the ability of an Iterator to detect when such "fail" actions happen. The "fast" part of the "fail-fast" (and, which in my opinion should be called "best-effort-fast"), will terminate the iteration via ConcurrentModificationException as soon as it can detect that a "fail" action has happen.

QByteArray to QString

You can use this QString constructor for conversion from QByteArray to QString:

QString(const QByteArray &ba)

QByteArray data;
QString DataAsString = QString(data);

How can I do string interpolation in JavaScript?

While templates are probably best for the case you describe, if you have or want your data and/or arguments in iterable/array form, you can use String.raw.

  raw: ["I'm ", " years old!"]
}, 3);

With the data as an array, one can use the spread operator:

const args = [3, 'yesterday'];
  raw: ["I'm ", " years old as of ", ""]
}, ...args);

Writing Python lists to columns in csv

import csv
dic = {firstcol,secondcol} #dictionary
csv = open('result.csv', "w") 
for key in dic.keys():
    row ="\n"+ str(key) + "," + str(dic[key]) 

ASP.NET MVC - passing parameters to the controller

public ActionResult ViewNextItem(int? id) makes the id integer a nullable type, no need for string<->int conversions.

What are the ways to make an html link open a folder

Does not work in Chrome, but this other answers suggests a solution via a plugin:

Can Google Chrome open local links?

Java count occurrence of each item in an array

I would use a hashtable with in key takes the element of the array (here string) and in value an Integer.

then go through the list doing something like this :

for(String s:array){
  Integer i = hash.get(s);
  hash.put(s, new Interger(1));

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

Simple test, accessing http://localhost:8000/hello?foo=bar#this-is-not-sent-to-server

python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"
Serving HTTP on port 8000 ...
localhost - - [02/Jun/2009 12:48:47] code 404, message File not found
localhost - - [02/Jun/2009 12:48:47] "GET /hello?foo=bar HTTP/1.1" 404 -

The server receives the request without the #appendage - anything after the hash tag is simply an anchor lookup on the client.

You can find the anchor name used within the URL via javascript using, as an example:


The parse_url() function in PHP can work if you already have the needed URL string including the fragment (

echo parse_url("http://foo?bar#fizzbuzz",PHP_URL_FRAGMENT);

Output: fizzbuzz

But I don't think PHP receives the fragment information because it's client-only.

How to get a jqGrid selected row cells value

Use "selrow" to get the selected row Id

var myGrid = $('#myGridId');

var selectedRowId = myGrid.jqGrid("getGridParam", 'selrow');

and then use getRowData to get the selected row at index selectedRowId.

var selectedRowData = myGrid.getRowData(selectedRowId);

If the multiselect is set to true on jqGrid, then use "selarrrow" to get list of selected rows:

var selectedRowIds = myGrid.jqGrid("getGridParam", 'selarrrow');

Use loop to iterate the list of selected rows:

var selectedRowData;

for(selectedRowIndex = 0; selectedRowIndex < selectedRowIds .length; selectedRowIds ++) {

   selectedRowData = myGrid.getRowData(selectedRowIds[selectedRowIndex]);


How to fill a datatable with List<T>

Try this

static DataTable ConvertToDatatable(List<Item> list)
    DataTable dt = new DataTable();

    foreach (var item in list)
        var row = dt.NewRow();

        row["Name"] = item.Name;
        row["Price"] = Convert.ToString(item.Price);
        row["URL"] = item.URL;


    return dt;

How can I put a ListView into a ScrollView without it collapsing?

A solution I use is, to add all Content of the ScrollView (what should be above and under the listView) as headerView and footerView in the ListView.

So it works like, also the convertview is resued how it should be.

Comparing two dictionaries and checking how many (key, value) pairs are equal

>>> hash_1
{'a': 'foo', 'b': 'bar'}
>>> hash_2
{'a': 'foo', 'b': 'bar'}
>>> set_1 = set (hash_1.iteritems())
>>> set_1
set([('a', 'foo'), ('b', 'bar')])
>>> set_2 = set (hash_2.iteritems())
>>> set_2
set([('a', 'foo'), ('b', 'bar')])
>>> len (set_1.difference(set_2))
>>> if (len(set_1.difference(set_2)) | len(set_2.difference(set_1))) == False:
...    print "The two hashes match."
The two hashes match.
>>> hash_2['c'] = 'baz'
>>> hash_2
{'a': 'foo', 'c': 'baz', 'b': 'bar'}
>>> if (len(set_1.difference(set_2)) | len(set_2.difference(set_1))) == False:
...     print "The two hashes match."
>>> hash_2.pop('c')

Here's another option:

>>> id(hash_1)
>>> id(hash_2)

So as you see the two id's are different. But the rich comparison operators seem to do the trick:

>>> hash_1 == hash_2
>>> hash_2
{'a': 'foo', 'b': 'bar'}
>>> set_2 = set (hash_2.iteritems())
>>> if (len(set_1.difference(set_2)) | len(set_2.difference(set_1))) == False:
...     print "The two hashes match."
The two hashes match.

API pagination best practices

Just to add to this answer by Kamilk :

Depends a lot on how large dataset you are working on. Small data sets do work on effectively on offset pagination but large realtime datasets do require cursor pagination.

Found a wonderful article on how Slack evolved its api's pagination as there datasets increased explaining the positives and negatives at every stage :

How to concatenate two numbers in javascript?

This is the easy way to do this

var value = 5 + "" + 6;

Can't install any packages in Node.js using "npm install"

I found the there is a certificate expired issue with:

npm set registry

So I made it http, not https :-

npm set registry

And have no problems so far.

How do I count cells that are between two numbers in Excel?


For cells containing the values between 21-31, the formula is:


Unknown column in 'field list' error on MySQL Update query

In my case, it was caused by an unseen trailing space at the end of the column name. Just check if you really use "y" or "y " instead.

Unloading classes in java?

Classes have an implicit strong reference to their ClassLoader instance, and vice versa. They are garbage collected as with Java objects. Without hitting the tools interface or similar, you can't remove individual classes.

As ever you can get memory leaks. Any strong reference to one of your classes or class loader will leak the whole thing. This occurs with the Sun implementations of ThreadLocal, java.sql.DriverManager and java.beans, for instance.

Plotting multiple lines, in different colors, with pandas dataframe

You can use this code to get your desire output

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'color': ['red','red','red','blue','blue','blue'], 'x': [0,1,2,3,4,5],'y': [0,1,2,9,16,25]})
print df

  color  x   y
0   red  0   0
1   red  1   1
2   red  2   2
3  blue  3   9
4  blue  4  16
5  blue  5  25

To plot graph

a = df.iloc[[i for i in xrange(0,len(df)) if df['x'][i]==df['y'][i]]].plot(x='x',y='y',color = 'red')
df.iloc[[i for i in xrange(0,len(df)) if df['y'][i]== df['x'][i]**2]].plot(x='x',y='y',color = 'blue',ax=a)

Output The output result will look like this

How to select specific columns in laravel eloquent

Table::where('id', 1)->get(['name','surname']);

Tests not running in Test Explorer

What works for me is to delete the bin folder, then rebuild the project.

Don't reload application when orientation changes

protected void onSaveInstanceState(Bundle b)
    String str="Screen Change="+String.valueOf(screenChange)+"....";
        Toast.makeText(ctx,str+"You are changing orientation...",Toast.LENGTH_SHORT).show();


How to set Sqlite3 to be case insensitive when string comparing?

If the column is of type char then you need to append the value you are querying with spaces, please refer to this question here . This in addition to using COLLATE NOCASE or one of the other solutions (upper(), etc).

Reset/remove CSS styles for element only

Let me answer this question thoroughly, because it's been a source of pain for me for several years and very few people really understand the problem and why it's important for it to be solved. If I were at all responsible for the CSS spec I'd be embarrassed, frankly, for having not addressed this in the last decade.

The Problem

You need to insert markup into an HTML document, and it needs to look a specific way. Furthermore, you do not own this document, so you cannot change existing style rules. You have no idea what the style sheets could be, or what they may change to.

Use cases for this are when you are providing a displayable component for unknown 3rd party websites to use. Examples of this would be:

  1. An ad tag
  2. Building a browser extension that inserts content
  3. Any type of widget

Simplest Fix

Put everything in an iframe. This has it's own set of limitations:

  1. Cross Domain limitations: Your content will not have access to the original document at all. You cannot overlay content, modify the DOM, etc.
  2. Display Limitations: Your content is locked inside of a rectangle.

If your content can fit into a box, you can get around problem #1 by having your content write an iframe and explicitly set the content, thus skirting around the issue, since the iframe and document will share the same domain.

CSS Solution

I've search far and wide for the solution to this, but there are unfortunately none. The best you can do is explicitly override all possible properties that can be overridden, and override them to what you think their default value should be.

Even when you override, there is no way to ensure a more targeted CSS rule won't override yours. The best you can do here is to have your override rules target as specifically as possible and hope the parent document doesn't accidentally best it: use an obscure or random ID on your content's parent element, and use !important on all property value definitions.

PHP combine two associative arrays into one array

        $array = array(
            22 => true,
            25 => true,
            34 => true,
            35 => true,

            array_replace($array, [
                22 => true,
                42 => true,

            array_merge($array, [
                22 => true,
                42 => true,

If it is numeric but not sequential associative array, you need to use array_replace

jQuery pass more parameters into callback

For me, and other newbies who has just contacted with Javascript,
I think that the Closeure Solution is a little kind of too confusing.

While I found that, you can easilly pass as many parameters as you want to every ajax callback using jquery.

Here are two easier solutions.

First one, which @zeroasterisk has mentioned above, example:

var $items = $('.some_class');
$.each($items, function(key, item){
    var url = 'http://request_with_params' + $(item).html();
        selfDom     : $(item),
        selfData    : 'here is my self defined data',

        url         : url,
        dataType    : 'json',
        success     : function(data, code, jqXHR){
            // in $.ajax callbacks, 
            // [this] keyword references to the options you gived to $.ajax
            // if you had not specified the context of $.ajax callbacks.
            // see context
            var $item = this.selfDom;
            var selfdata = this.selfData;
            $item.html( selfdata );

Second one, pass self-defined-datas by adding them into the XHR object which exists in the whole ajax-request-response life span.

var $items = $('.some_class');
$.each($items, function(key, item){
    var url = 'http://request_with_params' + $(item).html();
        url         : url,
        dataType    : 'json',
        beforeSend  : function(XHR) {
            // ??????,???? jquery??????? XHR
            XHR.selfDom = $(item);
            XHR.selfData = 'here is my self defined data';
        success     : function(data, code, jqXHR){
            // jqXHR is a superset of the browser's native XHR object
            var $item = jqXHR.selfDom;
            var selfdata = jqXHR.selfData;
            $item.html( selfdata );

As you can see these two solutions has a drawback that : you need write a little more code every time than just write:

$.get/post (url, data, successHandler);

Read more about $.ajax :

Problems with Android Fragment back stack

After @Arvis reply i decided to dig even deeper and I've written a tech article about this here:

For the lazy developers around. My solution consists in always adding the transactions to the backstack and perform an extra FragmentManager.popBackStackImmediate() when needed (automatically).

The code is very few lines of code and, in my example, I wanted to skip from C to A without jumping back to "B" if the user didn't went deeper in the backstack (ex from C navigates to D).

Hence the code attached would work as follow A -> B -> C (back) -> A & A -> B -> C -> D (back) -> C (back) -> B (back) -> A


fm.beginTransaction().replace(, new CFragment()).commit()

were issued from "B" to "C" as in the question.

Ok,Ok here is the code :)

public static void performNoBackStackTransaction(FragmentManager fragmentManager, String tag, Fragment fragment) {
  final int newBackStackLength = fragmentManager.getBackStackEntryCount() +1;

      .replace(, fragment, tag)

  fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
    public void onBackStackChanged() {
      int nowCount = fragmentManager.getBackStackEntryCount();
      if (newBackStackLength != nowCount) {
        // we don't really care if going back or forward. we already performed the logic here.

        if ( newBackStackLength > nowCount ) { // user pressed back

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

I was having issue with connecting to MS SQL 2005 using Windows Authentication. I was able to solve the issue with help from this and other forums. Here is what I did:

  1. Install the JTDS driver
  2. Do not use the "domain= " property in the jdbc:jtds:://[:][/][;=[;...]] string
  3. Install the ntlmauth.dll in c:\windows\system32 directory (registration of the dll was not required) on the web server machine.
  4. Change the logon identity for the Apache Tomcat service to a domain User with access to the SQL database server (it was not necessary for the user to have access to the dbo.master).

My environment: Windows XP clinet hosting Apache Tomcat 6 with MS SQL 2005 backend on Windows 2003

How to use a keypress event in AngularJS?


<textarea id="messageTxt" 
    placeholder="Escriba su mensaje" 


$scope.keyPressed = function (keyEvent) {
    if (keyEvent.keyCode == 13) {
        alert('presiono enter');
        console.log('presiono enter');

How can I convert string date to NSDate?

To add String within Date Format in Swift, I did this

 var dataFormatter:NSDateFormatter = NSDateFormatter()
                dataFormatter.dateFormat = "dd-MMMM 'at' HH:mm a"

cell.timeStamplbl.text = dataFormatter.stringFromDate(object.createdAt)

Oracle listener not running and won't start

I solved it by updating listener.ora file inside oracle directory oraclexe\app\oracle\product\11.2.0\server\network\ADMIN.

Why did it happen to me was because I changed my system name but inside listener.ora there was old name for HOST.

This might be one of the reasons... for those who still face such issue might think of this possibility as well.

Can my enums have friendly names?

They follow the same naming rules as variable names. Therefore they should not contain spaces.

Also what you are suggesting would be very bad practice anyway.

Static variables in C++

Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.

When static variable is declared in a header file is its scope limited to .h file or across all units.

There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.

As such, a static variable declared in a header file is like a static variable in each individual source file.

Since declaring a variable static this way means internal linkage, every translation unit #includeing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.

I would like to know what is the difference between static variables in a header file vs declared in a class.

In a class declaration, static means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to the static (or "class") variable, it's the same value for all objects. You could think of it as a "class global".

Also generally static variable is initialized in .cpp file when declared in a class right ?

Yes, one (and only one) translation unit must initialize the class variable.

So that does mean static variable scope is limited to 2 compilation units ?

As I said:

  • A header is not a compilation unit,
  • static means completely different things depending on context.

Global static limits scope to the translation unit. Class static means global to all instances.

I hope this helps.

PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use static in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )

Best way to determine user's locale within browser

There's a difference between the user's preferred languages and the system/browser locale.

A user can configure preferred languages in the browser, and these will be used for navigator.language(s), and used when requesting resources from a server, to request content according to a list of language priorities.

However, the browser locale will decide how to render number, date, time and currency. This setting is likely the highest ranking language, but there is no guarantee. On Mac and Linux, the locale is decided by the system regardless of the user language preferences. On Windows is can be elected among the languages in the preferred list on Chrome.

By using Intl (, developers can override/set the locale to use to render these things, but there are elements that cannot be overridden, such as the <input type="date"> format.

To properly extract this language, the only way I've found is:

(new Intl.NumberFormat()).resolvedOptions().locale

(Intl.NumberFormat().resolvedOptions().locale also seems to work)

This will create a new NumberFormat instance for the default locale and then reading back the locale of those resolved options.

OperationalError, no such column. Django

I see we have the same problem here, I have the same error. I want to write this for the future user who will experience the same error. After making changes to your class Snippet model like @Burhan Khalid said, you must migrate tables:

python makemigrations snippets
python migrate

And that should resolve the error. Enjoy.

PHP __get and __set magic methods

I'd recommend to use an array for storing all values via __set().

class foo {

    protected $values = array();

    public function __get( $key )
        return $this->values[ $key ];

    public function __set( $key, $value )
        $this->values[ $key ] = $value;


This way you make sure, that you can't access the variables in another way (note that $values is protected), to avoid collisions.

How to show android checkbox at right side?

I think it's too late to answer this question, but actually there is a way to achieve your goal. You just need to add the following line to your checkbox:


You can use your customized drawable for checkbox as well.

And for a radioButton:


And if you want to do it programmatically:

Define a layout and name it RightCheckBox and copy the following lines :

<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android=""

and when you need to add it programmatically you just need to inflate it to a CheckBox and add it to the root view.

CheckBox cb = (CheckBox)((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.check_right_checkbox,null);

Should I write script in the body or the head of the html?

The problem with writing scripts at the head of a page is blocking. The browser must stop processing the page until the script is download, parsed and executed. The reason for this is pretty clear, these scripts might insert more into the page changing the result of the rendering, they also may remove things that dont need to be rendered, etc.

Some of the more modern browsers violate this rule by not blocking on the downloading the scripts (ie8 was the first) but overall the download isn't the majority of the time spent blocking.

Check out Even Faster Websites, I just finished reading it and it goes over all of the fast ways to get scripts onto a page, Including putting scripts at the bottom of the page to allow rendering to complete (better UX).

Reload .profile in bash shell script (in unix)?

Try this:

source .bash_profile

How to do constructor chaining in C#

This is best illustrated with an example. Imaging we have a class Person

public Person(string name) : this(name, string.Empty)

public Person(string name, string address) : this(name, address, string.Empty)

public Person(string name, string address, string postcode)
    this.Name = name;
    this.Address = address;
    this.Postcode = postcode;

So here we have a constructor which sets some properties, and uses constructor chaining to allow you to create the object with just a name, or just a name and address. If you create an instance with just a name this will send a default value, string.Empty through to the name and address, which then sends a default value for Postcode through to the final constructor.

In doing so you're reducing the amount of code you've written. Only one constructor actually has code in it, you're not repeating yourself, so, for example, if you change Name from a property to an internal field you need only change one constructor - if you'd set that property in all three constructors that would be three places to change it.

How to check if a date is greater than another in Java?

You can use Date.before() or Date.after() or Date.equals() for date comparison.

Taken from here:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {

    public static void main( String[] args )
        compareDates("2017-01-13 00:00:00", "2017-01-14 00:00:00");// output will be Date1 is before Date2
        compareDates("2017-01-13 00:00:00", "2017-01-12 00:00:00");//output will be Date1 is after Date2
        compareDates("2017-01-13 00:00:00", "2017-01-13 10:20:30");//output will be Date1 is before Date2 because date2 is ahead of date 1 by 10:20:30 hours
        compareDates("2017-01-13 00:00:00", "2017-01-13 00:00:00");//output will be Date1 is equal Date2 because both date and time are equal

    public static void compareDates(String d1,String d2)
            // If you already have date objects then skip 1

            // Create 2 dates starts
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(d2);


            // Create 2 dates ends

            // Date object is having 3 methods namely after,before and equals for comparing
            // after() will return true if and only if date1 is after date 2
                System.out.println("Date1 is after Date2");
            // before() will return true if and only if date1 is before date2
                System.out.println("Date1 is before Date2");

            //equals() returns true if both the dates are equal
                System.out.println("Date1 is equal Date2");

        catch(ParseException ex){

    public static void compareDates(Date date1,Date date2)
        // if you already have date objects then skip 1


        //date object is having 3 methods namely after,before and equals for comparing
        //after() will return true if and only if date1 is after date 2
            System.out.println("Date1 is after Date2");

        //before() will return true if and only if date1 is before date2
            System.out.println("Date1 is before Date2");

        //equals() returns true if both the dates are equal
            System.out.println("Date1 is equal Date2");


Base64 String throwing invalid character error

If removing \0 from the end of string is impossible, you can add your own character for each string you encode, and remove it on decode.

Java reflection: how to get field value from an object, not knowing its class

I strongly recommend using Java generics to specify what type of object is in that List, ie. List<Car>. If you have Cars and Trucks you can use a common superclass/interface like this List<Vehicle>.

However, you can use Spring's ReflectionUtils to make fields accessible, even if they are private like the below runnable example:

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

list.add("some value");

for(Object obj : list)
    Class<?> clazz = obj.getClass();

    Field field = org.springframework.util.ReflectionUtils.findField(clazz, "value");

    System.out.println("value=" + field.get(obj));

Running this has an output of:


Simulate low network connectivity for Android

  1. Open terminal inAndroid Studio and Go to ../../Android/sdk/tools. 'emulator' executable should be available here.

  2. Run ./emulator -netdelay "delay_in_millis" -avd "emulator_device_name"

    Ex: ./emulator -netdelay 60000 -avd Nexus_5_API_21

  3. Now build your app and install it in emulator.

  4. Run your scenario in app.

Make sure you have your code changes in app that sets timeout to your request and handles that.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

When I ran into this error the fix was simple. I was simply missing a setter for a property. Make sure you define matching getters / setters for all your properties.

.htaccess rewrite to redirect root URL to subdirectory

Most of the above solutions are correct but they are all missing the transparency of the redirection.

In my case, when visiting I wanted to get redirected to the subdirectory /store but without updating the URL to (all I want is to get the page code form that directory). If that is your case the solution below works perfectly.

RewriteEngine on
RewriteCond %{HTTP_HOST} example\.com [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ /store/$1 [L]


Can we create an instance of an interface in Java?

Short answer...yes. You can use an anonymous class when you initialize a variable. Take a look at this question: Anonymous vs named inner classes? - best practices?

How to restore to a different database in sql server?

If no database exists I use the following code:

ALTER PROCEDURE [dbo].[RestoreBackupToNewDB]    
         @pathToBackup  varchar(500),--where to take backup from
         @pathToRestoreFolder  varchar(500), -- where to put the restored db files 
         @newDBName varchar(100)

            SET NOCOUNT ON
            DECLARE @fileListTable TABLE (
            [LogicalName]           NVARCHAR(128),
            [PhysicalName]          NVARCHAR(260),
            [Type]                  CHAR(1),
            [FileGroupName]         NVARCHAR(128),
            [Size]                  NUMERIC(20,0),
            [MaxSize]               NUMERIC(20,0),
            [FileID]                BIGINT,
            [CreateLSN]             NUMERIC(25,0),
            [DropLSN]               NUMERIC(25,0),
            [UniqueID]              UNIQUEIDENTIFIER,
            [ReadOnlyLSN]           NUMERIC(25,0),
            [ReadWriteLSN]          NUMERIC(25,0),
            [BackupSizeInBytes]     BIGINT,
            [SourceBlockSize]       INT,
            [FileGroupID]           INT,
            [LogGroupGUID]          UNIQUEIDENTIFIER,
            [DifferentialBaseLSN]   NUMERIC(25,0),
            [DifferentialBaseGUID]  UNIQUEIDENTIFIER,
            [IsReadOnly]            BIT,
            [IsPresent]             BIT,
            [TDEThumbprint]         VARBINARY(32) -- remove this column if using SQL 2005
            INSERT INTO @fileListTable EXEC('RESTORE FILELISTONLY FROM DISK ='''+ @pathToBackup+'''')
            DECLARE @restoreDatabaseFilePath NVARCHAR(500)
            DECLARE @restoreLogFilePath NVARCHAR(500)
            DECLARE @databaseLogicName NVARCHAR(500)
            DECLARE @logLogicName NVARCHAR(500)
            DECLARE @pathSalt uniqueidentifier = NEWID()

            SET @databaseLogicName = (SELECT LogicalName FROM @fileListTable WHERE [Type]='D') 
            SET @logLogicName = (SELECT LogicalName FROM @fileListTable WHERE [Type]='L')           
            SET @restoreDatabaseFilePath= @pathToRestoreFolder + @databaseLogicName + convert(nvarchar(50), @pathSalt) + '.mdf'
            SET @restoreLogFilePath= @pathToRestoreFolder + @logLogicName + convert(nvarchar(50), @pathSalt) + '.ldf'

            RESTORE DATABASE @newDBName FROM DISK=@pathToBackup     
               MOVE @databaseLogicName TO @restoreDatabaseFilePath,
               MOVE @logLogicName TO @restoreLogFilePath

            SET NOCOUNT OFF

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

I had almost the same example as you in this notebook where I wanted to illustrate the usage of an adjacent module's function in a DRY manner.

My solution was to tell Python of that additional module import path by adding a snippet like this one to the notebook:

import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:

This allows you to import the desired function from the module hierarchy:

from project1.lib.module import function
# use the function normally

Note that it is necessary to add empty files to project1/ and lib/ folders if you don't have them already.

How to do a for loop in windows command line?

The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.

For your purpose, you probably want something like:

FOR %i IN (*.ext) DO my-function %i

Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).

The (*.ext) part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:

FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i

To perform an operation in a different directory.

There are scores of options for the filespec and FOR in general. See


from the command prompt for more information.

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Try to import


instead of


How can I backup a remote SQL Server database to a local drive?

I could do that once...TO do this you have to have a share opened on the remote server. then you can directly place the backup on the share itself, than the default location...

Usually the admin takes the backup and shares it with us in some shared folder. I tried if that will work if i place the backup there. It worked.

jQuery change method on input type="file"

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). Refer:

$('#imageFile').on("change", function(){ uploadFile(); });

How to hide Table Row Overflow?

wrap the table in a div with class="container"

div.container {
    width: 100%;
    overflow-x: auto;


#table_id tr td {


overflow effect

HTML anchor link - href and onclick both?

<a href="#Foo" onclick="return runMyFunction();">Do it!</a>


function runMyFunction() {
  return true;

This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

How can I get the external SD card path for Android 4.0+?

 String path = Environment.getExternalStorageDirectory()
                        + File.separator + Environment.DIRECTORY_PICTURES;
                File dir = new File(path);

How to insert a data table into SQL Server database table?

    //best way to deal with this is sqlbulkcopy 
    //but if you dont like it you can do it like this
    //read current sql table in an adapter
    //add rows of datatable , I have mentioned a simple way of it
    //and finally updating changes

    Dim cnn As New SqlConnection("connection string")        
    Dim cmd As New SqlCommand("select * from  sql_server_table", cnn)
    Dim da As New SqlDataAdapter(cmd)       
    Dim ds As New DataSet()
    da.Fill(ds, "sql_server_table")
    Dim cb As New SqlCommandBuilder(da)        

    //for each datatable row
    ds.Tables("sql_server_table").Rows.Add(COl1, COl2)

    da.Update(ds, "sql_server_table")

Expand a random range from 1–5 to 1–7

solution in php

function random_5(){
    return rand(1,5);

function random_7(){
 $total = 0;

        $total += random_5();

    return ($total%7)+1; 

echo random_7();

Reset ID autoincrement ? phpmyadmin

I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.

Multiple select in Visual Studio?

In the Visual Studio Shift+Alt+. / Shift+Alt+,

  • Shift+Alt+. - match caret;
  • Shift+Alt+, - remove previous caret;

Same function as on VSCode Ctrl+D.

Much more setting Tool - Options - Environment - keyboard. Next in the Show commands containing enter Edit..

Also, can use keyboard schema Visual Studio Code. Available for Visual Studio 2017

For conclusion, nice link Visual Studio All keyboard shortcuts

How to uninstall a package installed with pip install --user

The answer is Not possible yet. You have to remove it manually.

How can JavaScript save to a local file?

So, your real question is: "How can JavaScript save to a local file?"

Take a look at

They save their HTML page locally after you have "changed" it internally.

[ UPDATE 2016.01.31 ]

TiddlyWiki original version saved directly. It was quite nice, and saved to a configurable backup directory with the timestamp as part of the backup filename.

TiddlyWiki current version just downloads it as any file download. You need to do your own backup management. :(


The trick is, you have to open the page as file:// not as http:// to be able to save locally.

The security on your browser will not let you save to _someone_else's_ local system, only to your own, and even then it isn't trivial.


what is the size of an enum type data in C++?

The size is four bytes because the enum is stored as an int. With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.

0 0 0 0  January
0 0 0 1  February
0 0 1 0  March
0 0 1 1  April
0 1 0 0  May
0 1 0 1  June
0 1 1 0  July
0 1 1 1  August
1 0 0 0  September
1 0 0 1  October
1 0 1 0  November
1 0 1 1  December
1 1 0 0  ** unused **
1 1 0 1  ** unused **
1 1 1 0  ** unused **
1 1 1 1  ** unused **

Without enums, you might be tempted to use raw integers to represent the months. That would work and be efficient, but it would make your code hard to read. With enums, you get efficient storage and readability.

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

If I were explaining this to someone I'd say we'll get to it later for now you need to know that the way to run your program is to use :

public static void main(String[] args) {

Assuming he/she knows what an array is, I'd say the args is an argument array and you can show some cool examples.

Then after you've gone a bit about Java/JVM and that stuff, you'd get to modifiers eventually to static and public as well.

Then you can spend some time talking about meaning of these IMHO.

You could mention other "cool" stuff such as varargs that you can use this in later versions of Java.

public static void main(String ...args) {

Xpath for href element

Best way to locate anchor elements is to use link=Re-Call:"link=Re-Call");

It will work..

mongod command not recognized when trying to connect to a mongodb server

For add environment variable please add \ after bin like below

C:\Program Files\MongoDB\Server\3.2\bin\

Then try below code in command prompt to run mongo server from parent folder of data folder.

mongod -dbpath ./data

For my case I am unable to run mongo from command prompt(normal mode). You should run as administrator. It also works on git bash.

Returning pointer from a function

To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.

    void main(void){
        int* test;
        test = tester();
    int* tester(void){
        int *retMe;
        retMe = new int;//<----Here retMe is getting malloc for integer type
        *retMe = 12;<---- Initializes retMe... Note * dereferences retMe 
    return retMe;

Convert hex color value ( #ffffff ) to integer value

I was facing the same problem. This way I was able to solved it. As CQM said, using Color.parseColor() is a good solution to this issue.

Here is the code I used:

this.Button_C.setTextColor(Color.parseColor(prefs.getString("color_prefs", String.valueOf(;

In this case my target was to change the Button's text color (Button_C) when I change the color selection from my Preferences (color_prefs).

How can I check if the current date/time is past a set date/time?


$curDateTime = date("Y-m-d H:i:s");
$myDate = date("Y-m-d H:i:s", strtotime("2018-06-26 16:15:33"));
if($myDate < $curDateTime){
    echo "active";exit;
    echo "inactive";exit;

Is it possible to override / remove background: none!important with jQuery?

div { background: none !important }
div { background: red; }

Is transparent.

div { background: none !important }
div { background: red !important; }

Is red.

An !important can override another !important.

If you can't edit the CSS file you can still add another one, or a style tag in the head tag.

How to create an AVD for Android 4.0

This site Android Create AVD shows you how to install the latest version of the Android SDK and AVD version 4 in Eclipse with video and screenshots if you're still stuck?

How to create a drop-down list?

Spinner xml:

      android:layout_height="match_parent" />


public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    private Spinner spinner;
    private static final String[] paths = {"item 1", "item 2", "item 3"};

    protected void onCreate(Bundle savedInstanceState){

        spinner = (Spinner)findViewById(;
        ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,



    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

        switch (position) {
            case 0:
                // Whatever you want to happen when the first item gets selected
            case 1:
                // Whatever you want to happen when the second item gets selected
            case 2:
                // Whatever you want to happen when the thrid item gets selected


    public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub


Validate email with a regex in jQuery

You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:

var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i

  alert('not a valid e-mail address');

How to get max value of a column using Entity Framework?

Your column is nullable

int maxAge = context.Persons.Select(p => p.Age).Max() ?? 0;

Your column is non-nullable

int maxAge = context.Persons.Select(p => p.Age).Cast<int?>().Max() ?? 0;

In both cases, you can use the second code. If you use DefaultIfEmpty, you will do a bigger query on your server. For people who are interested, here are the EF6 equivalent:

Query without DefaultIfEmpty

    [GroupBy1].[A1] AS [C1]
        MAX([Extent1].[Age]) AS [A1]
        FROM [dbo].[Persons] AS [Extent1]
    )  AS [GroupBy1]

Query with DefaultIfEmpty

    [GroupBy1].[A1] AS [C1]
        MAX([Join1].[A1]) AS [A1]
        FROM ( SELECT 
            CASE WHEN ([Project1].[C1] IS NULL) THEN 0 ELSE [Project1].[Age] END AS [A1]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable1]
                [Extent1].[Age] AS [Age], 
                cast(1 as tinyint) AS [C1]
                FROM [dbo].[Persons] AS [Extent1]) AS [Project1] ON 1 = 1
        )  AS [Join1]
    )  AS [GroupBy1]

Passing base64 encoded strings in URL

@joeshmo Or instead of writing a helper function, you could just urlencode the base64 encoded string. This would do the exact same thing as your helper function, but without the need of two extra functions.

$str = 'Some String';

$encoded = urlencode( base64_encode( $str ) );
$decoded = base64_decode( urldecode( $encoded ) );

Python "string_escape" vs "unicode_escape"

According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.

They are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.

3-dimensional array in numpy

You have a truncated array representation. Let's look at a full example:

>>> a = np.zeros((2, 3, 4))
>>> a
array([[[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]]])

Arrays in NumPy are printed as the word array followed by structure, similar to embedded Python lists. Let's create a similar list:

>>> l = [[[ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.]],

          [[ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.]]]

>>> l
[[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], 
 [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]

The first level of this compound list l has exactly 2 elements, just as the first dimension of the array a (# of rows). Each of these elements is itself a list with 3 elements, which is equal to the second dimension of a (# of columns). Finally, the most nested lists have 4 elements each, same as the third dimension of a (depth/# of colors).

So you've got exactly the same structure (in terms of dimensions) as in Matlab, just printed in another way.

Some caveats:

  1. Matlab stores data column by column ("Fortran order"), while NumPy by default stores them row by row ("C order"). This doesn't affect indexing, but may affect performance. For example, in Matlab efficient loop will be over columns (e.g. for n = 1:10 a(:, n) end), while in NumPy it's preferable to iterate over rows (e.g. for n in range(10): a[n, :] -- note n in the first position, not the last).

  2. If you work with colored images in OpenCV, remember that:

    2.1. It stores images in BGR format and not RGB, like most Python libraries do.

    2.2. Most functions work on image coordinates (x, y), which are opposite to matrix coordinates (i, j).

How to set RelativeLayout layout params in code not in xml?

I hope the below code will help. It will create an EditText and a Log In button. Both placed relatively. All done in

package com.example.atul.allison;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.widget.EditText;
import android.content.res.Resources;
import android.util.TypedValue;     
    public class MainActivity extends AppCompatActivity {

        protected void onCreate(Bundle savedInstanceState) {
            RelativeLayout atulsLayout = new RelativeLayout(this);

            Button redButton = new Button(this);
            redButton.setText("Log In");

            //Username input
            EditText username =  new EditText(this);


            RelativeLayout.LayoutParams buttonDetails= new RelativeLayout.LayoutParams(

            RelativeLayout.LayoutParams usernameDetails= new RelativeLayout.LayoutParams(

            //give rules to position widgets


            Resources r = getResources();
            int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200,r.getDisplayMetrics());

            //Add widget to layout(button is now a child of layout)

            //Set these activities content/display to this view

Javascript How to define multiple variables on a single line?

Here is the new ES6 method of declaration multiple variables in one line:

const person = { name: 'Prince', age: 22, id: 1 };_x000D_
let {name, age, id} = person;_x000D_

* Your variable name and object index need be same

Is there a JavaScript / jQuery DOM change listener?

For a long time, DOM3 mutation events were the best available solution, but they have been deprecated for performance reasons. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver (or as the vendor-prefixed WebKitMutationObserver in old versions of Chrome):

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true

This example listens for DOM changes on document and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:


  • Set to true if mutations to target's children are to be observed.


  • Set to true if mutations to target's attributes are to be observed.


  • Set to true if mutations to target's data are to be observed.


  • Set to true if mutations to not just target, but also target's descendants are to be observed.


  • Set to true if attributes is set to true and target's attribute value before the mutation needs to be recorded.


  • Set to true if characterData is set to true and target's data before the mutation needs to be recorded.


  • Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.

(This list is current as of April 2014; you may check the specification for any changes.)

How to draw border on just one side of a linear layout?

You can use this to get border on one side

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="">
    <shape android:shape="rectangle">
        <solid android:color="#FF0000" />
<item android:left="5dp">
    <shape android:shape="rectangle">
        <solid android:color="#000000" />


As many including me wanted to have a one side border with transparent background, I have implemented a BorderDrawable which could give me borders with different size and color in the same way as we use css. But this could not be used via xml. For supporting XML, I have added a BorderFrameLayout in which your layout can be wrapped.

See my github for the complete source.

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.

If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
setInterval(fn60sec, 60*1000);

How to show hidden divs on mouseover?

Option 1 Each div is specifically identified, so any other div (without the specific IDs) on the page will not obey the :hover pseudo-class.

<style type="text/css">
  #div1, #div2, #div3{  
  #div1:hover, #div2:hover, #div3:hover{  

Option 2 All divs on the page, regardless of IDs, have the hover effect.

<style type="text/css">

source of historical stock data

I'd crawl (for the quotes) - or

Both these will return html pages for most exchanges around the world, including historical. Then, it's just a matter of parsing the HTML to extract what you need.

I've done this in the past, with great success. Alternatively, if you don't mind using Perl - there are several modules on CPAN that have done this work for you - i.e. extracting quotes from Google/Yahoo.

For more, see Quote History

Call removeView() on the child's parent first

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

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

Losing Session State

I was only losing the session which was not a string or integer but a datarow. Putting the data in a serializable object and saving that into the session worked for me.

Installing R with Homebrew

I used this tutorial to install R on my mac, and it had me install xquartz and a fortran complier (gfortran) as well.

My suggestion would be to brew untap homebrew/science and then brew tap homebrew/science and try again, also, make sure you don't have any errors when you run brew doctor

Hope this helps

Android - Get value from HashMap

 Iterator iterator = meMap.keySet().iterator();
                while(iterator.hasNext() ){
                  //get key
                    String key=(String);
                    //toast value


Bundler: Command not found

Make sure you do rbenv rehash when installing different rubies

Change DataGrid cell colour based on values

If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.


public class ValueToBrushConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        int input;
            DataGridCell dgc = (DataGridCell)value;
            System.Data.DataRowView rowView = (System.Data.DataRowView)dgc.DataContext;
            input = (int)rowView.Row.ItemArray[dgc.Column.DisplayIndex];
        catch (InvalidCastException e)
            return DependencyProperty.UnsetValue;
        switch (input)
            case 1: return Brushes.Red;
            case 2: return Brushes.White;
            case 3: return Brushes.Blue;
            default: return DependencyProperty.UnsetValue;

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        throw new NotSupportedException();


    <conv:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
    <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
<DataGrid x:Name="dataGrid" CellStyle="{StaticResource CellStyle}">

Delegation: EventEmitter or Observable in Angular

I found out another solution for this case without using Reactivex neither services. I actually love the rxjx API however I think it goes best when resolving an async and/or complex function. Using It in that way, Its pretty exceeded to me.

What I think you are looking for is for a broadcast. Just that. And I found out this solution:

  <app-nav (selectedTab)="onSelectedTab($event)"></app-nav>
       // This component bellow wants to know when a tab is selected
       // broadcast here is a property of app component
  <app-interested [broadcast]="broadcast"></app-interested>

 @Component class App {
   broadcast: EventEmitter<tab>;

   constructor() {
     this.broadcast = new EventEmitter<tab>();

   onSelectedTab(tab) {

 @Component class AppInterestedComponent implements OnInit {
   broadcast: EventEmitter<Tab>();


   ngOnInit() {
     this.broadcast.subscribe((tab) => this.doSomethingWhenTab(tab))

This is a full working example:

How do I use the lines of a file as arguments of a command?

As already mentioned, you can use the backticks or $(cat filename).

What was not mentioned, and I think is important to note, is that you must remember that the shell will break apart the contents of that file according to whitespace, giving each "word" it finds to your command as an argument. And while you may be able to enclose a command-line argument in quotes so that it can contain whitespace, escape sequences, etc., reading from the file will not do the same thing. For example, if your file contains:

a "b c" d

the arguments you will get are:


If you want to pull each line as an argument, use the while/read/do construct:

while read i ; do command_name $i ; done < filename

Passing html values into javascript functions

Try: if(parseInt(order)>0){....

The difference between fork(), vfork(), exec() and clone()

  • vfork() is an obsolete optimization. Before good memory management, fork() made a full copy of the parent's memory, so it was pretty expensive. since in many cases a fork() was followed by exec(), which discards the current memory map and creates a new one, it was a needless expense. Nowadays, fork() doesn't copy the memory; it's simply set as "copy on write", so fork()+exec() is just as efficient as vfork()+exec().

  • clone() is the syscall used by fork(). with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.

How to display a "busy" indicator with jQuery?

I did it in my project ,

make a div with back ground url as gif , which is nothing but animation gif

<div class="busyindicatorClass"> </div>

background-url///give animation here

in your ajax call , add this class to the div and in ajax success remove the class.

it will do the trick thatsit.

let me know if you need antthing else , i can give you more details

in the ajax success remove the class

success: function(data) {
    remove class using jquery

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation:

This is all I know how to do though sorry.


import dpkt



for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:

    if ip.p==dpkt.ip.IP_PROTO_TCP: 

    if ip.p==dpkt.ip.IP_PROTO_UDP:

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter


Project on GitHub, documentation here

tmux status bar configuration

I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.

Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.

Easy way to get a test file into JUnit

If you want to load a test resource file as a string with just few lines of code and without any extra dependencies, this does the trick:

public String loadResourceAsString(String fileName) throws IOException {
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));
    String contents = scanner.useDelimiter("\\A").next();
    return contents;

"\\A" matches the start of input and there's only ever one. So this parses the entire file contents and returns it as a string. Best of all, it doesn't require any 3rd party libraries (like IOUTils).

Apache: Restrict access to specific source IP inside virtual host

For Apache 2.4, you would use the Require IP directive. So to only allow machines from the network (range -

<VirtualHost *:80>
    <Location />
      Require ip

And if you just want the localhost machine to have access, then there's a special Require local directive.

The local provider allows access to the server if any of the following conditions is true:

  • the client address matches
  • the client address is ::1
  • both the client and the server address of the connection are the same

This allows a convenient way to match connections that originate from the local host:

<VirtualHost *:80>
    <Location />
      Require local

How to list only top level directories in Python?

Filter the result using os.path.isdir() (and use os.path.join() to get the real path):

>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']

ValueError: math domain error

You are trying to do a logarithm of something that is not positive.

Logarithms figure out the base after being given a number and the power it was raised to. log(0) means that something raised to the power of 2 is 0. An exponent can never result in 0*, which means that log(0) has no answer, thus throwing the math domain error

*Note: 0^0 can result in 0, but can also result in 1 at the same time. This problem is heavily argued over.

What is the best way to auto-generate INSERT statements for a SQL Server table?

You can generate INSERT or MERGE statement with this simple and free application I wrote a few years ago:
Data Script Writer (Desktop Application for Windows)

enter image description here Also, I wrote a blog post about these tools recently and approach to leveraging SSDT for a deployment database with data. Find out more:
Script and deploy the data for database from SSDT project

Postgresql 9.2 pg_dump version mismatch

If you have docker installed you can do something like:

$ docker run postgres:9.2 pg_dump books > books.out

That will download the Docker container with Postgres 9.2 in it, run pg_dump inside of the container, and write the output.

navbar color in Twitter Bootstrap

I actually just overwrite anything I want to change in the site.css, you should load the site.css after bootstrap so it will overwrite the classes. What I have done now is just made my own classes with my own little bootstrap theme. Little things like this

.navbar-nav li a{
    color: #fff;
    font-size: 15px;
    margin-top: 9px;
.navbar-nav li a:hover{

    background-color: #18678E;
    height: 61px;

I also changed the likes of the validations errors the same way.

How can I scroll a div to be visible in ReactJS?

Just in case someone stumbles here, I did it this way

    const node = this.refs.trackerRef;
    node && node.scrollIntoView({block: "end", behavior: 'smooth'})
  componentDidUpdate() {
    const node = this.refs.trackerRef;
    node && node.scrollIntoView({block: "end", behavior: 'smooth'})

  render() {
    return (

        {, index) => {
          return (
            <Message key={index} msgObj={msg}
              {/*<p>some test text</p>*/}

        <div style={{height: '30px'}} id='#tracker' ref="trackerRef"></div>

scrollIntoView is native DOM feature link

It will always shows tracker div