Programs & Examples On #Ora 12541

ORA-12541: TNS no listener

Oracle client ORA-12541: TNS:no listener

Check out your TNS Names, this must not have spaces at the left side of the ALIAS

Best regards

What are the differences between Deferred, Promise and Future in JavaScript?

A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, state and promise), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).

If target is provided, deferred.promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.

If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return only the Promise object via deferred.promise() so other code can register callbacks or inspect the current state.

Simply we can say that a Promise represents a value that is not yet known where as a Deferred represents work that is not yet finished.

enter image description here

'MOD' is not a recognized built-in function name

If using JDBC driver you may use function escape sequence like this:

select {fn MOD(5, 2)}
#Result 1

select  mod(5, 2)
#SQL Error [195] [S00010]: 'mod' is not a recognized built-in function name.

Simple search MySQL database using php

Just with the above answer I hope it was the problem.

$_POST['search'] instead of $_post['search']

And again use LIKE '%$name%' instead of LIKE '%{$name}%'

Extract a part of the filepath (a directory) in Python

This is what I did to extract the piece of the directory:

for path in file_list:
  directories = path.rsplit('\\')
  line_replace_add_directory = line_replace+directories[2]

Thank you for your help.

HTML Form: Select-Option vs Datalist-Option

Think of it as the difference between a requirement and a suggestion. For the select element, the user is required to select one of the options you've given. For the datalist element, it is suggested that the user select one of the options you've given, but he can actually enter anything he wants in the input.

Edit 1: So which one you use depends upon your requirements. If the user must enter one of your choices, use the select element. If the use can enter whatever, use the datalist element.

Edit 2: Found this tidbit in the HTML Living Standard: "Each option element that is a descendant of the datalist element...represents a suggestion."

Grant Select on a view not base table when base table is in a different database

I tried this in one of my databases.

To get it to work, the user had to be added to the database housing the actual data. No rights were needed, just access.

Have you considered keeping the view in the database it references? Re usability and all if its benefits could follow.

Connection string using Windows Authentication

For connecting to a sql server database via Windows authentication basically needs which server you want to connect , what is your database name , Integrated Security info and provider name.

Basically this works:

<add name="MyConnectionString"
         connectionString="data source=ServerName;
   Initial Catalog=DatabaseName;Integrated Security=True;"
         providerName="System.Data.SqlClient" />

Setting Integrated Security field true means basically you want to reach database via Windows authentication, if you set this field false Windows authentication will not work.

It is also working different according which provider you are using.

  • SqlClient both Integrated Security=true; or IntegratedSecurity=SSPI; is working.

  • OleDb it is Integrated Security=SSPI;

  • Odbc it is Trusted_Connection=yes;
  • OracleClient it is Integrated Security=yes;

Integrated Security=true throws an exception when used with the OleDb provider.

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

Change Title of Javascript Alert

As others have said, you can't do that either using alert()or confirm().

You can, however, create an external HTML document containing your error message and an OK button, set its <title> element to whatever you want, then display it in a modal dialog box using showModalDialog().

When is assembly faster than C?

In my job, there are three reasons for me to know and use assembly. In order of importance:

  1. Debugging - I often get library code that has bugs or incomplete documentation. I figure out what it's doing by stepping in at the assembly level. I have to do this about once a week. I also use it as a tool to debug problems in which my eyes don't spot the idiomatic error in C/C++/C#. Looking at the assembly gets past that.

  2. Optimizing - the compiler does fairly well in optimizing, but I play in a different ballpark than most. I write image processing code that usually starts with code that looks like this:

    for (int y=0; y < imageHeight; y++) {
        for (int x=0; x < imageWidth; x++) {
           // do something

    the "do something part" typically happens on the order of several million times (ie, between 3 and 30). By scraping cycles in that "do something" phase, the performance gains are hugely magnified. I don't usually start there - I usually start by writing the code to work first, then do my best to refactor the C to be naturally better (better algorithm, less load in the loop etc). I usually need to read assembly to see what's going on and rarely need to write it. I do this maybe every two or three months.

  3. doing something the language won't let me. These include - getting the processor architecture and specific processor features, accessing flags not in the CPU (man, I really wish C gave you access to the carry flag), etc. I do this maybe once a year or two years.

Autoplay an audio with HTML5 embed tag while the player is invisible

For future reference to people who find this page later you can use:

<audio controls autoplay loop hidden>
<source src="kooche.mp3" type="audio/mpeg">
<p>If you can read this, your browser does not support the audio element.</p>

How to "properly" create a custom object in JavaScript?

var Person = function (lastname, age, job){ = name;
this.age = age;
this.job = job;
this.changeName = function(name){
this.lastname = name;
var myWorker = new Person('Adeola', 23, 'Web Developer');

console.log("New Worker" + myWorker.lastname);

get UTC timestamp in python with datetime

Naïve datetime versus aware datetime

Default datetime objects are said to be "naïve": they keep time information without the time zone information. Think about naïve datetime as a relative number (ie: +4) without a clear origin (in fact your origin will be common throughout your system boundary).

In contrast, think about aware datetime as absolute numbers (ie: 8) with a common origin for the whole world.

Without timezone information you cannot convert the "naive" datetime towards any non-naive time representation (where does +4 targets if we don't know from where to start ?). This is why you can't have a datetime.datetime.toutctimestamp() method. (cf:

To check if your datetime dt is naïve, check dt.tzinfo, if None, then it's naïve:        ## DANGER: returns naïve datetime pointing on local time
datetime(1970, 1, 1)  ## returns naïve datetime pointing on user given time

I have naïve datetimes, what can I do ?

You must make an assumption depending on your particular context: The question you must ask yourself is: was your datetime on UTC ? or was it local time ?

  • If you were using UTC (you are out of trouble):

    import calendar
    def dt2ts(dt):
        """Converts a datetime object to UTC timestamp
        naive datetime will be considered UTC.
        return calendar.timegm(dt.utctimetuple())
  • If you were NOT using UTC, welcome to hell.

    You have to make your datetime non-naïve prior to using the former function, by giving them back their intended timezone.

    You'll need the name of the timezone and the information about if DST was in effect when producing the target naïve datetime (the last info about DST is required for cornercases):

    import pytz     ## pip install pytz
    mytz = pytz.timezone('Europe/Amsterdam')             ## Set your timezone
    dt = mytz.normalize(mytz.localize(dt, is_dst=True))  ## Set is_dst accordingly

    Consequences of not providing is_dst:

    Not using is_dst will generate incorrect time (and UTC timestamp) if target datetime was produced while a backward DST was put in place (for instance changing DST time by removing one hour).

    Providing incorrect is_dst will of course generate incorrect time (and UTC timestamp) only on DST overlap or holes. And, when providing also incorrect time, occuring in "holes" (time that never existed due to forward shifting DST), is_dst will give an interpretation of how to consider this bogus time, and this is the only case where .normalize(..) will actually do something here, as it'll then translate it as an actual valid time (changing the datetime AND the DST object if required). Note that .normalize() is not required for having a correct UTC timestamp at the end, but is probably recommended if you dislike the idea of having bogus times in your variables, especially if you re-use this variable elsewhere.

    and AVOID USING THE FOLLOWING: (cf: Datetime Timezone conversion using pytz)

    dt = dt.replace(tzinfo=timezone('Europe/Amsterdam'))  ## BAD !!

    Why? because .replace() replaces blindly the tzinfo without taking into account the target time and will choose a bad DST object. Whereas .localize() uses the target time and your is_dst hint to select the right DST object.

OLD incorrect answer (thanks @J.F.Sebastien for bringing this up):

Hopefully, it is quite easy to guess the timezone (your local origin) when you create your naive datetime object as it is related to the system configuration that you would hopefully NOT change between the naive datetime object creation and the moment when you want to get the UTC timestamp. This trick can be used to give an imperfect question.

By using time.mktime we can create an utc_mktime:

def utc_mktime(utc_tuple):
    """Returns number of seconds elapsed since epoch

    Note that no timezone are taken into consideration.

    utc tuple must be: (year, month, day, hour, minute, second)


    if len(utc_tuple) == 6:
        utc_tuple += (0, 0, 0)
    return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0))

def datetime_to_timestamp(dt):
    """Converts a datetime object to UTC timestamp"""

    return int(utc_mktime(dt.timetuple()))

You must make sure that your datetime object is created on the same timezone than the one that has created your datetime.

This last solution is incorrect because it makes the assumption that the UTC offset from now is the same than the UTC offset from EPOCH. Which is not the case for a lot of timezones (in specific moment of the year for the Daylight Saving Time (DST) offsets).

Is there an equivalent for var_dump (PHP) in Javascript?

A lot of modern browsers support the following syntax:


Get first day of week in SQL Server

For the basic (the current week's Sunday)

select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) as date)

If previous week:

select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) -7 as date)

Internally, we built a function that does it but if you need quick and dirty, this will do it.

Autoreload of modules in IPython

For IPython version 3.1, 4.x, and 5.x

%load_ext autoreload
%autoreload 2

Then your module will be auto-reloaded by default. This is the doc:


``autoreload`` is an IPython extension that reloads modules
automatically before executing the line of code typed.

This makes for example the following workflow possible:

.. sourcecode:: ipython

   In [1]: %load_ext autoreload

   In [2]: %autoreload 2

   In [3]: from foo import some_function

   In [4]: some_function()
   Out[4]: 42

   In [5]: # open in an editor and change some_function to return 43

   In [6]: some_function()
   Out[6]: 43

The module was reloaded without reloading it explicitly, and the
object imported with ``from foo import ...`` was also updated.

There is a trick: when you forget all of the above when using ipython, just try:

import autoreload
# Then you get all the above

How to resolve git stash conflict without commit?

It seems that this may be the answer you're looking for, I haven't tried this personally yet, but it seems like it may do the trick. With this command GIT will try to apply the changes as they were before, without trying to add all of them for commit.

git stash apply --index

here is the full explanation:

Draw Circle using css alone

yup.. here's my code:

     width: 100px;
     height: 100px;
     border-radius: 50%;
     background-color: blue
<div class="circle">

Xcode 10: A valid provisioning profile for this executable was not found

In my case, Device date-time was set to a future date. Changing the date setting to "automatic" fixed the issue.

What's HTML character code 8203?

I have these characters show up in scripts where I do not desire them. I noticed because it ruins my HTML/CSS visual formatting : it makes a new text box.

Pretty sure a buggy editor is adding them... I suspect Komodo Edit for the Mac, in my case.

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

Sorting JSON by values

jQuery.fn.sort = function() {  
    return this.pushStack( [].sort.apply( this, arguments ), []);  

 function sortLastName(a,b){  
     if (a.l_name == b.l_name){
       return 0;
     return a.l_name> b.l_name ? 1 : -1;  
  function sortLastNameDesc(a,b){  
     return sortLastName(a,b) * -1;  
var people= [
"f_name": "john",
"l_name": "doe",
"sequence": "0",
"title" : "president",
"url" : "",
"color" : "333333",
"f_name": "michael",
"l_name": "goodyear",
"sequence": "0",
"title" : "general manager",
"url" : "",
"color" : "333333",


Remove folder and its contents from git/GitHub's history

The best and most accurate method I found was to download the bfg.jar file:

Then run the commands:

git clone --bare https://project/repository project-repository
cd project-repository
java -jar bfg.jar --delete-folders DIRECTORY_NAME
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --mirror https://project/new-repository

If you want to delete files then use the delete-files option instead:

java -jar bfg.jar --delete-files *.pyc

How to validate an e-mail address in swift?

Here is a method based on rangeOfString:

class func isValidEmail(testStr:String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
    let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
    let result = range != nil ? true : false
    return result

Note: updated TLD length.

Here is the definitive RegEx for email as per RFC 5322, note that this is best not used because it only checks the basic syntax of email addresses and does not check is the top level domain exists.

  |  "(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]
      |  \\[\x01-\x09\x0b\x0c\x0e-\x7f])*")
@ (?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
  |  \[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
          |  \\[\x01-\x09\x0b\x0c\x0e-\x7f])+)

See for more complete information on email RegExs.

Note that no escaping as required by a language such as Objective-C or Swift.

How to read user input into a variable in Bash?

Also you can try zenity !

user=$(zenity --entry --text 'Please enter the username:') || exit 1

Facebook Oauth Logout

I am having the same problem. I also login using oauth (I am using RubyOnRails), but for logout, I do it with JavaScript using a link like this:

<a href="/logout" onclick="FB.logout();">Logout</a> 

This first calls the onclick function and performs a logout on facebook, and then the normal /logout function of my site is called.

Though I would prefer a serverside solution as well, but at least it does what I want, it logs me out on both sites.

I am also quite new to the Facebook integration stuff and played around the first time with it, but my general feeling is that the documentation is pretty spread all over the place with lots of outdated stuff.

C++: Converting Hexadecimal to Decimal

Here is a solution using strings and converting it to decimal with ASCII tables:

#include <iostream>
#include <string>
#include "math.h"
using namespace std;
unsigned long hex2dec(string hex)
    unsigned long result = 0;
    for (int i=0; i<hex.length(); i++) {
        if (hex[i]>=48 && hex[i]<=57)
            result += (hex[i]-48)*pow(16,hex.length()-i-1);
        } else if (hex[i]>=65 && hex[i]<=70) {
            result += (hex[i]-55)*pow(16,hex.length( )-i-1);
        } else if (hex[i]>=97 && hex[i]<=102) {
            result += (hex[i]-87)*pow(16,hex.length()-i-1);
    return result;

int main(int argc, const char * argv[]) {
    string hex_str;
    cin >> hex_str;
    cout << hex2dec(hex_str) << endl;
    return 0;

Toggle Checkboxes on/off

A better approach and UX

$('.checkall').on('click', function() {
   var $checks  = $('checks');
   var $ckall = $(this);

    $.each($checks, function(){
        $(this).prop("checked", $ckall.prop('checked'));

$('checks').on('click', function(e){
   $('.checkall').prop('checked', false);

Split string to equal length substrings in Java

i use the following java 8 solution:

public static List<String> splitString(final String string, final int chunkSize) {
  final int numberOfChunks = (string.length() + chunkSize - 1) / chunkSize;
  return IntStream.range(0, numberOfChunks)
                  .mapToObj(index -> string.substring(index * chunkSize, Math.min((index + 1) * chunkSize, string.length())))

Java code To convert byte to Hexadecimal

Others have covered the general case. But if you have a byte array of a known form, for example a MAC address, then you can:

byte[] mac = { (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00 };

String str = String.format("%02X:%02X:%02X:%02X:%02X:%02X",
                           mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); 

What's the difference between 'r+' and 'a+' when open file in python?

Python opens files almost in the same way as in C:

  • r+ Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).

How to keep the console window open in Visual C++?

just add system("pause") at the end of the code before return 0 like this

#include <stdlib.h>

int main()
    //some code goes here
    return 0;

Check if a key exists inside a json object

Try this,



the JS Object thisSession should be like

amt: "10.00",
email: "[email protected]",
merchant_id: "sam",
mobileNo: "9874563210",
orderID: "123456",
passkey: "1234"

you can find the details here

How to set the value for Radio Buttons When edit?

<td><input type="radio" name="gender" value="Male" id="male" <? if($gender=='Male')
{?> checked="" <? }?>/>Male
<input type="radio" name="gender" value="Female" id="female" <? if($gender=='Female') {?> checked="" <?}?>/>Female<br/> </td>

Building and running app via Gradle and Android Studio is slower than via Eclipse

A trivial change (to a resoruce xml) still took 10 minutes. As @rivare says in his answer, a command line build is mutch faster (took this down to 15 seconds).
Here are some steps to at least make a trivial build fast from the command line for Windows.

  1. Go to your projects root (where the gradlew.bat is):

    cd c:\android\MaskActivity

  2. execute the build:

    gradlew assembleDebug

  3. uninstall the apk from the phone directly (drag it to uninstall).

  4. When the build is finished, kill the BIG java process using Windows Task Manager.

OR if you have unix tools on your Windows machine:


"pid" 's are shown:

kill -9 <pid>
  1. Now install your apk:

    adb -d install C:\Android\MaskActivity\app\build\outputs\apk\app-debug.apk

jQuery scroll to element

jQuery(document).ready(function($) {_x000D_
  $('a[href^="#"]').bind('click.smoothscroll',function (e) {_x000D_
    var target = this.hash,_x000D_
        $target = $(target);_x000D_
    $('html, body').stop().animate( {_x000D_
      'scrollTop': $target.offset().top-40_x000D_
    }, 900, 'swing', function () {_x000D_
      window.location.hash = target;_x000D_
    } );_x000D_
  } );_x000D_
} );
<script src=""></script>_x000D_
<ul role="tablist">_x000D_
  <li class="active" id="p1"><a href="#pane1" role="tab">Section 1</a></li>_x000D_
  <li id="p2"><a href="#pane2" role="tab">Section 2</a></li>_x000D_
  <li id="p3"><a href="#pane3" role="tab">Section 3</a></li>_x000D_
<div id="pane1"></div>_x000D_
<div id="pane2"></div>_x000D_
<div id="pane3"></div>

Inserting HTML elements with JavaScript

To my knowledge, which, to be fair, is fairly new and limited, the only potential issue with this technique is the fact that you are prevented from dynamically creating some table elements.

I use a form to templating by adding "template" elements to a hidden DIV and then using cloneNode(true) to create a clone and appending it as required. Bear in ind that you do need to ensure you re-assign id's as required to prevent duplication.

Can't find file executable in your configured search path for gnc gcc compiler

Just open your setting->compiler and click on the reset defaults and it will start work.

Random date in C#

Well, if you gonna present alternate optimization, we can also go for an iterator:

 static IEnumerable<DateTime> RandomDay()
    DateTime start = new DateTime(1995, 1, 1);
    Random gen = new Random();
    int range = ((TimeSpan)(DateTime.Today - start)).Days;
    while (true)
        yield return  start.AddDays(gen.Next(range));        

you could use it like this:

int i=0;
foreach(DateTime dt in RandomDay())
    if (++i == 10)

Convert text into number in MySQL query

SELECT *, CAST(SUBSTRING_INDEX(field, '-', -1) AS UNSIGNED) as num FROM tableName ORDER BY num;

How to check if user input is not an int value

Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
  ; // discard
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");


How to input a path with a white space?

I see Federico you've found solution by yourself. The problem was in two places. Assignations need proper quoting, in your case

SOME_PATH="/$COMPANY/someProject/some path"

is one of possible solutions.

But in shell those quotes are not stored in a memory, so when you want to use this variable, you need to quote it again, for example:


because if not, space will be expanded to command level, like this:

NEW_VAR=/YourCompany/someProject/some path

which is not what you want.

For more info you can check out my article about it

(Mac) -bash: __git_ps1: command not found

__git_ps1 for bash is now found in in /usr/local/etc/bash_completion.d on my brew installed git version

How to persist a property of type List<String> in JPA?

Use some JPA 2 implementation: it adds a @ElementCollection annotation, similar to the Hibernate one, that does exactly what you need. There's one example here.


As mentioned in the comments below, the correct JPA 2 implementation is


Map<Key, Value> collection;


Returning the product of a list

The fastest way I found was, using while:

mysetup = '''
import numpy as np
from find_intervals import return_intersections 

# code snippet whose execution time is to be measured
mycode = '''

x = [4,5,6,7,8,9,10]
prod = 1
i = 0
while True:
    prod = prod * x[i]
    i = i + 1
    if i == len(x):

# timeit statement for while:
print("using while : ",

# timeit statement for mul:
print("using mul : ",
    timeit.timeit('from functools import reduce;
    from operator import mul;
    c = reduce(mul, [4,5,6,7,8,9,10])'))

# timeit statement for mul:
print("using lambda : ",      
    timeit.timeit('from functools import reduce;
    from operator import mul;
    c = reduce(lambda x, y: x * y, [4,5,6,7,8,9,10])'))

and the timings are:

>>> using while : 0.8887967770060641

>>> using mul : 2.0838719510065857

>>> using lambda : 2.4227715369997895

Is there a JavaScript strcmp()?

localeCompare() is slow, so if you don't care about the "correct" ordering of non-English-character strings, try your original method or the cleaner-looking:

str1 < str2 ? -1 : +(str1 > str2)

This is an order of magnitude faster than localeCompare() on my machine.

The + ensures that the answer is always numeric rather than boolean.

What is the fastest way to send 100,000 HTTP requests in Python?

Threads are absolutely not the answer here. They will provide both process and kernel bottlenecks, as well as throughput limits that are not acceptable if the overall goal is "the fastest way".

A little bit of twisted and its asynchronous HTTP client would give you much better results.

How to open link in new tab on html?

You could do it like this:

<a href="" target="_blank" rel="noopener noreferrer">Open</a>

Originally was:

<a href=""></a>

Also look at the following url on MDN for more information about security and privacy:

which in turn has a link to a good article named Target="_blank" - the most underestimated vulnerability ever:

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>


<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;

These updates can be seen in this JSBin demo.

An error has occured. Please see log file - eclipse juno

In my case, error was due to Java 14 , which is not an LTS, downgraded it to java 8 and it worked.

What is the meaning of CTOR?

To expand a little more, there are two kinds of constructors: instance initializers (.ctor), type initializers (.cctor). Build the code below, and explore the IL code in ildasm.exe. You will notice that the static field 'b' will be initialized through .cctor() whereas the instance field will be initialized through .ctor()

internal sealed class CtorExplorer
   protected int a = 0;
   protected static int b = 0;

Capturing a form submit with jquery and .submit

$(document).ready(function () {_x000D_
  var form = $('#login_form')[0];_x000D_
  form.onsubmit = function(e){_x000D_
  var data = $("#login_form :input").serializeArray();_x000D_
  url: "the url to post",_x000D_
  data: data,_x000D_
  processData: false,_x000D_
  contentType: false,_x000D_
  type: 'POST',_x000D_
  success: function(data){_x000D_
  error: function(xhrRequest, status, error) {_x000D_
    return false;_x000D_
<!DOCTYPE html>_x000D_
<title>Capturing sumit action</title>_x000D_
<script src=""></script>_x000D_
<form method="POST" id="login_form">_x000D_
    <input type="text" name="username" id="username"/>_x000D_
    <input type="password" name="password" id="password"/>_x000D_
    <input type="submit" value="Submit" name="submit" class="submit" id="submit" />_x000D_

How to get data by SqlDataReader.GetValue by column name

thisReader.GetString(int columnIndex)

How to export dataGridView data Instantly to Excel on button click?

The Best is use use Library.Refer it @

var wb = new ClosedXML.Excel.XLWorkbook();
DataTable dt = GetTheDataTable();//Refer documentation


Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\"");

using (var ms = new System.IO.MemoryStream()) {


Run all SQL files in a directory

If you can use Interactive SQL:

1 - Create a .BAT file with this code:

for %%G in (*.sql) do dbisql -c "uid=dba;pwd=XXXXXXXX;ServerName=INSERT-DB-NAME-HERE" %%G

2 - Change the pwd and ServerName.

3 - Put the .BAT file in the folder that contains .SQL files and run it.

Component is part of the declaration of 2 modules

As the error says to remove the module AddEvent from root if your Page/Component is already had ionic module file if not just remove it from the other/child page/component, at the end page/component should be present in only one module file imported if to be used.

Specifically, you should add in root module if required in multiple pages and if in specific pages keep it in only one page.

Why is a ConcurrentModificationException thrown and how to debug it

Try either CopyOnWriteArrayList or CopyOnWriteArraySet depending on what you are trying to do.

How to set opacity to the background color of a div?

You can use CSS3 RGBA in this way:

rgba(255, 0, 0, 0.7);

0.7 means 70% opacity.

Mock a constructor with parameter

Mockito has limitations testing final, static, and private methods.

with jMockit testing library, you can do few stuff very easy and straight-forward as below:

Mock constructor of a class:

new MockUp<File>(){
    public void $init(String pathname){
        // or do whatever you want
  • the public constructor name should be replaced with $init
  • arguments and exceptions thrown remains same
  • return type should be defined as void

Mock a static method:

  • remove static from the method mock signature
  • method signature remains same otherwise

python exception message capturing

Use str(ex) to print execption

   #your code
except ex:

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

This kind of logic could be implemented using EXISTS:

INSERT INTO tab(a,b) VALUES(1,'a'),(1, NULL),(NULL, 'a'),(2,'b');



--SET @a = 1;    -- specific NOT NULL value
--SET @a = NULL; -- NULL value
--SET @a = -1;   -- all values

FROM tab t

db<>fiddle demo

It could be extended to contain multiple params:

FROM tab t

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:


would result in:

["Saab", "BMW"]

CSS: fixed position on x-axis but not y?

Very easy solution is:

window.onscroll = function (){
  document.getElementById('header').style.left= 15 - (document.documentElement.scrollLeft + document.body.scrollLeft)+"px";

How to add many functions in ONE ng-click?

ng-click "$watch(edit($index), open())"

git diff between two different files

I believe using --no-index is what you're looking for:

git diff [<options>] --no-index [--] <path> <path>

as mentioned in the git manual:

This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.

Convert pandas Series to DataFrame

One line answer would be



myseries.reset_index(drop=True, inplace=True)  # As needed

Javascript - validation, numbers only

Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.


RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.

Simply omit the negating ! and use if(/\D/.test(z)).

Causes of getting a java.lang.VerifyError

In my case, I was getting verify error with below stack trace

jasperreports-server-cp-6.4.0-bin\buildomatic\build.xml:61: The following error occurred while executing this line:
TIB_js-jrs-cp_6.4.0_bin\jasperreports-server-cp-6.4.0-bin\buildomatic\bin\setup.xml:320: java.lang.VerifyError: (class: org/apache/commons/codec/binary/Base64OutputStream, method: <init> signature: (Ljava/io/OutputStream;ZI[B)V) Incompatible argument to function
    at com.jaspersoft.jasperserver.crypto.KeystoreManager.createKeystore(
    at com.jaspersoft.jasperserver.crypto.KeystoreManager.init(
    at com.jaspersoft.buildomatic.crypto.KeystoreTask.execute(
    at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(
    at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(

I got it resolved by removing classpath entry for commons-codec-1.3.jar, there was a mismatch in version of this jar with the one comes with Jasper.

How do I rename all folders and files to lowercase on Linux?

Man, you guys/gals like to over complicate things... Use:

rename 'y/A-Z/a-z/' *

Best way to update data with a RecyclerView adapter

Found following solution working for my similar problem:

private ExtendedHashMap mData = new ExtendedHashMap();
private  String[] mKeys;

public void setNewData(ExtendedHashMap data) {
    mKeys = data.keySet().toArray(new String[data.size()]);

Using the clear-command


is not nessescary

How can I plot with 2 different y-axes?

One option is to make two plots side by side. ggplot2 provides a nice option for this with facet_wrap():

dat <- data.frame(x = c(rnorm(100), rnorm(100, 10, 2))
  , y = c(rnorm(100), rlnorm(100, 9, 2))
  , index = rep(1:2, each = 100)

ggplot(dat, aes(x,y)) + 
geom_point() + 
facet_wrap(~ index, scales = "free_y")

C# naming convention for constants?

The recommended naming and capitalization convention is to use PascalCasing for constants (Microsoft has a tool named StyleCop that documents all the preferred conventions and can check your source for compliance - though it is a little bit too anally retentive for many people's tastes). e.g.

private const int TheAnswer = 42;

The Pascal capitalization convention is also documented in Microsoft's Framework Design Guidelines.

Set value of textbox using JQuery

You are logging sup directly which is a string


Also you are using the wrong id

The template says #main_search but you are using #searchBar

I suppose you are trying this out

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

Removing html5 required attribute with jQuery

<script src=""></script>

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Decoding base64 to UTF8 String

Below is current most voted answer by @brandonscript

function b64DecodeUnicode(str) {
    // Going backwards: from bytestream, to percent-encoding, to original string.
    return decodeURIComponent(atob(str).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);

Above code can work, but it's very slow. If your input is a very large base64 string, for example 30,000 chars for a base64 html document. It will need lots of computation.

Here is my answer, use built-in TextDecoder, nearly 10x faster than above code for large input.

function decodeBase64(base64) {
    const text = atob(base64);
    const length = text.length;
    const bytes = new Uint8Array(length);
    for (let i = 0; i < length; i++) {
        bytes[i] = text.charCodeAt(i);
    const decoder = new TextDecoder(); // default is utf-8
    return decoder.decode(bytes);

Issue with adding common code as git submodule: "already exists in the index"

This happens if the .git file is missing in the target path. It happend to me after I executed git clean -f -d.

I had to delete all target folders showing in the message and then executing git submodule update --remote

show icon in actionbar/toolbar with AppCompat-v7 21

simplest thing to do; just add:


to the < tag

where @drawable/ic_action_navigation_menu is the name of icon

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

Here is a nice little function that worked for me.

function getDisplayDatetime() {
    var d = new Date(); var hh = d.getHours(); var mm = d.getMinutes(); var dd = "AM"; var h = hh;

    if (mm.toString().length == 1) {
        mm = "0" + mm;

    if (h >= 12) {
        h = hh - 12;
        dd = "PM";

    if (h == 0) {
        h = 12;
    var Datetime = "Datetime: " + d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getUTCDate() + " " + h + ":" + mm;
    return Datetime + " " + dd;

Get my phone number in android

From the documentation:

Returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.

So you have done everything right, but there is no phone number stored.

If you get null, you could display something to get the user to input the phone number on his/her own.

Google map V3 Set Center to specific Marker

If you want to center map onto a marker and you have the cordinate, something like click on a list item and the map should center on that coordinate then the following code will work:


<ul class="locationList" ng-repeat="LocationDetail in coordinateArray| orderBy:'LocationName'">
      <div ng-click="focusMarker(LocationDetail)">
          <strong><div ng-bind="locationDetail.LocationName"></div></strong>
          <div ng-bind="locationDetail.AddressLine"></div>
          <div ng-bind="locationDetail.State"></div>
          <div ng-bind="locationDetail.City"></div>

In Controller:

$scope.focusMarker = function (coords) {
    map.setCenter(new google.maps.LatLng(coords.Latitude, coords.Longitude));

Location Object:

    "Name": "Taj Mahal",
    "AddressLine": "Tajganj",
    "City": "Agra",
    "State": "Uttar Pradesh",
    "PhoneNumber": "1234 12344",
    "Latitude": "27.173891",
    "Longitude": "78.042068"

Java variable number or arguments for a method

For different types of arguments, there is 3-dots :

public void foo(Object... x) {
    String myVar1  = x.length > 0 ? (String)x[0]  : "Hello";
    int myVar2     = x.length > 1 ? Integer.parseInt((String) x[1]) : 888;

Then call it

foo("Hii", 146); 

for security, use like this:
if (!(x[0] instanceof String)) { throw new IllegalArgumentException("..."); }

The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Please, see more variations .

Anaconda vs. miniconda

The difference is that miniconda is just shipping the repository management system. So when you install it there is just the management system without packages. Whereas with Anaconda, it is like a distribution with some built in packages.

Like with any Linux distribution, there are some releases which bundles lots of updates for the included packages. That is why there is a difference in version numbering. If you only decide to upgrade Anaconda, you are updating a whole system.

JBoss AS 7: How to clean up tmp?

As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time


 |---> standalone
 |      |----> lib
 |      |----> configuration
 |      |----> deployments
 |---> domain


     |---> standalone
     |      |----> lib
     |      |----> configuration
     |      |----> deployments
     |      |----> tmp
     |      |----> data
     |      |----> log
     |---> domain

As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.

For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.

Good luck!

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Compiling answers given by @adurdin and @User

Add followings to your info.plist & change with your corresponding domain name, you can add multiple domains as well:


You info.plist must looks like this:

enter image description here

What is perm space?

PermGen Space stands for memory allocation for Permanent generation All Java immutable objects come under this category, like String which is created with literals or with String.intern() methods and for loading the classes into memory. PermGen Space speeds up our String equality searching.

node.js execute system command synchronously

I get used to implement "synchronous" stuff at the end of the callback function. Not very nice, but it works. If you need to implement a sequence of command line executions you need to wrap exec into some named function and recursively call it. This pattern seem to be usable for me:


function SeqOfExec(somepParam) {
    // some stuff
    // .....
    // .....

    var execStr = "yourExecString";
    child_proc.exec(execStr, function (error, stdout, stderr) {
        if (error != null) {
            if (stdout) {
                throw Error("Smth goes wrong" + error);
            } else {
                // consider that empty stdout causes
                // creation of error object
        // some stuff
        // .....
        // .....

        // you also need some flag which will signal that you 
        // need to end loop
        if (someFlag ) {
            // your synch stuff after all execs
            // here
            // .....
        } else {

curl_exec() always returns false

Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error() and curl_errno() will contain further information in case of failure:

try {
    $ch = curl_init();

    // Check if initialization had gone wrong*    
    if ($ch === false) {
        throw new Exception('failed to initialize');

    curl_setopt($ch, CURLOPT_URL, '');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt(/* ... */);

    $content = curl_exec($ch);

    // Check the return value of curl_exec(), too
    if ($content === false) {
        throw new Exception(curl_error($ch), curl_errno($ch));

    /* Process $content here */

    // Close curl handle
} catch(Exception $e) {

        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),


* The curl_init() manual states:

Returns a cURL handle on success, FALSE on errors.

I've observed the function to return FALSE when you're using its $url parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.

Cannot set some HTTP headers when using System.Net.WebRequest

Basically, no. That is an http header, so it is reasonable to cast to HttpWebRequest and set the .Referer (as you indicate in the question):

HttpWebRequest req = ...
req.Referer = "your url";

python pandas dataframe to dictionary

I found this question while trying to make a dictionary out of three columns of a pandas dataframe. In my case the dataframe has columns A, B and C (let's say A and B are the geographical coordinates of longitude and latitude and C the country region/state/etc, which is more or less the case).

I wanted a dictionary with each pair of A,B values (dictionary key) matching the value of C (dictionary value) in the corresponding row (each pair of A,B values is guaranteed to be unique due to previous filtering, but it is possible to have the same value of C for different pairs of A,B values in this context), so I did:

mydict = dict(zip(zip(df['A'],df['B']), df['C']))

Using pandas to_dict() also works:

mydict = df.set_index(['A','B']).to_dict(orient='dict')['C']

(none of the columns A or B were used as index before executing the line creating the dictionary)

Both approaches are fast (less than one second on a dataframe with 85k rows, 5-year-old fast dual-core laptop).

The reasons I'm posting this:

  1. for those who need this kind of solution
  2. if someone knows a faster executing solution (e.g., for millions of rows), I'd appreciate a reply.

Convert bytes to a string

When working with data from Windows systems (with \r\n line endings), my answer is

String = Bytes.decode("utf-8").replace("\r\n", "\n")

Why? Try this with a multiline Input.txt:

Bytes = open("Input.txt", "rb").read()
String = Bytes.decode("utf-8")
open("Output.txt", "w").write(String)

All your line endings will be doubled (to \r\r\n), leading to extra empty lines. Python's text-read functions usually normalize line endings so that strings use only \n. If you receive binary data from a Windows system, Python does not have a chance to do that. Thus,

Bytes = open("Input.txt", "rb").read()
String = Bytes.decode("utf-8").replace("\r\n", "\n")
open("Output.txt", "w").write(String)

will replicate your original file.

ExecuteReader: Connection property has not been initialized

As mentioned you should assign the connection and you should preferably also use sql parameters instead, so your command assignment would read:

    // 3. Pass the connection to a command object
    SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn); // ", conn)" added
    cmd.Parameters.Add("project", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;
    cmd.Parameters.Add("iteration", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;

    // 4. Use the connection

By using parameters you avoid SQL injection and other problematic typos (project names like "myproject's" is an example).

ImportError: cannot import name NUMPY_MKL

If you look at the line which is causing the error, you'll see this:

from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl

This line comment states the dependency as numpy+mkl (numpy with Intel Math Kernel Library). This means that you've installed the numpy by pip, but the scipy was installed by precompiled archive, which expects numpy+mkl.

This problem can be easy solved by installation for numpy+mkl from whl file from here.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Can't use System.Windows.Forms

may be necesssary, unreference and reference again.

How do I convert a string to a double in Python?

The decimal operator might be more in line with what you are looking for:

>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434 how to deserialize without using the default constructor?


public Response Get(string jsonData) {
    var json = JsonConvert.DeserializeObject<modelname>(jsonData);
    var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
    return data;


public class modelname {
    public long parameter{ get; set; }
    public int parameter{ get; set; }
    public int parameter{ get; set; }
    public string parameter{ get; set; }

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  7  /

----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

getPathInfo() gives the extra path information after the URI, used to access your Servlet, where as getRequestURI() gives the complete URI.

I would have thought they would be different, given a Servlet must be configured with its own URI pattern in the first place; I don't think I've ever served a Servlet from root (/).

For example if Servlet 'Foo' is mapped to URI '/foo' then I would have thought the URI:


Would result in:

RequestURI = /foo/path/to/resource


PathInfo = /path/to/resource

Android Fragment no view found for ID?

My mistake was on the FragamentTransaction.

I was doing this t.replace(R.layout.mylayout); instead of t.replace(;

The difference is that one is the layout and the other is a reference to the layout(id)

How to add a bot to a Telegram Group?

You have to use @BotFather, send it command: /setjoingroups There will be dialog like this:

YOU: /setjoingroups

BotFather: Choose a bot to change group membership settings.

YOU: @YourBot

BotFather: 'Enable' - bot can be added to groups. 'Disable' - block group invitations, the bot can't be added to groups. Current status is: DISABLED

YOU: Enable

BotFather: Success! The new status is: ENABLED.

After this you will see button "Add to Group" in your bot's profile.

What's the best free C++ profiler for Windows?

Very Sleepy is a C/C++ CPU profiler for Windows systems (free).

How to send cookies in a post request with the Python Requests library?

The latest release of Requests will build CookieJars for you from simple dictionaries.

import requests

cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}

r ='', cookies=cookies)

Enjoy :)

Insert php variable in a href

echo '<a href="' . $folder_path . '">Link text</a>';

Please note that you must use the path relative to your domain and, if the folder path is outside the public htdocs directory, it will not work.

EDIT: maybe i misreaded the question; you have a file on your pc and want to insert the path on the html page, and then send it to the server?

Does C have a "foreach" loop construct?

C doesn't have a foreach, but macros are frequently used to emulate that:

#define for_each_item(item, list) \
    for(T * item = list->head; item != NULL; item = item->next)

And can be used like

for_each_item(i, processes) {

Iteration over an array is also possible:

#define foreach(item, array) \
    for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
        keep && count != size; \
        keep = !keep, count++) \
      for(item = (array) + count; keep; keep = !keep)

And can be used like

int values[] = { 1, 2, 3 };
foreach(int *v, values) {
    printf("value: %d\n", *v);

Edit: In case you are also interested in C++ solutions, C++ has a native for-each syntax called "range based for"

If Browser is Internet Explorer: run an alternative script instead

You define a boolean value with default of true, and then inside an IE conditional comment, set the value to false, and use the value of this to determine whether your advanced code should run. Something like:

<script type="text/javascript">var runFancy = true;</script>
<!--[if IE]>
<script type="text/javascript">
    runFancy = false;
    //any other IE specific stuff here
<script type="text/javascript">
    if (runFancy) {
         //do your code that works with sane browsers

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

From Apple -

Thanks for bringing this to the attention of the community and apologies for the issues you’ve been having. This issue stems from having a copy of the expired WWDR Intermediate certificate in both your System and Login keychains. To resolve the issue, you should first download and install the new WWDR intermediate certificate (by double-clicking on the file). Next, in the Keychain Access application, select the System keychain. Make sure to select “Show Expired Certificates” in the View menu and then delete the expired version of the Apple Worldwide Developer Relations Certificate Authority Intermediate certificate (expired on February 14, 2016). Your certificates should now appear as valid in Keychain Access and be available to Xcode for submissions to the App Store.

As noted in a comment below, the expired certificate also needs to be removed from the login section, as well:

To all that cannot get it working despite the instructions... There are two expired WWDR certs. One is in login keychain, and the other one is in the System. You have to delete both of them in order to make things working

How to stop an unstoppable zombie job on Jenkins without restarting the server?

I guess it is too late to answer but my help some people.

  1. Install the monitoring plugin. (
  2. Go to jenkinsUrl/monitoring/nodes
  3. Go to the Threads section at the bottom
  4. Click on the details button on the left of the master
  5. Sort by User time (ms)
  6. Then look at the name of the thread, you will have the name and number of the build
  7. Kill it

I don't have enough reputation to post images sorry.

Hope it can help

Best way to retrieve variable values from a text file?

You can treat your text file as a python module and load it dynamically using imp.load_source:

import imp
imp.load_source( name, pathname[, file]) 


// mydata.txt
var1 = 'hi'
var2 = 'how are you?'
var3 = { 1:'elem1', 2:'elem2' }

// In your script file
def getVarFromFile(filename):
    import imp
    f = open(filename)
    global data
    data = imp.load_source('data', '', f)

# path to "config" file
print data.var1
print data.var2
print data.var3

How to size an Android view based on its parent's dimensions

You can now use PercentRelativeLayout. Boom! Problem solved.

Sleep/Wait command in Batch

You want to use timeout. timeout 10 will sleep 10 seconds

How to change a css class style through Javascript?

There are two ways in which this can be accomplished using vanilla javascript. The first is className and the second is classList. className works in all browsers but can be unwieldy to work with when modifying an element's class attribute. classList is an easier way to modify an element's class(es).

To outright set an element's class attribute, className is the way to go, otherwise to modify an element's class(es), it's easier to use classList.

Initial Html

<div id="ID"></div>

Setting the class attribute

var div = document.getElementById('ID');
div.className = "foo bar car";


<div id="ID" class="foo bar car"></div>

Adding a class

div.classList.add("car");// Class already exists, nothing happens

Note: There's no need to test if a class exists before adding it. If a class needs to be added, just add it. If it already exists, a duplicate won't be added.

<div id="ID" class="foo bar car tar"></div>

Removing a class

div.classList.remove("car");// No class of this name exists, nothing happens

Note: Just like add, if a class needs to be removed, remove it. If it's there, it'll be removed, otherwise nothing will happen.

<div id="ID" class="foo bar"></div>

Checking if a class attribute contains a specific class

if (div.classList.contains("foo")) {
  // Do stuff

Toggling a class

var classWasAdded = div.classList.toggle("bar"); // "bar" gets removed
// classWasAdded is false since "bar" was removed

classWasAdded = div.classList.toggle("bar"); // "bar" gets added
// classWasAdded is true since "bar" was added

.toggle has a second boolean parameter that, in my opinion, is redundant and isn't worth going over.

For more information on classList, check out MDN. It also covers browser compatibility if that's a concern, which can be addressed by using Modernizr for detection and a polyfill if needed.

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

You need to add two jars into the WEB-INF/lib directory or your webapp (or lib directory of the server):

What is the difference between x86 and x64

If you download Java Development Kit(JDK) then there is a difference as it contains native libraries which differ for different architectures:

  • x86 is for 32-bit OS
  • x64 is for 64-bit OS

In addition you can use 32-bit JDK(x86) on 64-bit OS. But you can not use 64-bit JDK on 32-bit OS.

At the same time you can run compiled Java classes on any JVM. It does not matter whether it 32 or 64-bit.

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {

      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {


What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

In the next major version of the library HttpClient interface is going to extend Closeable. Until then it is recommended to use CloseableHttpClient if compatibility with earlier 4.x versions (4.0, 4.1 and 4.2) is not required.

Set Google Maps Container DIV width and height 100%

If you can't affect your parents elements (like in a nested components situation) you can use height: 100vh which will make it a full window (=view) height;

Matching special characters and letters in regex

I tried a bunch of these but none of them worked for all of my tests. So I found this:


from this source:

How do I select a MySQL database through CLI?

Hope this helps.


VBScript - How to make program wait until process has finished?

This may not specifically answer your long 3 part question but this thread is old and I found this while searching today. Here is one shorter way to: "Wait until a process has finished." If you know the name of the process such as "EXCEL.EXE"

strProcess = "EXCEL.EXE"    
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Do While colProcesses.Count > 0
    Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
    Wscript.Sleep(1000) 'Sleep 1 second
   'msgbox colProcesses.count 'optional to show the loop works

Credit to:

Calculating distance between two points, using latitude longitude?

Note: this solution only works for short distances.

I tried to use dommer's posted formula for an application and found it did well for long distances but in my data I was using all very short distances, and dommer's post did very poorly. I needed speed, and the more complex geo calcs worked well but were too slow. So, in the case that you need speed and all the calculations you're making are short (maybe < 100m or so). I found this little approximation to work great. it assumes the world is flat mind you, so don't use it for long distances, it works by approximating the distance of a single Latitude and Longitude at the given Latitude and returning the Pythagorean distance in meters.

public class FlatEarthDist {
    //returns distance in meters
    public static double distance(double lat1, double lng1, 
                                      double lat2, double lng2){
     double a = (lat1-lat2)*FlatEarthDist.distPerLat(lat1);
     double b = (lng1-lng2)*FlatEarthDist.distPerLng(lat1);
     return Math.sqrt(a*a+b*b);

    private static double distPerLng(double lat){
      return 0.0003121092*Math.pow(lat, 4)
             +0.0101182384*Math.pow(lat, 3)

    private static double distPerLat(double lat){
            return -0.000000487305676*Math.pow(lat, 4)
                -0.0033668574*Math.pow(lat, 3)

SQL distinct for 2 fields in a database

Share my stupid thought:

Maybe I can select distinct only on c1 but not on c2, so the syntax may be select ([distinct] col)+ where distinct is a qualifier for each column.

But after thought, I find that distinct on only one column is nonsense. Take the following relationship:

   | A | B
  1| 1 | 2
  2| 1 | 1

If we select (distinct A), B, then what is the proper B for A = 1?

Thus, distinct is a qualifier for a statement.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Sorting arraylist in alphabetical order (case insensitive)

Custom Comparator should help

Collections.sort(list, new Comparator<String>() {
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);

Or if you are using Java 8:


Git: How to update/checkout a single file from remote origin master?

With Git 2.23 (August 2019) and the new (still experimental) command git restore, seen in "How to reset all files from working directory but not from staging area?", that would be:

git fetch
git restore -s origin/master -- path/to/file

The idea is: git restore only deals with files, not files and branches as git checkout does.
See "Confused by git checkout": that is where git switch comes in)

codersam adds in the comments:

in my case I wanted to get the data from my upstream (from which I forked).
So just changed to:

git restore -s upstream/master -- path/to/file

generate a random number between 1 and 10 in c

Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.

Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid()) (_getpid() on Windows), but that still won't be random.

The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random (Linux) or CryptGenRandom() (Windows), or from a service like

How do I create a datetime in Python from milliseconds?

Bit heavy because of using pandas but works:

import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()

How to resolve "Server Error in '/' Application" error?

I had this error when the .NET version was wrong - make sure the site is configured to the one you need.

See aspnet_regiis.exe for details.

How to remove a newline from a string in Bash

Under , there are some bashisms:

The tr command could be replaced by // bashism:

COMMAND=$'\nREBOOT\r   \n'
echo "|${COMMAND}|"

echo "|${COMMAND//[$'\t\r\n']}|"

echo "|${COMMAND//[$'\t\r\n ']}|"

See Parameter Expansion and QUOTING in bash's man page:

man -Pless\ +/\/pattern bash
man -Pless\ +/\\\'string\\\' bash

man -Pless\ +/^\\\ *Parameter\\\ Exp bash
man -Pless\ +/^\\\ *QUOTING bash


As asked by @AlexJordan, this will suppress all specified characters. So what if $COMMAND do contain spaces...

COMMAND=$'         \n        RE BOOT      \r           \n'
echo "|$COMMAND|"

echo "|$CLEANED|"
|                 RE BOOT                 |

shopt -q extglob || { echo "Set shell option 'extglob' on.";shopt -s extglob;}

echo "|$CLEANED|"
|                 RE BOOT|

echo "|$CLEANED|"


COMMAND=$'         \n        RE BOOT      \r           \n'
CLEANED=${COMMAND//[$'\t\r\n']} && CLEANED=${CLEANED%%*( )}
echo "|${CLEANED##*( )}|"

Note: have extglob option to be enabled (shopt -s extglob) in order to use *(...) syntax.

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

I was using Visual Studio Code.

1) Try to install the package 'Microsoft.EntityFrameworkCore.SqlServer' by specifying the version number.

VS Code:

'dotnet add package Microsoft.EntityFrameworkCore.SqlServer -v 1.1.1'

Visual Studio:-

'Install-Package Microsoft.EntityFrameworkCore.SqlServer -v 1.1.1'

Refer the link 'Package 'Microsoft.EntityFrameworkCore.SqlServer' is incompatible with 'all' frameworks in the project' for doing it.

2) Then add the namespace 'using Microsoft.EntityFrameworkCore;' manually in the Startup.cs file.

Refer the below link

3) If you get any dependency issue for 'Microsoft.EntityFrameworkCore.SqlServer.Design', like "Package 'Microsoft.EntityFrameworkCore.Design' is incompatible with 'all' frameworks in project" ,we need to run the below command,

VS Code:-

dotnet add package Microsoft.EntityFrameworkCore.Design -v 1.1

Visual Studio

Install-Package Microsoft.EntityFrameworkCore.Design -v 1.1

Cannot import XSSF in Apache POI

I Got the Solution Guys

You need to keep some points in your mind .

  1. There are two different dependency one is (poi) & other dependency is (poi- ooxml) but make sure you must use poi-ooxml dependency in your code.

  2. Just Add the following dependency in pom.xml & Save it.


3 .After you have saved the pom.xml then you need to try a small thing ,Use (.) operator will try to import/fetch it & finally will not see any sort of error because now it has imported that thing in your package.

Sample Code to Understand Better !!

package ReadFile;// package   
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  // automatically added to your code after importing
public class Test          
public static void Hello() // Method  
XSSFWorkbook workbook = new XSSFWorkbook();   

I tried my best to give you the solution , If you face any issue comment here i will try
to solve it .

Keep Learning Guys !!

Convert float64 column to int64 in Pandas

You can need to pass in the string 'int64':

>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1.0, 2.0]})  # some test dataframe

>>> df['a'].astype('int64')
0    1
1    2
Name: a, dtype: int64

There are some alternative ways to specify 64-bit integers:

>>> df['a'].astype('i8')      # integer with 8 bytes (64 bit)
0    1
1    2
Name: a, dtype: int64

>>> import numpy as np
>>> df['a'].astype(np.int64)  # native numpy 64 bit integer
0    1
1    2
Name: a, dtype: int64

Or use np.int64 directly on your column (but it returns a numpy.array):

>>> np.int64(df['a'])
array([1, 2], dtype=int64)

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

Eclipse - debugger doesn't stop at breakpoint

Go to Right click->Debug Configuration and check if too many debug instances are created. My issue was resolved when i deleted multiple debug instances from configuration and freshly started debugging.

Fastest method of screen capturing on Windows

You can try the c++ open source project WinRobot @git, a powerful screen capturer

CComPtr<IWinRobotService> pService;
hr = pService.CoCreateInstance(__uuidof(ServiceHost) );

//get active console session
CComPtr<IUnknown> pUnk;
hr = pService->GetActiveConsoleSession(&pUnk);
CComQIPtr<IWinRobotSession> pSession = pUnk;

// capture screen
pUnk = 0;
hr = pSession->CreateScreenCapture(0,0,1280,800,&pUnk);

// get screen image data(with file mapping)
CComQIPtr<IScreenBufferStream> pBuffer = pUnk;

Support :

  • UAC Window
  • Winlogon
  • DirectShowOverlay

How to debug SSL handshake using cURL?

I have used this command to troubleshoot client certificate negotiation:

openssl s_client -connect -prexit

The output will probably contain "Acceptable client certificate CA names" and a list of CA certificates from the server, or possibly "No client certificate CA names sent", if the server doesn't always require client certificates.

css h1 - only as wide as the text

.h1 {
  width: -moz-fit-content;
  width: fit-content;

  // workaround for IE11
  display: table;

All modern browsers support width: fit-content for that.

For IE11 we could emulate this behavior with display: table which doesn't break margin collapse like display: inline-block or float: left.

Find length (size) of an array in jquery

If length is undefined you can use:

function count(array){

    var c = 0;
    for(i in array) // in returns key, not object
        if(array[i] != undefined)

    return c;

var total = count(array);

Allow user to select camera or gallery for image

Building upon David's answer, my two pennies on the onActivityResult() part. It takes care of the changes introduced in 5.1.1 and detects whether the user has picked a single or multiple image from the library.

private enum Outcome {
    camera, singleLibrary, multipleLibrary, unknown

 * Returns a List<Uri> containing the image uri(s) chosen by the user
 * @param data      The data intent coming from the onActivityResult()
 * @param cameraUri The uri that had been passed to the intent when the chooser was invoked.
 * @return A List<Uri>, never null.
public List<Uri> getPicturesUriFromIntent(Intent data, Uri cameraUri) {

    Outcome outcome = Outcome.unknown;

    if (data == null || (data.getData() == null && data.getClipData() == null)) {
        outcome =;
    } else if (data.getData() != null && data.getClipData() == null) {
        outcome = Outcome.singleLibrary;
    } else if (data.getData() == null) {
        outcome = Outcome.multipleLibrary;
    } else {
        final String action = data.getAction();
        if (action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE)) {
            outcome =;

    // list the uri(s) we got back
    List<Uri> uris = new ArrayList<>();
    switch (outcome) {
        case camera:

        case singleLibrary:

        case multipleLibrary:
            final ClipData clipData = data.getClipData();
            for (int i = 0; i < clipData.getItemCount(); i++) {
                ClipData.Item item = clipData.getItemAt(i);

    return uris;

How to make an android app to always run in background?

You have to start a service in your Application class to run it always. If you do that, your service will be always running. Even though user terminates your app from task manager or force stop your app, it will start running again.

Create a service:

public class YourService extends Service {

    public IBinder onBind(Intent intent) {
        return null;

    public int onStartCommand(Intent intent, int flags, int startId) {
        // do your jobs here
        return super.onStartCommand(intent, flags, startId);

Create an Application class and start your service:

public class App extends Application {

    public void onCreate() {

        startService(new Intent(this, YourService.class));

Add "name" attribute into the "application" tag of your AndroidManifest.xml


Also, don't forget to add your service in the "application" tag of your AndroidManifest.xml

<service android:name=".YourService"/>

And also this permission request in the "manifest" tag (if API level 28 or higher):

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>


After Android Oreo, Google introduced some background limitations. Therefore, this solution above won't work probably. When a user kills your app from task manager, Android System will kill your service as well. If you want to run a service which is always alive in the background. You have to run a foreground service with showing an ongoing notification. So, edit your service like below.

public class YourService extends Service {

    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";

    public IBinder onBind(Intent intent) {
        return null;

    public int onStartCommand(Intent intent, int flags, int startId){

        // do your jobs here

        return super.onStartCommand(intent, flags, startId);

    private void startForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        startForeground(NOTIF_ID, new NotificationCompat.Builder(this, 
                NOTIF_CHANNEL_ID) // don't forget create a notification channel first
                .setContentText("Service is running background")


Unfortunately, some OEMs (Xiaomi, OnePlus, Samsung, Huawei etc.) restrict background operations due to provide longer battery life. There is no proper solution for these OEMs. Users need to allow some special permissions that are specific for OEMs or they need to add your app into whitelisted app list by device settings. You can find more detail information from

If background operations are an obligation for you, you need to explain it to your users why your feature is not working and how they can enable your feature by allowing those permissions. I suggest you to use AutoStarter library ( in order to redirect your users regarding permissions page easily from your app.

By the way, if you need to run some periodic work instead of having continuous background job. You better take a look WorkManager (

Convert String to System.IO.Stream

To convert a string to a stream you need to decide which encoding the bytes in the stream should have to represent that string - for example you can:

MemoryStream mStrm= new MemoryStream( Encoding.UTF8.GetBytes( contents ) );

MSDN references:

How to inject JPA EntityManager using spring

Is it possible to have spring to inject the JPA entityManager object into my DAO class whitout extending JpaDaoSupport? if yes, does spring manage the transaction in this case?

This is documented black on white in 12.6.3. Implementing DAOs based on plain JPA:

It is possible to write code against the plain JPA without using any Spring dependencies, using an injected EntityManagerFactory or EntityManager. Note that Spring can understand @PersistenceUnit and @PersistenceContext annotations both at field and method level if a PersistenceAnnotationBeanPostProcessor is enabled. A corresponding DAO implementation might look like this (...)

And regarding transaction management, have a look at 12.7. Transaction Management:

Spring JPA allows a configured JpaTransactionManager to expose a JPA transaction to JDBC access code that accesses the same JDBC DataSource, provided that the registered JpaDialect supports retrieval of the underlying JDBC Connection. Out of the box, Spring provides dialects for the Toplink, Hibernate and OpenJPA JPA implementations. See the next section for details on the JpaDialect mechanism.

jQuery - Add active class and remove active from other element on click

$(document).ready(function() {
    $(".tab").click(function () {

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

How to install pywin32 module in windows 7

I had the exact same problem. The problem was that Anaconda had not registered Python in the windows registry.

1) pip install pywin
2) execute this script to register Python in the windows registry
3) download the appropriate package form Corey Goldberg's answer and python will be detected

Entity Framework code first unique column

Note that in Entity Framework 6.1 (currently in beta) will support the IndexAttribute to annotate the index properties which will automatically result in a (unique) index in your Code First Migrations.

Download Excel file via AJAX MVC

CSL's answer was implemented in a project I'm working on but the problem I incurred was scaling out on Azure broke our file downloads. Instead, I was able to do this with one AJAX call:


public FileResult DownloadInvoice(int id1, int id2)
    //necessary to get the filename in the success of the ajax callback
    HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

    byte[] fileBytes = _service.GetInvoice(id1, id2);
    string fileName = "Invoice.xlsx";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

CLIENT (modified version of Handle file download from ajax post)

$("#downloadInvoice").on("click", function() {

    var xhr = new XMLHttpRequest();
    var params = [];'POST', "@Html.Raw(Url.Action("DownloadInvoice", "Controller", new { id1 = Model.Id1, id2 = Model.Id2 }))", true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function () {
        if (this.status === 200) {
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            var type = xhr.getResponseHeader('Content-Type');

            var blob = typeof File === 'function'
                ? new File([this.response], filename, { type: type })
                : new Blob([this.response], { type: type });
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                window.navigator.msSaveBlob(blob, filename);
            } else {
                var URL = window.URL || window.webkitURL;
                var downloadUrl = URL.createObjectURL(blob);

                if (filename) {
                    // use HTML5 a[download] attribute to specify filename
                    var a = document.createElement("a");
                    // safari doesn't support this yet
                    if (typeof === 'undefined') {
                        window.location = downloadUrl;
                    } else {
                        a.href = downloadUrl;
               = filename;
                } else {
                    window.location = downloadUrl;


                setTimeout(function() {
                }, 100); // cleanup
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

Duplicate line in Visual Studio Code

It's possible to create keybindings that are only active when Vim for VSCode is on and in a certain mode (i.e., "Normal", "Insert", or "Visual").

To do so, use Ctrl + Shift + P to open up VSCode's Command Palette, then search for "Preferences: Open Keyboard Shortcuts (JSON)"--selecting this option will open up keybindings.json. Here, custom bindings can be added.

For example, here are the classic VSCode commands to move/duplicate lines tweaked for ease of use in Vim..

        "key": "alt+j",
        "command": "editor.action.moveLinesDownAction",
        "when": "editorTextFocus && && vim.mode == 'Normal'"
        "key": "alt+shift+j",
        "command": "editor.action.copyLinesDownAction",
        "when": "editorTextFocus && && vim.mode == 'Normal'"
        "key": "alt+k",
        "command": "editor.action.moveLinesUpAction",
        "when": "editorTextFocus && && vim.mode == 'Normal'"
        "key": "alt+shift+k",
        "command": "editor.action.copyLinesUpAction",
        "when": "editorTextFocus && && vim.mode == 'Normal'"

Now we can use these Vim-friendly commands in VSCode!

  • Alt + J to move a line down
  • Alt + K to move a line up
  • Shift + Alt + J to duplicate a line down
  • Shift + Alt + K to duplicate a line up

How to initialize struct?

You use an implicit operator that converts the string value to a struct value:

public struct MyStruct {
  public string s;
  public int length;

  public static implicit operator MyStruct(string value) {
    return new MyStruct() { s = value, length = value.Length };



MyStruct myStruct = "Lol";



correct way to define class variables in Python

I think this sample explains the difference between the styles:

#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
['__doc__', '__init__', '__module__', 'element1']
['__doc__', '__init__', '__module__', 'element1', 'element2']
Hello World
Traceback (most recent call last):
  File "./", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

Difference between private, public, and protected inheritance

I have tried explaining inheritance using a picture below.

The main gist is that the private members of parent class are never directly accessible from derived/child class but you can use parent class's member function to access the private members of parent class. Private variables are always present in derived class but it cannot be accessed by derived class. Its like its their but you cannot see with your own eyes but if you ask someone form the parent class then he can describe it to you. Inheritance Mapping cpp

Java Try and Catch IOException Problem

The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:

public static void main(String[] args) {
  int lines = 0;  

  // TODO - Need to get the filename to populate sFileName.  Could
  // come from the command line arguments.

   try {
       lines = LineCounter.countLines(sFileName);
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);

   if(lines > 0) {
     // Do rest of program.

Pandas DataFrame concat vs append

Pandas concat vs append vs join vs merge

  • Concat gives the flexibility to join based on the axis( all rows or all columns)

  • Append is the specific case(axis=0, join='outer') of concat

  • Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']

  • Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'

Marker content (infoWindow) Google Maps

We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:

Create a new function with your information for the infoWindow in it:

function addInfoWindow(marker, message) {

            var infoWindow = new google.maps.InfoWindow({
                content: message

            google.maps.event.addListener(marker, 'click', function () {
      , marker);

Then call the function with the array ID and the marker you want to create:

addInfoWindow(marker, hotels[i][3]);

How to get all files under a specific directory in MATLAB?

I used the code mentioned in this great answer and expanded it to support 2 additional parameters which I needed in my case. The parameters are file extensions to filter on and a flag indicating whether to concatenate the full path to the name of the file or not.

I hope it is clear enough and someone will finds it beneficial.

function fileList = getAllFiles(dirName, fileExtension, appendFullPath)

  dirData = dir([dirName '/' fileExtension]);      %# Get the data for the current directory
  dirWithSubFolders = dir(dirName);
  dirIndex = [dirWithSubFolders.isdir];  %# Find the index for directories
  fileList = {}';  %'# Get a list of the files
  if ~isempty(fileList)
    if appendFullPath
      fileList = cellfun(@(x) fullfile(dirName,x),...  %# Prepend path to files
  subDirs = {dirWithSubFolders(dirIndex).name};  %# Get a list of the subdirectories
  validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
                                               %#   that are not '.' or '..'
  for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dirName,subDirs{iDir});    %# Get the subdirectory path
    fileList = [fileList; getAllFiles(nextDir, fileExtension, appendFullPath)];  %# Recursively call getAllFiles


Example for running the code:

fileList = getAllFiles(dirName, '*.xml', 0); %#0 is false obviously

What is the simplest SQL Query to find the second largest value?

    column < (SELECT max(columnq) FROM table) 
    column DESC LIMIT 1

How to compare LocalDate instances Java 8

Using equals() LocalDate does override equals:

int compareTo0(LocalDate otherDate) {
    int cmp = (year - otherDate.year);
    if (cmp == 0) {
        cmp = (month - otherDate.month);
        if (cmp == 0) {
            cmp = (day -;
    return cmp;

If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

Convert PDF to image with high resolution

One more suggestion is that you can use GIMP.

Just load the PDF file in GIMP->save as .xcf and then you can do whatever you want to the image.

jQuery - simple input validation - "empty" and "not empty"

    jQuery("#input").live('change', function() {
        // since we check more than once against the value, place it in a var.
        var inputvalue = $("#input").attr("value");

        // if it's value **IS NOT** ""
        if(inputvalue !== "") {
            jQuery(this).css('outline', 'solid 1px red'); 

        // else if it's value **IS** ""
        else if(inputvalue === "") {


Babel 6 regeneratorRuntime is not defined

This solution is out of date.

I found the solution in the youtube comments of this video

This should direct to the correct comment. Much props to "beth w" for finding the solution.

Beth W 3 months ago (edited)
Another change I had to make in 2019 - babel no longer uses the stage-0 preset as of v7 apparently, so at 26:15 instead of 'npm install --save-dev babel-polyfill babel-preset-stage-0', I had to do:

npm install --save @babel/polyfill

Which covers both of the older options. Then, in the entry point for the app I > included '@babel/polyfill', and in the query presets I left it as-is. So the webpack config ends up looking like:

const path = require('path');
module.exports = {
    entry: {
        app: ['@babel/polyfill', './src/app.js']
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'app.bundle.js'
    mode: 'development',
    module: {
        rules: [{
            test: /\.js?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
                presets: ['@babel/preset-env']

Hope that helps someone!

BigDecimal equals() versus compareTo()

I see that BigDecimal has an inflate() method on equals() method. What does inflate() do actually?

Basically, inflate() calls BigInteger.valueOf(intCompact) if necessary, i.e. it creates the unscaled value that is stored as a BigInteger from long intCompact. If you don't need that BigInteger and the unscaled value fits into a long BigDecimal seems to try to save space as long as possible.

How to run .sh on Windows Command Prompt?

New feature in Windows - run bash on ubuntu on windows - available in Windows 10 "Insiders" builds after the Build conference:

Importing csv file into R - numeric values read as characters

Including this in the read.csv command worked for me: strip.white = TRUE

(I found this solution here.)

Can't access RabbitMQ web management interface after fresh install

If you still can't access the management console after a fresh install, check if the management console was enabled. To enable it:

  1. Go to the RabbitMQ command prompt.

  2. Type:

    rabbitmq-plugins enable rabbitmq_management

Current timestamp as filename in Java

Use SimpleDateFormat as aix suggested to format the current time into a string. You should use a format that does not include / characters etc. I would suggest something like yyyyMMddhhmm

Best C# API to create PDF


I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.

I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at

What's the "average" requests per second for a production web application?

You can search "slashdot effect analysis" for graphs of what you would see if some aspect of the site suddenly became popular in the news, e.g. this graph on wiki.

Web-applications that survive tend to be the ones which can generate static pages instead of putting every request through a processing language.

There was an excellent video (I think it might have been on I think it might have been by flickr web team? Does someone know the link?) with ideas on how to scale websites beyond the single server, e.g. how to allocate connections amongst the mix of read-only and read-write servers to get best effect for various types of users.

How to deserialize a list using GSON or another JSON library in Java?

Another way is to use an array as a type, e.g.:

Video[] videoArray = gson.fromJson(json, Video[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list, e.g.:

List<Video> videoList = Arrays.asList(videoArray);

IMHO this is much more readable.

In Kotlin this looks like this:

Gson().fromJson(jsonString, Array<Video>

To convert this array into List, just use .toList() method

What do >> and << mean in Python?

12 << 2


Actual binary value of 12 is "00 1100" when we execute the above statement Left shift ( 2 places shifted left) returns the value 48 its binary value is "11 0000".

48 >> 2


The binary value of 48 is "11 0000", after executing above statement Right shift ( 2 places shifted right) returns the value 12 its binary value is "00 1100".

Changing Placeholder Text Color with Swift

Create UITextField Extension like this:

extension UITextField{
   @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue!])

And in your storyboard or .xib. You will see

enter image description here

How to display all elements in an arraylist?

You are getting an error because your getAll function in the Car class returns a single Car and you want to assign it into an array.

It's really not clear and you may want to post more code. why are you passing a single Car to the function? What is the meaning of calling getAll on a Car.

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Perform the following steps:

  1. Start the Registry Editor by typing regedit in the Run window.
  2. Select the following key in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
  3. In the Security menu, click Permissions.
  4. Grant Full Permission to the account which is being used for making connections.
  5. Quit the Registry Editor.

How do I write to the console from a Laravel Controller?

Bit late to this...I'm surprised that no one mentioned Symfony's VarDumper component that Laravel includes, in part, for its dd() (and lesser-known, dump()) utility functions.

$dumpMe = new App\User([ 'name' => 'Cy Rossignol' ]);

(new Symfony\Component\VarDumper\Dumper\CliDumper())->dump( 
    (new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($dumpMe)

There's a bit more code needed, but, in return, we get nice formatted, readable output in the console—especially useful for debugging complex objects or arrays:

App\User {#17
  #attributes: array:1 [
    "name" => "Cy Rossignol"
  #fillable: array:3 [
    0 => "name"
    1 => "email"
    2 => "password"
  #guarded: array:1 [
    0 => "*"
  #primaryKey: "id"
  #casts: []
  #dates: []
  #relations: []
  ... etc ...

To take this a step further, we can even colorize the output! Add this helper function to the project to save some typing:

function toConsole($var) 
    $dumper = new Symfony\Component\VarDumper\Dumper\CliDumper();

    $dumper->dump((new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($var));

If we're running the app behind a full webserver (like Apache or Nginx—not artisan serve), we can modify this function slightly to send the dumper's prettified output to the log (typically storage/logs/laravel.log):

function toLog($var) 
    $lines = [ 'Dump:' ];
    $dumper = new Symfony\Component\VarDumper\Dumper\CliDumper();
    $dumper->setOutput(function ($line) use (&$lines) { 
        $lines[] = $line;

    $dumper->dump((new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($var));

    Log::debug(implode(PHP_EOL, $lines));

...and, of course, watch the log using:

$ tail -f storage/logs/laravel.log

PHP's error_log() works fine for quick, one-off inspection of simple values, but the functions shown above take the hard work out of debugging some of Laravel's more complicated classes.

Set focus on <input> element

To make the execution after the boolean has changed and avoid the usage of timeout you can do:

import { ChangeDetectorRef } from '@angular/core';

constructor(private cd: ChangeDetectorRef) {}

showSearch(){ = !;;

Importing variables from another file?

Import file1 inside file2:

To import all variables from file1 without flooding file2's namespace, use:

import file1

#now use file1.x1, file2.x2, ... to access those variables

To import all variables from file1 to file2's namespace( not recommended):

from file1 import *
#now use x1, x2..

From the docs:

While it is valid to use from module import * at module level it is usually a bad idea. For one, this loses an important property Python otherwise has — you can know where each toplevel name is defined by a simple “search” function in your favourite editor. You also open yourself to trouble in the future, if some module grows additional functions or classes.

Stopword removal with NLTK

There is an in-built stopword list in NLTK made up of 2,400 stopwords for 11 languages (Porter et al), see

>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> stop = set(stopwords.words('english'))
>>> sentence = "this is a foo bar sentence"
>>> print([i for i in sentence.lower().split() if i not in stop])
['foo', 'bar', 'sentence']
>>> [i for i in word_tokenize(sentence.lower()) if i not in stop] 
['foo', 'bar', 'sentence']

I recommend looking at using tf-idf to remove stopwords, see Effects of Stemming on the term frequency?

How to capitalize the first letter of text in a TextView in an Android Application

You can add Apache Commons Lang in Gradle like compile 'org.apache.commons:commons-lang3:3.4'

And use WordUtils.capitalizeFully(name)

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

Entity Framework Queryable async

The problem seems to be that you have misunderstood how async/await work with Entity Framework.

About Entity Framework

So, let's look at this code:

public IQueryable<URL> GetAllUrls()
    return context.Urls.AsQueryable();

and example of it usage:

repo.GetAllUrls().Where(u => <condition>).Take(10).ToList()

What happens there?

  1. We are getting IQueryable object (not accessing database yet) using repo.GetAllUrls()
  2. We create a new IQueryable object with specified condition using .Where(u => <condition>
  3. We create a new IQueryable object with specified paging limit using .Take(10)
  4. We retrieve results from database using .ToList(). Our IQueryable object is compiled to sql (like select top 10 * from Urls where <condition>). And database can use indexes, sql server send you only 10 objects from your database (not all billion urls stored in database)

Okay, let's look at first code:

public async Task<IQueryable<URL>> GetAllUrlsAsync()
    var urls = await context.Urls.ToListAsync();
    return urls.AsQueryable();

With the same example of usage we got:

  1. We are loading in memory all billion urls stored in your database using await context.Urls.ToListAsync();.
  2. We got memory overflow. Right way to kill your server

About async/await

Why async/await is preferred to use? Let's look at this code:

var stuff1 = repo.GetStuff1ForUser(userId);
var stuff2 = repo.GetStuff2ForUser(userId);
return View(new Model(stuff1, stuff2));

What happens here?

  1. Starting on line 1 var stuff1 = ...
  2. We send request to sql server that we want to get some stuff1 for userId
  3. We wait (current thread is blocked)
  4. We wait (current thread is blocked)
  5. .....
  6. Sql server send to us response
  7. We move to line 2 var stuff2 = ...
  8. We send request to sql server that we want to get some stuff2 for userId
  9. We wait (current thread is blocked)
  10. And again
  11. .....
  12. Sql server send to us response
  13. We render view

So let's look to an async version of it:

var stuff1Task = repo.GetStuff1ForUserAsync(userId);
var stuff2Task = repo.GetStuff2ForUserAsync(userId);
await Task.WhenAll(stuff1Task, stuff2Task);
return View(new Model(stuff1Task.Result, stuff2Task.Result));

What happens here?

  1. We send request to sql server to get stuff1 (line 1)
  2. We send request to sql server to get stuff2 (line 2)
  3. We wait for responses from sql server, but current thread isn't blocked, he can handle queries from another users
  4. We render view

Right way to do it

So good code here:

using System.Data.Entity;

public IQueryable<URL> GetAllUrls()
   return context.Urls.AsQueryable();

public async Task<List<URL>> GetAllUrlsByUser(int userId) {
   return await GetAllUrls().Where(u => u.User.Id == userId).ToListAsync();

Note, than you must add using System.Data.Entity in order to use method ToListAsync() for IQueryable.

Note, that if you don't need filtering and paging and stuff, you don't need to work with IQueryable. You can just use await context.Urls.ToListAsync() and work with materialized List<Url>.

How to create/read/write JSON files in Qt5

An example on how to use that would be great. There is a couple of examples at the Qt forum, but you're right that the official documentation should be expanded.

QJsonDocument on its own indeed doesn't produce anything, you will have to add the data to it. That's done through the QJsonObject, QJsonArray and QJsonValue classes. The top-level item needs to be either an array or an object (because 1 is not a valid json document, while {foo: 1} is.)

Create a File object in memory from a string in Java

FileReader r = new FileReader(file);

Use a file reader load the file and then write its contents to a string buffer.


The link above shows you an example of how to accomplish this. As other post to this answer say to load a file into memory you do not need write access as long as you do not plan on making changes to the actual file.

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.


>>> import requests
>>> r = requests.get('')
>>> r.status_code

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Bash Shell Script - Check for a flag and grab its value

Here is a generalized simple command argument interface you can paste to the top of all your scripts.


declare -A flags
declare -A booleans

while [ "$1" ];
    if [ "${1:0:1}" == "-" ]
      rev=$(echo "$arg" | rev)
      if [ -z "$1" ] || [ "${1:0:1}" == "-" ] || [ "${rev:0:1}" == ":" ]
        bool=$(echo ${arg:1} | sed s/://g)
        echo \"$bool\" is boolean
        echo \"$arg\" is flag with value \"$value\"
      echo \"$arg\" is an arg

echo -e "\n"
echo booleans: ${booleans[@]}
echo flags: ${flags[@]}
echo args: ${args[@]}

echo -e "\nBoolean types:\n\tPrecedes Flag(pf): ${booleans[pf]}\n\tFinal Arg(f): ${booleans[f]}\n\tColon Terminated(Ct): ${booleans[Ct]}\n\tNot Mentioned(nm): ${boolean[nm]}"
echo -e "\nFlag: myFlag => ${flags["myFlag"]}"
echo -e "\nArgs: one: ${args[0]}, two: ${args[1]}, three: ${args[2]}"

By running the command: firstArg -pf -myFlag "my flag value" secondArg -Ct: thirdArg -f

The output will be this:

"firstArg" is an arg
"pf" is boolean
"-myFlag" is flag with value "my flag value"
"secondArg" is an arg
"Ct" is boolean
"thirdArg" is an arg
"f" is boolean

booleans: true true true
flags: my flag value
args: firstArg secondArg thirdArg

Boolean types:
    Precedes Flag(pf): true
    Final Arg(f): true
    Colon Terminated(Ct): true
    Not Mentioned(nm): 

Flag: myFlag => my flag value

Args: one => firstArg, two => secondArg, three => thirdArg

Basically, the arguments are divided up into flags booleans and generic arguments. By doing it this way a user can put the flags and booleans anywhere as long as he/she keeps the generic arguments (if there are any) in the specified order.

Allowing me and now you to never deal with bash argument parsing again!

You can view an updated script here

This has been enormously useful over the last year. It can now simulate scope by prefixing the variables with a scope parameter.

Just call the script like

replace() (
  source $FUTIL_REL_DIR/ -scope ${FUNCNAME[0]} "$@"
  echo ${replaceFlags[f]}
  echo ${replaceBooleans[b]}

Doesn't look like I implemented argument scope, not sure why I guess I haven't needed it yet.

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);


a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));

    public static class Extenions
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)

                yield return l;

Dealing with HTTP content in HTTPS pages

It would be best to just have the http content on https

Why does Vim save files with a ~ extension?

The only option that worked for me was to put this line in my ~/.vimrc file

set noundofile

The other options referring to backup files did not prevent the creation of the temp files ending in ~ (tilde)

What are file descriptors, explained in simple terms?

Addition to above all simplified responses.

If you are working with files in bash script, it's better to use file descriptor.

For example: If you want to read and write from/to the file "test.txt", use the file descriptor as show below:

FILE=$1 # give the name of file in the command line
exec 5<>$FILE # '5' here act as the file descriptor

# Reading from the file line by line using file descriptor
while read LINE; do
    echo "$LINE"
done <&5

# Writing to the file using descriptor
echo "Adding the date: `date`" >&5 
exec 5<&- # Closing a file descriptor

Why does JavaScript only work after opening developer tools in IE once?

I guess this could help, adding this before any tag of javascript:

   console={}; console.log = function(){};

How to update Identity Column in SQL Server?



Pretty graphs and charts in Python

I used pychart and thought it was very straightforward.

It's all native python and does not have a busload of dependencies. I'm sure matplotlib is lovely but I'd be downloading and installing for days and I just want one measley bar chart!

It doesn't seem to have been updated in a few years but hey it works!

How do I update Anaconda?

If you are trying to update your Anaconda version to a new one, you'll notice that running the new installer wouldn't work, as it complains the installation directory is non-empty.

So you should use conda to upgrade as detailed by the official docs:

conda update conda
conda update anaconda

In Windows, if you made a "for all users" installation, it might be necessary to run from an Anaconda prompt with Administrator privileges.

Simply right click on Anaconda Prompt in the start menu

This prevents the error:

ERROR An error occurred while uninstalling package 'defaults::conda-4.5.4-py36_0'. PermissionError(13, 'Access is denied')

Timer function to provide time in nano seconds using C++

If you need subsecond precision, you need to use system-specific extensions, and will have to check with the documentation for the operating system. POSIX supports up to microseconds with gettimeofday, but nothing more precise since computers didn't have frequencies above 1GHz.

If you are using Boost, you can check boost::posix_time.

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

This link android-9.0-changes-28-->Apache HTTP client deprecation explains reason for adding the following to your AndroidManifest.xml:

<uses-library android:name="org.apache.http.legacy" android:required="false"/>

With Android 6.0, we removed support for the Apache HTTP client. Beginning with Android 9, that library is removed from the bootclasspath and is not available to apps by default.

How to get multiple selected values of select box in php?

You could do like this too. It worked out for me.

<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
    <select id="selectDuration" name="selectDuration[]" multiple="multiple"> 
        <option value="1 WEEK" >Last 1 Week</option>
        <option value="2 WEEK" >Last 2 Week </option>
        <option value="3 WEEK" >Last 3 Week</option>
         <option value="4 WEEK" >Last 4 Week</option>
          <option value="5 WEEK" >Last 5 Week</option>
           <option value="6 WEEK" >Last 6 Week</option>
     <input type="submit"/> 

Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.



Select current date by default in ASP.Net Calendar control

DateTime.Now will not work, use DateTime.Today instead.

Python Graph Library

I would like to plug my own graph python library: graph-tool.

It is very fast, since it is implemented in C++ with the Boost Graph Library, and it contains lots of algorithms and extensive documentation.

Android Webview - Completely Clear the Cache

To clear all the webview caches while you signOUT form your APP:

CookieManager cookieManager = CookieManager.getInstance();        

For Lollipop and above:

CookieManager cookieManager = CookieManager.getInstance();