Programs & Examples On #Variable expansion

Evaluating or expanding a variable to get its value. Depending on the language, a variable may be expanded one or more times.

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

Switch on ranges of integers in JavaScript

If you are trying to do something fast, efficient and readable, use a standard if...then...else structure like this:

var d =;
if (d < 12) {
    if (d < 5) {
        alert("less than five");
    }else if (d < 9) {
        alert("between 5 and 8");
        alert("between 9 and 11");

If you want to obfuscate it and make it awful (but small), try this:

var;d<12?(d<5?alert("less than five"):d<9?alert("between 5 and 8"):alert("between 9 and 11")):alert("none");

BTW, the above code is a JavaScript if...then...else shorthand statement. It is a great example of how NOT to write code unless obfuscation or code minification is the goal. Be aware that code maintenance can be an issue if written this way. Very few people can easily read through it, if at all. The code size, however, is 50% smaller than the standard if...then...else without any loss of performance. This means that in larger codebases, minification like this can greatly speed code delivery across bandwidth constrained or high latency networks.

This, however, should not be considered a good answer. It is just an example of what CAN be done, not what SHOULD be done.

How to quickly drop a user with existing privileges

I had to add one more line to REVOKE...

After running:


I was still receiving the error: username cannot be dropped because some objects depend on it DETAIL: privileges for schema public

I was missing this:


Then I was able to drop the role.

DROP USER username;

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

I faced this problem this morning when I just opened an old app with a different certificate and allowed its access to the keychain. My other app that was working pretty well, stopped working with this error. I've been pulling out my hair till now, when I simply did this:

Xcode Menu > Preferences > Accounts > THE_APPLE_ID_THAT_YOU_ARE_USING > View Details

In the new window, at the bottom left of the Signing identities press the + button and select iOS Development. It'll re-add the identity, and after that my problem is fixed now and the app is running on the device again.

enter image description here

What is the difference between single and double quotes in SQL?

The difference lies in their usage. The single quotes are mostly used to refer a string in WHERE, HAVING and also in some built-in SQL functions like CONCAT, STRPOS, POSITION etc.

When you want to use an alias that has space in between then you can use double quotes to refer to that alias.

For example

(select account_id,count(*) "count of" from orders group by 1)sub 

Here is a subquery from an orders table having account_id as Foreign key that I am aggregating to know how many orders each account placed. Here I have given one column any random name as "count of" for sake of purpose.

Now let's write an outer query to display the rows where "count of" is greater than 20.

select "count of" from 
(select account_id,count(*) "count of" from orders group by 1)sub where "count of" >20;

You can apply the same case to Common Table expressions also.

Make a simple fade in animation in Swift?

import UIKit

 Here is simple subclass for CAAnimation which create a fadeIn animation

class FadeInAdnimation: CABasicAnimation {
    override init() {
        keyPath = "opacity"
        duration = 2.0
        fromValue = 0
        toValue = 1
        fillMode = CAMediaTimingFillMode.forwards
        isRemovedOnCompletion = false

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

 Example of usage

class ViewController: UIViewController {

    weak var label: UILabel!

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = UILabel()
        label.alpha = 0
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        label.text = "Hello World!"
        label.textColor = .black
        self.label = label

        let button = UIButton(type: .custom)
        button.frame = CGRect(x: 0, y: 250, width: 300, height: 100)
        button.setTitle("Press to Start FadeIn", for: UIControl.State())
        button.backgroundColor = .red
        button.addTarget(self, action: #selector(startFadeIn), for: .touchUpInside)

        self.view = view

     Animation in action
    @objc private func startFadeIn() {
        label.layer.add(FadeInAdnimation(), forKey: "fadeIn")


Is SMTP based on TCP or UDP?

Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!

What exactly are iterator, iterable, and iteration?

An iterable is a object which has a __iter__() method. It can possibly iterated over several times, such as list()s and tuple()s.

An iterator is the object which iterates. It is returned by an __iter__() method, returns itself via its own __iter__() method and has a next() method (__next__() in 3.x).

Iteration is the process of calling this next() resp. __next__() until it raises StopIteration.


>>> a = [1, 2, 3] # iterable
>>> b1 = iter(a) # iterator 1
>>> b2 = iter(a) # iterator 2, independent of b1
>>> next(b1)
>>> next(b1)
>>> next(b2) # start over, as it is the first call to b2
>>> next(b1)
>>> next(b1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
>>> b1 = iter(a) # new one, start over
>>> next(b1)

When to use DataContract and DataMember attributes?

Since a lot of programmers were overwhelmed with the [DataContract] and [DataMember] attributes, with .NET 3.5 SP1, Microsoft made the data contract serializer handle all classes - even without any of those attributes - much like the old XML serializer.

So as of .NET 3.5 SP1, you don't have to add data contract or data member attributes anymore - if you don't then the data contract serializer will serialize all public properties on your class, just like the XML serializer would.

HOWEVER: by not adding those attributes, you lose a lot of useful capabilities:

  • without [DataContract], you cannot define an XML namespace for your data to live in
  • without [DataMember], you cannot serialize non-public properties or fields
  • without [DataMember], you cannot define an order of serialization (Order=) and the DCS will serialize all properties alphabetically
  • without [DataMember], you cannot define a different name for your property (Name=)
  • without [DataMember], you cannot define things like IsRequired= or other useful attributes
  • without [DataMember], you cannot leave out certain public properties - all public properties will be serialized by the DCS

So for a "quick'n'dirty" solution, leaving away the [DataContract] and [DataMember] attributes will work - but it's still a good idea to have them on your data classes - just to be more explicit about what you're doing, and to give yourself access to all those additional features that you don't get without them...

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

In my case, for both Debug and Release, the solution was to clean then rebuild entire solution.

Edit: true in my case also (VS2017) step1: clean the project. step2: change configuration mode(from debug to release or vice versa). step3: clean the project. step4: build in the required configuration mode.

PS: to change config mode, find config settings under build menu

Get the last inserted row ID (with SQL statement)

You can use:


to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)



This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

SQL query for a carriage return in a string and ultimately removing carriage return

If you are considering creating a function, try this: DECLARE @schema sysname = 'dbo' , @tablename sysname = 'mvtEST' , @cmd NVarchar(2000) , @ColName sysname

    DECLARE @NewLine Table
    (ColumnName Varchar(100)
    ,Location Int
    ,ColumnValue Varchar(8000)


    OPEN looper
    FETCH NEXT FROM looper INTO @ColName

    WHILE @@fetch_status = 0
    SELECT @cmd = 'select ''' +@ColName+    ''',  CHARINDEX(Char(10),  '+  @ColName +') , '+ @ColName + ' from '+@schema + '.'+@tablename +' where CHARINDEX(Char(10),  '+  @ColName +' ) > 0 or CHARINDEX(CHAR(13), '+@ColName +') > 0'
    PRINT @cmd
    INSERT @NewLine ( ColumnName, Location, ColumnValue )
    EXEC sp_executesql @cmd
    FETCH NEXT FROM looper INTO @ColName
    CLOSE looper
    DEALLOCATE looper

    SELECT * FROM  @NewLine

How to Make Laravel Eloquent "IN" Query?

As @Raheel Answered it will fine but if you are working with Laravel 7/6

Then Eloquent whereIn Query.


$users = User::wherein('id',[1,2,3])->get();


$users = DB::table('users')->whereIn('id', [1, 2, 3])->get();


$ids = [1,2,3];

$users = User::wherein('id',$ids)->get();

Erasing elements from a vector

  1. You can iterate using the index access,

  2. To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.


void erase(std::vector<int>& v, int num)
  size_t j = 0;
  for (size_t i = 0; i < v.size(); ++i) {
    if (v[i] != num) v[j++] = v[i];
  // trim vector to new size

In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.

This code does not use erase method, but solves your task.

Using pure stl you can do this in the following way (this is similar to the Motti's answer):

#include <algorithm>

void erase(std::vector<int>& v, int num) {
    vector<int>::iterator it = remove(v.begin(), v.end(), num);
    v.erase(it, v.end());

new Date() is working in Chrome but not Firefox

Option 1 :

Suppose your timestring has a format that looks like this :

'2016-03-10 16:00:00.0'

In that case, you could do a simple regex to convert it to ISO 8601 :

'2016-03-10 16:00:00.0'.replace(/ /g,'T')

This would procude the following output :


This is the standard datetime format, and thus supported by all browsers :

document.body.innerHTML = new Date('2016-03-10T16:00:00.0') // THIS IS SAFE TO USE

Option 2 :

Suppose your timestring has a format that looks like this :

'02-24-2015 09:22:21 PM'

Here, you can do the following regex :

'02-24-2015 09:22:21 PM'.replace(/-/g,'/');

This, too, produces a format supported by all browsers :

document.body.innerHTML = new Date('02/24/2015 09:22:21 PM') // THIS IS SAFE TO USE

Option 3 :

Suppose you have a time string that isn't easy to adjust to one of the well-supported standards.

In that case, it's best to just split your time string into different pieces and use them as individual parameters for Date :

document.body.innerHTML = new Date(2016, 2, 26, 3, 24, 0); // THIS IS SAFE TO USE

PostgreSQL delete with inner join

This worked for me:

DELETE from m_productprice
WHERE  m_pricelist_version_id='1000020'
       AND m_product_id IN (SELECT m_product_id
                            FROM   m_product
                            WHERE  upc = '7094'); 

How to 'grep' a continuous stream?

Didn't see anyone offer my usual go-to for this:

less +F <file>
ctrl + c
/<search term>
shift + f

I prefer this, because you can use ctrl + c to stop and navigate through the file whenever, and then just hit shift + f to return to the live, streaming search.

Convert JSONArray to String Array

Simplest and correct code is:

public static String[] toStringArray(JSONArray array) {
        return null;

    String[] arr=new String[array.length()];
    for(int i=0; i<arr.length; i++) {
    return arr;

Using List<String> is not a good idea, as you know the length of the array. Observe that it uses arr.length in for condition to avoid calling a method, i.e. array.length(), on each loop.

CSS override rules and specificity

To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 trfrom rule one and add it to rule two.

table.rule1 tr td {
    background-color: #ff0000;

table.rule1 tr td.rule2 {
    background-color: #ffff00;

After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.

PHP Warning: Unknown: failed to open stream

In Fedora 25, it turned out to be an SE Linux issue, and the notification gave this solution which worked for me.

setsebool -P httpd_read_user_content 1

SQL Error with Order By in Subquery

Besides the fact that order by doesn't seem to make sense in your query.... To use order by in a sub select you will need to use TOP 2147483647.

  SELECT TOP 2147483647
  COUNT(1) FROM Seanslar WHERE MONTH(tarihi) = 4
  GROUP BY refKlinik_id
  ORDER BY refKlinik_id
) as dorduncuay

My understanding is that "TOP 100 PERCENT" doesn't gurantee ordering anymore starting with SQL 2005:

In SQL Server 2005, the ORDER BY clause in a view definition is used only to determine the rows that are returned by the TOP clause. The ORDER BY clause does not guarantee ordered results when the view is queried, unless ORDER BY is also specified in the query itself.

See SQL Server 2005 breaking changes

Hope this helps, Patrick

Vertical alignment of text and icon in button

Just wrap the button label in an extra span and add class="align-middle" to both (the icon and the label). This will center your icon with text vertical.

<button id="edit-listing-form-house_Continue" 
    class="btn btn-large btn-primary"
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>

How to specify in crontab by what user to run script?

You can also try using runuser (as root) to run a command as a different user

*/1 * * * * runuser php5 \
            --command="/var/www/web/includes/crontab/queue_process.php \
                       >> /var/www/web/includes/crontab/queue.log 2>&1"

See also: man runuser

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

I will say It 's just shorthand syntax for get reference of html element during debugging time , normaly these kind of task will perform by these method

document.getElementById , document.getElementsByClassName , document.querySelector

so clicking on an html element and getting a reference variable ($0) in console is a huge time saving during the day

HTML5 Audio Looping

I did it this way,

<audio controls="controls" loop="loop">
<source src="someSound.ogg" type="audio/ogg" />

and it looks like this

enter image description here

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:


In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

How to style a checkbox using CSS

Here is a CSS/HTML-only version, no jQuery or JavaScript needed at all, Simple and clean HTML and really simple and short CSS.

Here is the JSFiddle

Here is the HTML:

<div id="myContainer">
    <input type="checkbox" name="myCheckbox" id="myCheckbox_01_item" value="red" />
    <label for="myCheckbox_01_item" class="box"></label>
    <label for="myCheckbox_01_item" class="text">I accept the Terms of Use.</label>

Here is the CSS

#myContainer {
    outline: black dashed 1px;
    width: 200px;
#myContainer input[type="checkbox"][name="myCheckbox"] {
    display: none;
#myContainer input[type="checkbox"][name="myCheckbox"]:not(:checked) + {
    display: inline-block;
    width: 25px;
    height: 25px;
    border: black solid 1px;
    background: #FFF ;
    margin: 5px 5px;
#myContainer input[type="checkbox"][name="myCheckbox"]:checked + {
    display: inline-block;
    width: 25px;
    height: 25px;
    border: black solid 1px;
    background: #F00;
    margin: 5px 5px;
#myContainer input[type="checkbox"][name="myCheckbox"] + label + label.text {
    font: normal 12px arial;
    display: inline-block;
    line-height: 27px;
    vertical-align: top;
    margin: 5px 0px;

This can be adapted to be able to have individual radio or checkboxes, grooups of checkboxes and groups of radio buttons as well.

This html/css, will allow you to also capture click on the label, so the checkbox will be checked and unchecked even if you click just on the label.

This type of checkbox/radio button works perfectly with any form, no problem at all. Have been tested using PHP, ASP.NET (.aspx), JavaServer Faces, and ColdFusion too.

powershell mouse move does not prevent idle mode

I had a similar situation where a download needed to stay active overnight and required a key press that refreshed my connection. I also found that the mouse move does not work. However, using notepad and a send key function appears to have done the trick. I send a space instead of a "." because if there is a [yes/no] popup, it will automatically click the default response using the spacebar. Here is the code used.

param($minutes = 120)

$myShell = New-Object -com "Wscript.Shell"

for ($i = 0; $i -lt $minutes; $i++) {
  Start-Sleep -Seconds 30
  $myShell.sendkeys(" ")

This function will work for the designated 120 minutes (2 Hours), but can be modified for the timing desired by increasing or decreasing the seconds of the input, or increasing or decreasing the assigned value of the minutes parameter.

Just run the script in powershell ISE, or powershell, and open notepad. A space will be input at the specified interval for the desired length of time ($minutes).

Good Luck!

RestSharp simple complete example

I managed to find a blog post on the subject, which links off to an open source project that implements RestSharp. Hopefully of some help to you. The blog post is a 2 parter, and the project is here:

It might help if you had a full example of what wasn't working. It's difficult to get context on how the client was set up if you don't provide the code.

How can I extract the folder path from file path in Python?

The built-in submodule os.path has a function for that very task.

import os

A project with an Output Type of Class Library cannot be started directly

If you got this issue (got it in Visual Studio 2017 RC), and you don't get any of the things listed by Mak post from step 3 onward "4 In the Output Type drop box....", it is because you made a Class Library app when you want to create a cross platform app, so here is the solution :

1 Start a new project

2 select Visual C# and cross-platform app.

3 select cross-platform app (Xamarin and native app)

4 select blank form.

From then , right click, select as startup project and build as mentioned by Mak, and it should work.

If you can afford to start from scratch, it could do the trick as it did for me.

This could do the trick for the main issue as well, but must be adapted to your current version of Visual Studio ("Xamarin.forms portable" for visual studio 2015 for example).


How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

For plain ASP.NET MVC Controllers

Create a new attribute

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    public override void OnActionExecuting(ActionExecutingContext filterContext)
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");

Tag your action:

public ActionResult YourMethod()
    return Json("Works better?");


using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");


Tag a whole API controller:

public class ValuesController : ApiController

Or individual API calls:

public IEnumerable<PartViewModel> Get()

For Internet Explorer <= v9

IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).

Download it using nuget corsproxy and follow the included instructions.

Blog post | Source code

nodejs get file name from absolute path?

Use the basename method of the path module:

// returns

Here is the documentation the above example is taken from.

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

update the server arguments from -Dhttps.protocols=SSLv3 to -Dhttps.protocols=TLSv1,SSLv3

Upper memory limit?

No, there's no Python-specific limit on the memory usage of a Python application. I regularly work with Python applications that may use several gigabytes of memory. Most likely, your script actually uses more memory than available on the machine you're running on.

In that case, the solution is to rewrite the script to be more memory efficient, or to add more physical memory if the script is already optimized to minimize memory usage.


Your script reads the entire contents of your files into memory at once (line = u.readlines()). Since you're processing files up to 20 GB in size, you're going to get memory errors with that approach unless you have huge amounts of memory in your machine.

A better approach would be to read the files one line at a time:

for u in files:
     for line in u: # This will iterate over each line in the file
         # Read values from the line, do necessary calculations

Download File to server from URL

prodigitalson's answer didn't work for me. I got missing fopen in CURLOPT_FILE more details.

This worked for me, including local urls:

function downloadUrlToFile($url, $outFileName)
    if(is_file($url)) {
        copy($url, $outFileName); 
    } else {
        $options = array(
          CURLOPT_FILE    => fopen($outFileName, 'w'),
          CURLOPT_TIMEOUT =>  28800, // set this to 8 hours so we dont timeout on big files
          CURLOPT_URL     => $url

        $ch = curl_init();
        curl_setopt_array($ch, $options);

How to get row count in an Excel file using POI library?

Since Sheet.getPhysicalNumberOfRows() does not count empty rows and Sheet.getLastRowNum() returns 0 both if there is one row or no rows, I use a combination of the two methods to accurately calculate the total number of rows.

int rowTotal = sheet.getLastRowNum();

if ((rowTotal > 0) || (sheet.getPhysicalNumberOfRows() > 0)) {

Note: This will treat a spreadsheet with one empty row as having none but for most purposes this is probably okay.

How to read HDF5 files in Python

Use below code to data read and convert into numpy array

import h5py
f1 = h5py.File('data_1.h5', 'r')
X1 = f1['x']
df1= np.array(X1.value)
dfy1= np.array(y1.value)
print (df1.shape)
print (dfy1.shape)

Easiest way to copy a table from one database to another?

CREATE TABLE db1.table1 SELECT * FROM db2.table1

where db1 is the destination and db2 is the source

How can I change default dialog button text color in android 5

You can try to create the AlertDialog object first, and then use it to set up to change the color of the button and then show it. (Note that on builder object instead of calling show() we call create() to get the AlertDialog object:

//1. create a dialog object 'dialog'
MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage); 
AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialogInterface, int i) {


//2. now setup to change color of the button
dialog.setOnShowListener( new OnShowListener() {
    public void onShow(DialogInterface arg0) {

The reason you have to do it on onShow() and cannot just get that button after you create your dialog is that the button would not have been created yet.

I changed AlertDialog.BUTTON_POSITIVE to AlertDialog.BUTTON_NEGATIVE to reflect the change in your question. Although it is odd that "OK" button would be a negative button. Usually it is the positive button.

How to change a nullable column to not nullable in a Rails migration?

In Rails 4, this is a better (DRYer) solution:

change_column_null :my_models, :date_column, false

To ensure no records exist with NULL values in that column, you can pass a fourth parameter, which is the default value to use for records with NULL values:

change_column_null :my_models, :date_column, false,

How can I get the last day of the month in C#?

Something like:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);

Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.

How to get an object's property's value by property name?

Try this :

$obj = @{
    SomeProp = "Hello"

Write-Host "Property Value is $($obj."SomeProp")"

Positioning <div> element at center of screen

try this

<table style="height: 100%; left: 0; position: absolute; text-align: center; width: 100%;">
   <div style="text-align: left; display: inline-block;">
    Your Html code Here

Or this

<div style="height: 100%; left: 0; position: absolute; text-align: center; width: 100%; display: table">
 <div style="display: table-row">
  <div style="display: table-cell; vertical-align:middle;">
   <div style="text-align: left; display: inline-block;">
    Your Html code here

A top-like utility for monitoring CUDA activity on a GPU

To get real-time insight on used resources, do:

nvidia-smi -l 1

This will loop and call the view at every second.

If you do not want to keep past traces of the looped call in the console history, you can also do:

watch -n0.1 nvidia-smi

Where 0.1 is the time interval, in seconds.

enter image description here

Can't start Eclipse - Java was started but returned exit code=13

In my case, I have two different JDK that is IBM and Oracle JDK. I moved IBM JDK to the top of the Oracle JDK in environment variable then it worked. Note: I am going to use IBM JDK so I moved up.

Tried to Load Angular More Than Once

This happened to me too with .NET and MVC 5 and after a while I realized that within the label on Index.cshtml file:

<div data-ng-view=""></div>

again included as section scripts happens to you. To solve the problem on the server side what I do is return the partial view. Something like:

public class HomeController : Controller
    public ActionResult Index()
        return View();

    public ActionResult Login()
        return PartialView();

    public ActionResult About()
        return PartialView();

Pandas: sum DataFrame rows for given columns

If you have just a few columns to sum, you can write:

df['e'] = df['a'] + df['b'] + df['d']

This creates new column e with the values:

   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

For longer lists of columns, EdChum's answer is preferred.

How do you use a variable in a regular expression?

String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(replaceThis,"g"); 
   return this.replace(re, withThis);
var aa = "abab54..aba".replaceAll("\\.", "v");

Test with this tool

How to convert array to SimpleXML

function array_to_xml(array $arr, SimpleXMLElement $xml)
    foreach ($arr as $k => $v) {
            ? array_to_xml($v, $xml->addChild($k))
            : $xml->addChild($k, $v);
    return $xml;

$test_array = array (
    'bla' => 'blub',
    'foo' => 'bar',
    'another_array' => array (
        'stack' => 'overflow',

echo array_to_xml($test_array, new SimpleXMLElement('<root/>'))->asXML();

Count occurrences of a char in a string using Bash

awk works well if you your server has it

num=$(echo "${var}" | awk -F, '{print NF-1}')
echo "${num}"

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {


return m_Profiles.get(m_ActiveProfile);

PHP How to fix Notice: Undefined variable:

It looks like you don't have any records that match your query, so you'd want to return an empty array (or null or something) if the number of rows == 0.

Find the version of an installed npm package

Here's a portable Unix (using grep and sed) one-liner that returns the version string of a globally-installed npm package (remove the g from -pg to query local packages instead):

$ npm ll -pg --depth=0 grunt | grep -o "@.*:" | sed 's/.$//; s/^.//'
  • the npm ll outputs a parseable string formatted like: /usr/lib/node_modules/npm:[email protected]:;
  • the grep command extracts the value between @ and :, inclusive;
  • the sed command removes the surrounding characters.

How to know installed Oracle Client is 32 bit or 64 bit?

One thing that was super easy and worked well for me was doing a TNSPing from a cmd prompt:

TNS Ping Utility for 32-bit Windows: Version - Production on 13-MAR-2015 16:35:32

subtract time from date - moment js

I might be missing something in your question here... but from what I can gather, by using the subtract method this should be what you're looking to do:

var timeStr = "00:03:15";
    timeStr = timeStr.split(':');

var h = timeStr[1],
    m = timeStr[2];

var newTime = moment("01:20:00 06-26-2014")
    .subtract({'hours': h, 'minutes': m})

var str = h + " hours and " + m + " minutes earlier: " + newTime;

console.log(str); // 3 hours and 15 minutes earlier: 10:05

$(document).ready(function(){    _x000D_
     var timeStr = "00:03:15";_x000D_
        timeStr = timeStr.split(':');_x000D_
    var h = timeStr[1],_x000D_
        m = timeStr[2];_x000D_
    var newTime = moment("01:20:00 06-26-2014")_x000D_
        .subtract({'hours': h, 'minutes': m})_x000D_
    var str = h + " hours and " + m + " minutes earlier: " + newTime;_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<p id="new-time"></p>

What's the difference between select_related and prefetch_related in Django ORM?

As Django documentation says:


Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

More information about this:

SQL: how to use UNION and order by a specific select?

You want to do this:

select * from 
    SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
    SELECT id, 1 as ordered FROM b -- returns 2,1
order by ordered


I noticed that even though you have two different tables, you join the IDs, that means, if you have 1 in both tables, you are getting only one occurrence. If that's the desired behavior, you should stick to UNION. If not, change to UNION ALL.

So I also notice that if you change to the code I proposed, You would start getting both 1 and 2 (from both a and b). In that case, you might want to change the proposed code to:

select distinct id from 
    SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
    SELECT id, 1 as ordered FROM b -- returns 2,1
order by ordered

Install GD library and freetype on Linux

For CentOS: When installing php-gd you need to specify the version. I fixed it by running: sudo yum install php55-gd

Run/install/debug Android applications over Wi-Fi?

With new Android 11 you can debug your apps over WiFi without using an USB cable at all.

Quoting from Android Studio User Guide

Connect to a device over Wi-Fi (Android 11+)

Android 11 and higher support deploying and debugging your app wirelessly from your workstation using Android Debug Bridge (adb). For example, you can deploy your debuggable app to multiple remote devices without physically connecting your device via USB. This eliminates the need to deal with common USB connection issues, such as driver installation.

To use wireless debugging, you need to pair your device to your workstation using a pairing code. Your workstation and device must be connected to the same wireless network. To connect to your device, follow these steps:

  1. On your workstation, update to the latest version of the SDK Platform-Tools.
  2. On the device, enable developer options.
  3. Enable the Wireless debugging option.
  4. On the dialog that asks Allow wireless debugging on this network?, click Allow.
  5. Select Pair device with pairing code. Take note of the pairing code, IP address, and port number displayed on the device (see image).
  6. On your workstation, open a terminal and navigate to android_sdk/platform-tools.
  7. Run adb pair ipaddr:port. Use the IP address and port number from step 5.
  8. When prompted, enter the pairing code that you received in step 5. A message indicates that your device has been successfully paired.
    Enter pairing code: 482924
    Successfully paired to [guid=adb-235XY] 
  1. (For Linux or Microsoft Windows only) Run adb connect ipaddr:port. Use the IP address and port under Wireless debugging.

How to delete migration files in Rails 3

Side Note: Starting at rails 5.0.0 rake has been changed to rails So perform the following

rails db:migrate VERSION=0

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

How can I handle the warning of file_get_contents() function in PHP?

Enable allow_url_fopen From cPanel Or WHM then Try Hope it will Fix

scipy.misc module has no attribute imread?

For Python 3, it is best to use imread in matplotlib.pyplot:

from matplotlib.pyplot import imread

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron


yum install cronie

In both cases you get the same output:

 Package         Arch       Version         Repository      Size
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
Install       4 Package(s)

How to change the current URL in javascript?

This is more robust:

mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');

When the URL has multiple numbers, it will change the last one:

It supports numbers with leading zeros:


Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

It's quite simple... I'm sure that you all have a notebook or a PC at your home. So go to, sign in with your Google account and go to "Payment methods" and then to "Add Card or Account".

When you add the payment method, it's done! You will be able to buy your apps.

Slicing a dictionary

You should be iterating over the tuple and checking if the key is in the dict not the other way around, if you don't check if the key exists and it is not in the dict you are going to get a key error:

print({k:d[k] for k in l if k in d})

Some timings:

 {k:d[k] for k in set(d).intersection(l)}

In [22]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in l}
100 loops, best of 3: 11.5 ms per loop

In [23]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in set(d).intersection(l)}
10 loops, best of 3: 20.4 ms per loop

In [24]: %%timeit                        
l = xrange(100000)
l = set(l)                              
{key: d[key] for key in d.viewkeys() & l}
10 loops, best of 3: 24.7 ms per

In [25]: %%timeit                        

l = xrange(100000)
{k:d[k] for k in l if k in d}
100 loops, best of 3: 17.9 ms per loop

I don't see how {k:d[k] for k in l} is not readable or elegant and if all elements are in d then it is pretty efficient.

How do I remove lines between ListViews on Android?

  1. If you want to remove a divider line, use this code:

  2. If you want to add a space instead of a divider line:


So, you can use any drawable or color in the divider attribute.

How to set $_GET variable

If you want to fake a $_GET (or a $_POST) when including a file, you can use it like you would use any other var, like that:

$_GET['key'] = 'any get value you want';

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

This is an IndexError in python, which means that we're trying to access an index which isn't there in the tensor. Below is a very simple example to understand this error.

# create an empty array of dimension `0`
In [14]: arr = np.array([], dtype=np.int64) 

# check its shape      
In [15]: arr.shape  
Out[15]: (0,)

with this array arr in place, if we now try to assign any value to some index, for example to the index 0 as in the case below

In [16]: arr[0] = 23     

Then, we will get an IndexError, as below:

IndexError                                Traceback (most recent call last)
<ipython-input-16-0891244a3c59> in <module>
----> 1 arr[0] = 23

IndexError: index 0 is out of bounds for axis 0 with size 0

The reason is that we are trying to access an index (here at 0th position), which is not there (i.e. it doesn't exist because we have an array of size 0).

In [19]: arr.size * arr.itemsize  
Out[19]: 0

So, in essence, such an array is useless and cannot be used for storing anything. Thus, in your code, you've to follow the traceback and look for the place where you're creating an array/tensor of size 0 and fix that.

Direct method from SQL command text to DataSet

public static string textDataSource = "Data Source=localhost;Initial Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";

public static DataSet LoaderDataSet(string StrSql)      
    SqlConnection cnn;            
    SqlDataAdapter dad;
    DataSet dts = new DataSet();
    cnn = new SqlConnection(textDataSource);
    dad = new SqlDataAdapter(StrSql, cnn);

        return dts;
    catch (Exception)

        return dts;
        dts = null;
        cnn = null;

currently unable to handle this request HTTP ERROR 500

My take on this for future people watching this:

This could also happen if you're using: <? instead of <?php.

How do I detect if I am in release or debug mode?

The simplest, and best long-term solution, is to use BuildConfig.DEBUG. This is a boolean value that will be true for a debug build, false otherwise:

if (BuildConfig.DEBUG) {
  // do something for a debug build

There have been reports that this value is not 100% reliable from Eclipse-based builds, though I personally have not encountered a problem, so I cannot say how much of an issue it really is.

If you are using Android Studio, or if you are using Gradle from the command line, you can add your own stuff to BuildConfig or otherwise tweak the debug and release build types to help distinguish these situations at runtime.

The solution from Illegal Argument is based on the value of the android:debuggable flag in the manifest. If that is how you wish to distinguish a "debug" build from a "release" build, then by definition, that's the best solution. However, bear in mind that going forward, the debuggable flag is really an independent concept from what Gradle/Android Studio consider a "debug" build to be. Any build type can elect to set the debuggable flag to whatever value that makes sense for that developer and for that build type.

Named colors in matplotlib

To get a full list of colors to use in plots:

import matplotlib.colors as colors
colors_list = list(colors._colors_full_map.values())

So, you can use in that way quickly:

scatter(X,Y, color=colors_list[0])
scatter(X,Y, color=colors_list[1])
scatter(X,Y, color=colors_list[2])
scatter(X,Y, color=colors_list[-1])

An unhandled exception was generated during the execution of the current web request

In my case, I created a new project and when I ran it the first time, it gave me the following error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package

Problem solved!!

Query to get the names of all tables in SQL Server 2008 Database

Try this:

SELECT s.NAME + '.' + t.NAME AS TableName
FROM sys.tables t
INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id

it will display the schema+table name for all tables in the current database.

Here is a version that will list every table in every database on the current server. it allows a search parameter to be used on any part or parts of the server+database+schema+table names:

DECLARE @AllTables table (CompleteTableName nvarchar(4000))
DECLARE @Search nvarchar(4000)
       ,@SQL   nvarchar(4000)
SET @Search=null --all rows
SET @SQL='select @@SERVERNAME+''.''+''?''+''.''''.'' from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE @@SERVERNAME+''.''+''?''+''.''''.'' LIKE ''%'+ISNULL(@SEARCH,'')+'%'''

INSERT INTO @AllTables (CompleteTableName)
    EXEC sp_msforeachdb @SQL

set @Search to NULL for all tables, set it to things like 'dbo.users' or 'users' or '.master.dbo' or even include wildcards like '.master.%.u', etc.

How to parse JSON Array (Not Json Object) in Android

Create a class to hold the objects.

public class Person{
   private String name;
   private String url;
   //Get & Set methods for each field

Then deserialize as follows:

Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String

Reference Article:

Python Request Post with param data

Assign the response to a value and test the attributes of it. These should tell you something useful.

response =,params=data,headers=headers)
  • status_code should just reconfirm the code you were given before, of course

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

The Issue

The error presents itself as a message similar to this:

Cannot open database "DATABASE NAME" requested by the login. The login failed. Login failed for user XYZ.

  • The error cannot usually be rectified by a simple Visual Studio or full-computer restart.
  • The error can also be found as a seemingly locked database file.

The Fix

The solution is laid in the following steps. You will not lose any data in your database and you should not delete your database file!

Pre-requisite: You must have installed SQL Server Management Studio (Full or Express)

  1. Open SQL Server Management Studio
  2. In the "Connect to Server" window (File->Connect object explorer) enter the following:
    • Server type : Database Engine
    • Server name : (localdb)\v11.0
    • Authentication : [Whatever you used when you created your local db. Probably Windows Authentication).
  3. Click "Connect"
  4. Expand the "Databases" folder in the Object Explorer (View->Object Explorer, F8)
  5. Find your database. It should be named as the full path to your database (.mdf) file
    • You should see it says "(Pending Recovery)" at the end of the database name or when you try to expand the database it won't be able to and may or may not give you an error message.
    • This the issue! Your database has crashed essentially..
  6. Right click on the database then select "Tasks -> Detach...".
  7. In the detach window, select your database in the list and check the column that says "Drop Connections"
  8. Click OK.
  9. You should see the database disappear from the list of databases. Your problem should now be fixed. Go and run your application that uses your localdb.
  10. After running your application, your database will re-appear in the list of databases - this is correct. It should not say "Pending recovery" any more since it should be working properly.

The source of the solution:

Mean per group in a data.frame

You can also accomplish this using the sqldf package as shown below:


x <- read.table(text='Name     Month  Rate1     Rate2
Aira       1      12        23
                Aira       2      18        73
                Aira       3      19        45
                Ben        1      53        19
                Ben        2      22        87
                Ben        3      19        45
                Cat        1      22        87
                Cat        2      67        43
                Cat        3      45        32', header=TRUE)

  ,avg(Rate1) as Rate1_float
  ,avg(Rate2) as Rate2_float
  ,avg(Rate1) as Rate1
  ,avg(Rate2) as Rate2
from x
group by 

#  Name Rate1_float Rate2_float Rate1 Rate2
#1 Aira    16.33333    47.00000    16    47
#2  Ben    31.33333    50.33333    31    50
#3  Cat    44.66667    54.00000    44    54

I am a recent convert to dplyr as shown in other answers, but sqldf is nice as most data analysts/data scientists/developers have at least some fluency in SQL. In this way, I think it tends to make for more universally readable code than dplyr or other solutions presented above.

UPDATE: In responding to the comment below, I attempted to update the code as shown above. However, the behavior was not as I expected. It seems that the column definition (i.e. int vs float) is only carried through when the column alias matches the original column name. When you specify a new name, the aggregate column is returned without rounding.

The request was aborted: Could not create SSL/TLS secure channel

None of the answers worked for me.

This is what worked:

Instead of initializing my X509Certifiacte2 like this:

   var certificate = new X509Certificate2(bytes, pass);

I did it like this:

   var certificate = new X509Certificate2(bytes, pass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

Notice the X509KeyStorageFlags.Exportable !!

I didn't change the rest of the code (the WebRequest itself):

// I'm not even sure the first two lines are necessary:
ServicePointManager.Expect100Continue = true; 
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

request = (HttpWebRequest)WebRequest.Create(string.Format("https://{0}", server));
request.Method = "GET";
request.Referer = string.Format("{0}", servidor);
request.UserAgent = "Mozilla/4.0";
request.CookieContainer = new CookieContainer();

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    // etc...

In fact I'm not even sure that the first two lines are necessary...

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:

In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:

The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.

So Hibernate as well behaves like Ashish Agarwal stated above for JPA:

OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY

(see JPA 2.1 Spec)

bootstrap 3 - how do I place the brand in the center of the navbar?


.navbar-header {
    float: left;
    padding: 15px;
    text-align: center;
    width: 100%;
.navbar-brand {float:none;}


<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <a class="navbar-brand" href="#">Brand</a>

string decode utf-8

Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?

Truncating Text in PHP?


// truncate to 4 chars

echo substr(str_pad($text,4),0,4);

This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)

The performance impact of using instanceof in Java

I'll get back to you on instanceof performance. But a way to avoid problem (or lack thereof) altogether would be to create a parent interface to all the subclasses on which you need to do instanceof. The interface will be a super set of all the methods in sub-classes for which you need to do instanceof check. Where a method does not apply to a specific sub-class, simply provide a dummy implementation of this method. If I didn't misunderstand the issue, this is how I've gotten around the problem in the past.

How to Set Focus on JTextField?

if is there only one Top-Level Container then last lines in GUI constructor would be for example

EventQueue.invokeLater(new Runnable() {

     public void run() {
         myComponent.requestFocus();//or inWindow

Difference between a script and a program?

There are really two dimensions to the scripting vs program reality:

  1. Is the language powerful enough, particularly with string operations, to compete with a macro processor like the posix shell and particularly bash? If it isn't better than bash for running some function there isn't much point in using it.

  2. Is the language convenient and quickly started? Java, Scala, JRuby, Closure and Groovy are all powerful languages, but Java requires a lot of boilerplate and the JVM they all require just takes too long to start up.

OTOH, Perl, Python, and Ruby all start up quickly and have powerful string handling (and pretty much everything-else-handling) operations, so they tend to occupy the sometimes-disparaged-but-not-easily-encroached-upon "scripting" world. It turns out they do well at running entire traditional programs as well.

Left in limbo are languages like Javascript, which aren't used for scripting but potentially could be. Update: since this was written node.js was released on multiple platforms. In other news, the question was closed. "Oh well."

Add empty columns to a dataframe with specified names from a vector


df <-"cbind", list(df, rep(list(NA),length(namevector))))
colnames(df)[-1*(1:(ncol(df) - length(namevector)))] <- namevector

React component not re-rendering on state change

Another oh-so-easy mistake, which was the source of the problem for me: I’d written my own shouldComponentUpdate method, which didn’t check the new state change I’d added.

Signed to unsigned conversion in C - is it always safe?

Short Answer

Your i will be converted to an unsigned integer by adding UINT_MAX + 1, then the addition will be carried out with the unsigned values, resulting in a large result (depending on the values of u and i).

Long Answer

According to the C99 Standard: Usual arithmetic conversions

  1. If both operands have the same type, then no further conversion is needed.
  2. Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
  3. Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
  4. Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
  5. Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

In your case, we have one unsigned int (u) and signed int (i). Referring to (3) above, since both operands have the same rank, your i will need to be converted to an unsigned integer. Signed and unsigned integers

  1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
  2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
  3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

Now we need to refer to (2) above. Your i will be converted to an unsigned value by adding UINT_MAX + 1. So the result will depend on how UINT_MAX is defined on your implementation. It will be large, but it will not overflow, because:

6.2.5 (9)

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

Bonus: Arithmetic Conversion Semi-WTF

#include <stdio.h>

int main(void)
  unsigned int plus_one = 1;
  int minus_one = -1;

  if(plus_one < minus_one)
    printf("1 < -1");

  return 0;

You can use this link to try this online:

Bonus: Arithmetic Conversion Side Effect

Arithmetic conversion rules can be used to get the value of UINT_MAX by initializing an unsigned value to -1, ie:

unsigned int umax = -1; // umax set to UINT_MAX

This is guaranteed to be portable regardless of the signed number representation of the system because of the conversion rules described above. See this SO question for more information: Is it safe to use -1 to set all bits to true?

PHP Convert String into Float/Double

Surprisingly there is no accepted answer. The issue only exists in 32-bit PHP.

From the documentation,

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

In other words, the $string is first interpreted as INT, which cause overflow (The $string value 2968789218 exceeds the maximum value (PHP_INT_MAX) of 32-bit PHP, which is 2147483647.), then evaluated to float by (float) or floatval().

Thus, the solution is:

$string = "2968789218";
echo 'Original: ' . floatval($string) . PHP_EOL;
$string.= ".0";
$float = floatval($string);
echo 'Corrected: ' . $float . PHP_EOL;

which outputs:

Original: 2.00
Corrected: 2968789218

To check whether your PHP is 32-bit or 64-bit, you can:


If your PHP is 64-bit, it will print out 9223372036854775807, otherwise it will print out 2147483647.

How to get resources directory path programmatically

Just use class. Example:

 URL url = Resources.getResource("file name")

After that you have methods like: .getContent(), .getFile(), .getPath() etc

How to get $HOME directory of different user in bash script?

I was struggling with this question because I was looking for a way to do this in a bash script for OS X, hence /etc/passwd was out of the question, and my script was meant to be executed as root, therefore making the solutions invoking eval or bash -c dangerous as they allowed code injection into the variable specifying the username.

Here is what I found. It's simple and doesn't put a variable inside a subshell. However it does require the script to be ran by root as it sudos into the specified user account.

Presuming that $SOMEUSER contains a valid username:

echo "$(sudo -H -u "$SOMEUSER" -s -- "cd ~ && pwd")"

I hope this helps somebody!

Hibernate SessionFactory vs. JPA EntityManagerFactory

SessionFactory vs. EntityManagerFactory

As I explained in the Hibernate User Guide, the Hibernate SessionFactory extends the JPA EntityManagerFactory, as illustrated by the following diagram:

JPA and Hibernate relationship

So, the SessionFactory is also a JPA EntityManagerFactory.

Both the SessionFactory and the EntityManagerFactory contain the entity mapping metadata and allow you to create a Hibernate Session or a EntityManager.

Session vs. EntityManager

Just like the SessionFactory and EntityManagerFactory, the Hibernate Session extends the JPA EntityManager. So, all methods defined by the EntityManager are available in the Hibernate Session.

The Session and the `EntityManager translate entity state transitions into SQL statements, like SELECT, INSERT, UPDATE, and DELETE.

Hibernate vs. JPA bootstrap

When bootstrapping a JPA or Hibernate application, you have two choices:

  1. You can bootstrap via the Hibernate native mechanism, and create a SessionFactory via the BootstrapServiceRegistryBuilder. If you're using Spring, the Hibernate bootstrap is done via the LocalSessionFactoryBean, as illustrated by this GitHub example.
  2. Or, you can create a JPA EntityManagerFactory via the Persistence class or the EntityManagerFactoryBuilder. If you're using Spring, the JPA bootstrap is done via the LocalContainerEntityManagerFactoryBean, as illustrated by this GitHub example.

Bootstrapping via JPA is to be preferred. That's because the JPA FlushModeType.AUTO is a much better choice than the legacy FlushMode.AUTO, which breaks read-your-writes consistency for native SQL queries.

Unwrapping JPA to Hibernate

Also, if you bootstrap via JPA, and you have injected the EntityManagerFactory via the @PersistenceUnit annotation:

private EntityManagerFactory entityManagerFactory;

You can easily get access to the underlying Sessionfactory using the unwrap method:

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

The same can be done with the JPA EntityManager. If you inject the EntityManager via the @PersistenceContext annotation:

private EntityManager entityManager;

You can easily get access to the underlying Session using the unwrap method:

Session session = entityManager.unwrap(Session.class);


So, you should bootstrap via JPA, use the EntityManagerFactory and EntityManager, and only unwrap those to their associated Hibernate interfaces when you want to get access to some Hibernate-specific methods that are not available in JPA, like fetching the entity via its natural identifier.

SQL Server: Error converting data type nvarchar to numeric

I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT function on the nvarchar field.

Example: Left(Field,4)

Basically, the query will look like:

Select convert(float,left(Field,4)) from TABLE

Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.

Using intents to pass data between activities

Pass the data from Activity-1 to AndroidTabRes.. as below:

At sending activity...

Intent intent = new Intent(current.this, AndroidTabRestaurantDescSearchListView.class);

At AndroidTabRes.. activity...

  String data = getIntent().getExtras().getString("keyName");

Thus you can have data at receiving activity from sending activity...

And in your AndroidTabRestaurantDescSearchListView class, do this:

String value= getIntent().getStringExtra("keyName");

Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);
intent.putExtra("keyName", value);

Then in your RatingDescriptionSearchActivity class, do this:

 String data= getIntent().getStringExtra("keyName");

Find all files in a directory with extension .txt in Python

I did a test (Python 3.6.4, W7x64) to see which solution is the fastest for one folder, no subdirectories, to get a list of complete file paths for files with a specific extension.

To make it short, for this task os.listdir() is the fastest and is 1.7x as fast as the next best: os.walk() (with a break!), 2.7x as fast as pathlib, 3.2x faster than os.scandir() and 3.3x faster than glob.
Please keep in mind, that those results will change when you need recursive results. If you copy/paste one method below, please add a .lower() otherwise .EXT would not be found when searching for .ext.

import os
import pathlib
import timeit
import glob

def a():
    path = pathlib.Path().cwd()
    list_sqlite_files = [str(f) for f in path.glob("*.sqlite")]

def b(): 
    path = os.getcwd()
    list_sqlite_files = [f.path for f in os.scandir(path) if os.path.splitext(f)[1] == ".sqlite"]

def c():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith(".sqlite")]

def d():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob("*.sqlite")]

def e():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob1(str(path), "*.sqlite")]

def f():
    path = os.getcwd()
    list_sqlite_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".sqlite"):
                list_sqlite_files.append( os.path.join(root, file) )

print(timeit.timeit(a, number=1000))
print(timeit.timeit(b, number=1000))
print(timeit.timeit(c, number=1000))
print(timeit.timeit(d, number=1000))
print(timeit.timeit(e, number=1000))
print(timeit.timeit(f, number=1000))


# Python 3.6.4

Stack array using pop() and push()

Here is an example of implementing stack in java (Array Based implementation):

public class MyStack extends Throwable{

private static final long serialVersionUID = -4433344892390700337L;

protected static int top = -1;
protected static int capacity;
protected static int size;

public int stackDatas[] = null;

public MyStack(){
    stackDatas = new int[10];
    capacity = stackDatas.length;

public static int size(){

    if(top < 0){
        size = top + 1;
        return size;
    size = top+1;
    return size; 

public void push(int data){
    if(capacity == size()){
        System.out.println("no memory");
        stackDatas[++top] = data;

public boolean topData(){
    if(top < 0){
        return true;
        return false;

public void pop(){
    if(top < 0){
        System.out.println("stack is empty");
        int temp = stackDatas[top];
        stackDatas = ArrayUtils.remove(stackDatas, top--);
        System.out.println("poped data---> "+temp);

public String toString(){
    String result = "[";

        return "[]";

    for(int i = 0; i< size(); i++){
        result = result + stackDatas[i] +",";

    return result.substring(0, result.lastIndexOf(",")) +"]";

calling MyStack:

    public class CallingMyStack {

public static MyStack ms;

public static void main(String[] args) {

    ms = new MyStack();
    System.out.println("size: "+MyStack.size());
    System.out.println("List---> "+ms);
    System.out.println("List---> "+ms);
    System.out.println("size: "+MyStack.size());



size: 10
List---> [1,2,3,4,5,6,7,8,9,10]
poped data---> 10
poped data---> 9
poped data---> 8
poped data---> 7
List---> [1,2,3,4,5,6]
size: 6

How to list all files in a directory and its subdirectories in hadoop hdfs

Have you tried this:

import java.util.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;

public class cat{
    public static void main (String [] args) throws Exception{
            FileSystem fs = FileSystem.get(new Configuration());
            FileStatus[] status = fs.listStatus(new Path("hdfs://"));  // you need to pass in your hdfs path

            for (int i=0;i<status.length;i++){
                BufferedReader br=new BufferedReader(new InputStreamReader([i].getPath())));
                String line;
                while (line != null){
        }catch(Exception e){
            System.out.println("File not found");

What is a handle in C++?

In C++/CLI, a handle is a pointer to an object located on the GC heap. Creating an object on the (unmanaged) C++ heap is achieved using new and the result of a new expression is a "normal" pointer. A managed object is allocated on the GC (managed) heap with a gcnew expression. The result will be a handle. You can't do pointer arithmetic on handles. You don't free handles. The GC will take care of them. Also, the GC is free to relocate objects on the managed heap and update the handles to point to the new locations while the program is running.

How to update multiple columns in single update statement in DB2

The update statement in all versions of SQL looks like:

update table
    set col1 = expr1,
        col2 = expr2,
        . . .
        coln = exprn
    where some condition

So, the answer is that you separate the assignments using commas and don't repeat the set statement.

What does the colon (:) operator do?

Since most for loops are very similar, Java provides a shortcut to reduce the amount of code required to write the loop called the for each loop.

Here is an example of the concise for each loop:

for (Integer grade : quizGrades){

In the example above, the colon (:) can be read as "in". The for each loop altogether can be read as "for each Integer element (called grade) in quizGrades, print out the value of grade."

Using helpers in model: how do I include helper dependencies?

Just change the first line as follows :

include ActionView::Helpers

that will make it works.

UPDATE: For Rails 3 use:


Credit goes to lornc's answer

Setting Remote Webdriver to run tests in a remote computer using Java

This issue came for me due to the fact that .. i was running server with selenium-server-standalone-2.32.0 and client registered with selenium-server-standalone-2.37.0 .. When i made both selenium-server-standalone-2.32.0 and ran then things worked fine

How to split (chunk) a Ruby array into parts of X elements?

If you're using rails you can also use in_groups_of:


TypeError: 'NoneType' object has no attribute '__getitem__'

The function move.CompleteMove(events) that you use within your class probably doesn't contain a return statement. So nothing is returned to self.values (==> None). Use return in move.CompleteMove(events) to return whatever you want to store in self.values and it should work. Hope this helps.

SQL Views - no variables?

How often do you need to refresh the view? I have a similar case where the new data comes once a month; then I have to load it, and during the loading processes I have to create new tables. At that moment I alter my view to consider the changes. I used as base the information in this other question:

Create View Dynamically & synonyms

In there, it is proposed to do it 2 ways:

  1. using synonyms.
  2. Using dynamic SQL to create view (this is what helped me achieve my result).

Android: Changing Background-Color of the Activity (Main View)

Try creating a method in your Activity something like...

public void setActivityBackgroundColor(int color) {
    View view = this.getWindow().getDecorView();

Then call it from your OnClickListener passing in whatever colour you want.

Chrome DevTools Devices does not detect device when plugged in

I have been using this tool for years on different computers and with different devices. I often found that chrome / ADT does not see my device.

In this case only thing that works for me is to reset ADB deamon:

adb kill-server

or / and

adb usb

After you re-plug your device a message will be shown on your device asking you to allow USB debugging from the computer connected. It's really important that this request be allowed.

R numbers from 1 to 100

If you need the construct for a quick example to play with, use the : operator.

But if you are creating a vector/range of numbers dynamically, then use seq() instead.

Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.

In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,

seq(a, b, -1)

will raise an error for a=2, b=6, because the coder expected a decreasing sequence.

Conditional formatting, entire row based

In my case I wanted to compare values in cells of column E with Cells in Column G

Highlight the selection of cells to be checked in column E.

Select Conditional Format: Highlight cell rules Select one of the choices in my case it was greater than. In the left hand field of pop up use =indirect("g"&row()) where g was the row I was comparing against.

Now the row you are formatting will highlight based on if it is greater than the selection in row G

This works for every cell in Column E compared to cell in Column G of the selection you made for column E.

If G2 is greater than E2 it formats

G3 is greater than E3 it formats etc

Git error on git pull (unable to update local ref)

I had the same error, I was updating from within Eclipse and I got many errors. So I tried updating from a DOS command window, and got the same issue.

Then I tried the solution " git gc --prune=now " This gave messages that the files were locked in the refs directory.

Eclipse must have had a locked on something in the "refs" directory.
The solution I found was to simply close Eclipse. Then I updated the repository from DOS with a " git PULL " command, and everything worked fine.

How do I run a VBScript in 32-bit mode on a 64-bit machine?

Alternate method to run 32-bit scripts on 64-bit machine: %windir%\syswow64\cscript.exe vbscriptfile.vbs

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays. Just replace the line raising an error with:

m = np.log10(np.abs(x))

Apart from that the np.polyfit() call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

This expands on a previous answer. The best solution I've found is to make an innocuous CSS attribute that only appears if a CSS3 media query is met, and then have the JS test for that attribute.

So for instance, in the CSS you'd have:

@media screen only and (orientation:landscape)
    //  Some innocuous rule here
        background-color: #fffffe;
@media screen only and (orientation:portrait)
    //  Some innocuous rule here
        background-color: #fffeff;

You then go to JavaScript (I'm using jQuery for funsies). Color declarations may be weird, so you may want to use something else, but this is the most foolproof method I've found for testing it. You can then just use the resize event to pick up on switching. Put it all together for:

function detectOrientation(){
    //  Referencing the CSS rules here.
    //  Change your attributes and values to match what you have set up.
    var bodyColor = $("body").css("background-color");
    if (bodyColor == "#fffffe") {
        return "landscape";
    } else
    if (bodyColor == "#fffeff") {
        return "portrait";
    var orientation = detectOrientation();
    alert("Your orientation is " + orientation + "!");
        orientation = detectOrientation();
        alert("Your orientation is " + orientation + "!");

The best part of this is that as of my writing this answer, it doesn't appear to have any effect on desktop interfaces, since they (generally) don't (seem to) pass any argument for orientation to the page.

how to use XPath with XDocument?

XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); 
xnm.AddNamespace("x", "");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);

Run PHP Task Asynchronously

Another way to fork processes is via curl. You can set up your internal tasks as a webservice. For example:

Then in your user accessed scripts make calls to the service:

$service->addTask('t1', $data); // post data to URL via curl

Your service can keep track of the queue of tasks with mysql or whatever you like the point is: it's all wrapped up within the service and your script is just consuming URLs. This frees you up to move the service to another machine/server if necessary (ie easily scalable).

Adding http authorization or a custom authorization scheme (like Amazon's web services) lets you open up your tasks to be consumed by other people/services (if you want) and you could take it further and add a monitoring service on top to keep track of queue and task status.

It does take a bit of set-up work but there are a lot of benefits.

jquery select element by xpath

document.evaluate() (DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: (moved into a plugin in the current jQuery version, see It simply converts XPath expressions into equivalent CSS selectors however.

How to $http Synchronous call with AngularJS

What about wrapping your call in a Promise.all() method i.e.

Promise.all([$http.get(url).then(function(result){....}, function(error){....}])

According to MDN

Promise.all waits for all fulfillments (or the first rejection)

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

In case anyone else has the same issue as this on

Centos, try:

yum install python-lxml


sudo apt-get install -y python-lxml

worked for me.

error: (-215) !empty() in function detectMultiScale

If you are using Anaconda you should add the Anaconda path.

new_path = 'C:/Users/.../Anaconda/Library/etc/haarcascades/'

face_cascade = cv2.CascadeClassifier(new_path + 'haarcascade_frontalface_default.xml')

Percentage calculation

Mathematically, to get percentage from two numbers:

percentage = (yourNumber / totalNumber) * 100;

And also, to calculate from a percentage :

number = (percentage / 100) * totalNumber;

Fatal error: Call to undefined function mysqli_connect()

So this may not be the issue for you, but I was struggling with this error. I discovered what was causing my problem, though I can't really explain as to why.

For me, mysqli_connect was working fine where the connection was made on pages in any various sub-directory. For some reason though, the same code referenced on pages in the root directory was returning this error. The strange thing is that it was working fine on my localhost environment in MAMP in the root directory, however on my shared host it was not.

After struggling to figure out what was giving me "Error 500" white screen from this "PHP Fatal Error," I went through the code and stumbled upon this code in the error handling that was suggested by the PHP Manual (

if (!mysqli_query($link, "SET a=1")) {
    printf("Error message: %s\n", mysqli_error($link));

I randomly decided to remove it and, voila, connection to the database working in root directories. Maybe someone smarter than me can explain this, for anyone struggling with a similar issue.

How to save password when using Subversion from the console

Try clearing your .subversion folder in your home directory and try to commit again. It should prompt you for your password and then ask you if you would like to save the password.

Why doesn't JavaScript support multithreading?

JavaScript multi-threading (with some limitations) is here. Google implemented workers for Gears, and workers are being included with HTML5. Most browsers have already added support for this feature.

Thread-safety of data is guaranteed because all data communicated to/from the worker is serialized/copied.

For more info, read:

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

Tested in IE9, and latest Firefox and Chrome and also supported in IE8.

document.onreadystatechange = function () {
  var state = document.readyState;
  if (state == 'interactive') {
  } else if (state == 'complete') {


UPDATE - reusable version

I have just developed the following. It's a rather simplistic equivalent to jQuery or Dom ready without backwards compatibility. It probably needs further refinement. Tested in latest versions of Chrome, Firefox and IE (10/11) and should work in older browsers as commented on. I'll update if I find any issues.

window.readyHandlers = [];
window.ready = function ready(handler) {

window.handleState = function handleState () {
  if (['interactive', 'complete'].indexOf(document.readyState) > -1) {
    while(window.readyHandlers.length > 0) {

document.onreadystatechange = window.handleState;


ready(function () {
  // your code here

It's written to handle async loading of JS but you might want to sync load this script first unless you're minifying. I've found it useful in development.

Modern browsers also support async loading of scripts which further enhances the experience. Support for async means multiple scripts can be downloaded simultaneously all while still rendering the page. Just watch out when depending on other scripts loaded asynchronously or use a minifier or something like browserify to handle dependencies.

Mysql where id is in array

Your query translates to:

SELECT name FROM users WHERE id IN ('Array');

Or something to that affect.

Try using prepared queries instead, something like:

$numbers = explode(',', $string);
$prepare = array_map(function(){ return '?'; }, $numbers);
$statement = mysqli_prepare($link , "SELECT name FROM users WHERE id IN ('".implode(',', $prepare)."')");
if($statement) {
   $ints = array_map(function(){ return 'i'; }, $numbers);
   call_user_func_array("mysqli_stmt_bind_param", array_merge(
      array($statement, implode('', $ints)), $numbers
   $results = mysqli_stmt_execute($statement);
   // do something with results 
   // ...

Insert HTML from CSS

Content (for text and not html):

But just to be clear, it is bad practice. Its support throughout browsers is shaky, and it's generally not a good idea. But in cases where you really have to use it, there it is.

How to check if a string contains a specific text

Do mean to check if $a is a non-empty string? So that it contains just any text? Then the following will work.

If $a contains a string, you can use the following:

if (!empty($a)) {      // Means: if not empty

If you also need to confirm that $a is actually a string, use:

if (is_string($a) && !empty($a)) {      // Means: if $a is a string and not empty

Directory-tree listing in Python

If figured I'd throw this in. Simple and dirty way to do wildcard searches.

import re
import os

[a for a in os.listdir(".") if"^.*\.py$",a)]

Accessing a value in a tuple that is in a list

a = [(0,2), (4,3), (9,9), (10,-1)]
print(list(map(lambda item: item[1], a)))

Xcode 4 - "Archive" is greyed out?

I fixed this today...sort of. Although the archives still don't show up anywhere. But I got the Archive option back by going into Build Settings for the project and re-assigning my certs under "Code Signing Identity" for each build. They seemed to have gotten reset to something else when imported my 3.X project to 4.

I also used the instructions found here:

But I still can't get the actual archives to show up in Organizer (even though the files exist)

Angular: date filter adds timezone, how to output UTC?

Since version 1.3.0 AngularJS introduced extra filter parameter timezone, like following:

{{ date_expression | date : format : timezone}}

But in versions 1.3.x only supported timezone is UTC, which can be used as following:

{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}

Since version 1.4.0-rc.0 AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):

{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}

Here you can find documentation of AngularJS date filters.

NOTE: this is working only with Angular 1.x

Here's working example

What is the difference between attribute and property?

What is the difference between Attribute and Property?
What is the difference between Feature and Function? What is the difference between Characteristic and Character? What is the difference between Act and Behavior?

Its just a change in context.


A Person Acts in a Behavior. A Personality has Characteristics of a given Character. A Product has Feature that derive Functionality. An Object had Attributes that give it Properties.

How to debug "ImagePullBackOff"?

Have you tried to edit to see what's wrong (I had the wrong image location)

kubectl edit pods arix-3-yjq9w

or even delete your pod?

kubectl delete arix-3-yjq9w

Mocking methods of local scope objects with Mockito

You can do this by creating a factory method in MyObject:

class MyObject {
    public static MyObject create() {
      return new MyObject();

then mock that with PowerMock.

However, by mocking the methods of a local scope object, you are depending on that part of the implementation of the method staying the same. So you lose the ability to refactor that part of the method without breaking the test. In addition, if you are stubbing return values in the mock, then your unit test may pass, but the method may behave unexpectedly when using the real object.

In sum, you should probably not try to do this. Rather, letting the test drive your code (aka TDD), you would arrive at a solution like:

void method1(MyObject obj1) {

passing in the dependency, which you can easily mock for the unit test.

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>

This app won't run unless you update Google Play Services (via Bazaar)

I have found a nice solution which let you test your app in the emulator and also doesn't require you to revert to the older version of the library. See an answer to Stack Overflow question Running Google Maps v2 on the Android emulator.

What is the difference between CSS and SCSS?

css has variables as well. You can use them like this:

--primaryColor: #ffffff;
--width: 800px;

body {
    width: var(--width);
    color: var(--primaryColor);
    width: var(--width);
    background: var(--primaryColor);

Connecting PostgreSQL 9.2.1 with Hibernate

This is the hibernate.cfg.xml file to connect postgresql 9.5 and this is help to you basic configuration.

 <?xml version='1.0' encoding='utf-8'?>

  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <>.
<!DOCTYPE hibernate-configuration SYSTEM
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://localhost:5433/hibernatedb</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">password</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="">create</property>
        <mapping class="com.waseem.UserDetails"/>

Make sure File Location should be under src/main/resources/hibernate.cfg.xml

Create Excel files from C# without office

If you're interested in making .xlsx (Office 2007 and beyond) files, you're in luck. Office 2007+ uses OpenXML which for lack of a more apt description is XML files inside of a zip named .xlsx

Take an excel file (2007+) and rename it to .zip, you can open it up and take a look. If you're using .NET 3.5 you can use the System.IO.Packaging library to manipulate the relationships & zipfile itself, and linq to xml to play with the xml (or just DOM if you're more comfortable).

Otherwise id reccomend DotNetZip, a powerfull library for manipulation of zipfiles.

OpenXMLDeveloper has lots of resources about OpenXML and you can find more there.

If you want .xls (2003 and below) you're going to have to look into 3rd party libraries or perhaps learn the file format yourself to achieve this without excel installed.

VBA: How to display an error message just like the standard error message which has a "Debug" button?

For Me I just wanted to see the error in my VBA application so in the function I created the below code..

Function Database_FileRpt
On Error GoTo CleanFail
' Create_DailyReport_Action and code



MsgBox "********************" _

& vbCrLf & "Err.Number: " & Err.Number _

& vbCrLf & "Err.Description: " & Err.Description _

& vbCrLf & "Err.Source: " & Err.Source _

& vbCrLf & "********************" _

& vbCrLf & "...Exiting VBA Function: Database_FileRpt" _

& vbCrLf & "...Excel VBA Program Reset." _

, , "VBA Error Exception Raised!"


 ' Note that the next line will reset the error object to 0, the variables 
above are used to remember the values
' so that the same error can be re-raised


' *************************************

Resume CleanExit


'cleanup code , if any, goes here. runs regardless of error state.

Exit Function  ' SUB  or Function    

End Function  ' end of Database_FileRpt

' ------------------

How much data can a List can hold at the maximum?

Numbering an items in the java array should start from zero. This was i think we can have access to Integer.MAX_VALUE+1 an items.

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

Are you missing any maven build.

Apart from above JRE changes.I still faced similar issue.I was missing JUnit dependency after adding it is working fine.

Hope this will help.

What's the difference between unit tests and integration tests?

A unit test should have no dependencies on code outside the unit tested. You decide what the unit is by looking for the smallest testable part. Where there are dependencies they should be replaced by false objects. Mocks, stubs .. The tests execution thread starts and ends within the smallest testable unit.

When false objects are replaced by real objects and tests execution thread crosses into other testable units, you have an integration test

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

I had a similar problem. VS 2015 Community (MSBuild 14) building a c++ app, wanted to use VS 2010 (v100) tools. It all came down giving msbuild an invalid configuration option. Strange.

So, recheck all those options and parameters.

How to manually trigger click event in ReactJS?

Riffing on Aaron Hakala's answer with useRef inspired by this answer

const myRef = useRef(null);

  const clickElement = (ref) => {
      new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true,
        buttons: 1,

And your JSX:

<button onClick={() => clickElement(myRef)}>Click<button/>
<input ref={myRef}>

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Simply difference between Forward(ServletRequest request, ServletResponse response) and sendRedirect(String url) is


  1. The forward() method is executed in the server side.
  2. The request is transfer to other resource within same server.
  3. It does not depend on the client’s request protocol since the forward () method is provided by the servlet container.
  4. The request is shared by the target resource.
  5. Only one call is consumed in this method.
  6. It can be used within server.
  7. We cannot see forwarded message, it is transparent.
  8. The forward() method is faster than sendRedirect() method.
  9. It is declared in RequestDispatcher interface.


  1. The sendRedirect() method is executed in the client side.
  2. The request is transfer to other resource to different server.
  3. The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.
  4. New request is created for the destination resource.
  5. Two request and response calls are consumed.
  6. It can be used within and outside the server.
  7. We can see redirected address, it is not transparent.
  8. The sendRedirect() method is slower because when new request is created old request object is lost.
  9. It is declared in HttpServletResponse.

Show/Hide Div on Scroll

  <div class="a">

$(window).scroll(function() {
  if ($(this).scrollTop() > 0) {
  } else {


Writing data into CSV file in C#

I use a two parse solution as it's very easy to maintain

// Prepare the values
var allLines = (from trade in proposedTrades
                select new object[] 
                    string.Format("\"{0}\"", trade.Notes),                             

// Build the file content
var csv = new StringBuilder();
allLines.ForEach(line => 
    csv.AppendLine(string.Join(",", line));            

File.WriteAllText(filePath, csv.ToString());

Detecting when user scrolls to bottom of div with jQuery

this worked for me though

$(window).scroll(function() {
  if ($(window).scrollTop() >= (($(document).height() - $(window).height()) - $('#divID').innerHeight())) {
    console.log('div reached');

Checking if a string is empty or null in Java

You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.


System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true

Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).


System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?

Given this example url:

$_SERVER['REQUEST_URI'] will give you:


Whereas $_GET['q'] will give you:


In other words, $_SERVER['REQUEST_URI'] will hold the full request path including the querystring. And $_GET['q'] will give you the value of parameter q in the querystring.

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

suggestions of solving this problem is, If you already had installed app in your phone before downloading from google play.(obviously run from your code ) then first uninstal it. and then download and install app from google play . it worked for me .Thanks and regards.

Send json post using php

use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

Apparently, document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener() with the same parameters, instead.

Sending private messages to user

Make the code say if (msg.content === ('trigger')'text')}

How to clone a Date object?

var orig = new Date();
var copy = new Date(+orig);

console.log(orig, copy);

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Using CSS3 you don't need to make your own image with the transparency.

Just have a div with the following

background: rgba(255,255,255,.5);

The last parameter in background (.5) is the level of transparency (a higher number is more opaque).

Example Fiddle

What is the difference between a token and a lexeme?

Let's see the working of a lexical analyser ( also called Scanner )

Let's take an example expression :

INPUT : cout << 3+2+3;

FORMATTING PERFORMED BY SCANNER :  {cout}|space|{<<}|space|{3}{+}{2}{+}{3}{;} 

not the actual output though .


Lexeme is a substring of input that forms a valid string-of-terminals present in grammar . Every lexeme follows a pattern which is explained at the end ( the part that reader may skip at last )

( Important rule is to look for the longest possible prefix forming a valid string-of-terminals until next whitespace is encountered ... explained below )


  1. cout
  2. <<

( although "<" is also valid terminal-string but above mentioned rule shall select the pattern for lexeme "<<" in order to generate token returned by scanner )

  1. 3
  2. +
  3. 2
  4. ;

TOKENS : Tokens are returned one at a time ( by Scanner when requested by Parser ) each time Scanner finds a (valid) lexeme. Scanner creates ,if not already present, a symbol-table entry ( having attributes : mainly token-category and few others ) , when it finds a lexeme, in order to generate it's token

'#' denotes a symbol table entry . I have pointed to lexeme number in above list for ease of understanding but it technically should be actual index of record in symbol table.

The following tokens are returned by scanner to parser in specified order for above example.

  1. < identifier , #1 >

  2. < Operator , #2 >

  3. < Literal , #3 >

  4. < Operator , #4 >

  5. < Literal , #5 >

  6. < Operator , #4 >

  7. < Literal , #3 >

  8. < Punctuator , #6 >

As you can see the difference , a token is a pair unlike lexeme which is a substring of input.

And first element of the pair is the token-class/category

Token Classes are listed below:

  • And one more thing , Scanner detects whitespaces , ignores them and does not form any token for a whitespace at all. Not all delimiters are whitespaces, a whitespace is one form of delimiter used by scanners for it's purpose . Tabs , Newlines , Spaces , Escaped Characters in input all are collectively called Whitespace delimiters. Few other delimiters are ';' ',' ':' etc, which are widely recognised as lexemes that form token.

    Total number of tokens returned are 8 here , however only 6 symbol table entries are made for lexemes . Lexemes are also 8 in total ( see definition of lexeme )

    --- You can skip this part

    A ***pattern*** is a rule ( say, a regular expression ) that is used to check if a string-of-terminals is valid or not.

    If a substring of input composed only of grammar terminals is following the rule specified by any of the listed patterns , it is validated as a lexeme and selected pattern will identify the category of lexeme, else a lexical error is reported due to either (i) not following any of the rules or (ii) input consists of a bad terminal-character not present in grammar itself.

    for example :
    1. No Pattern Exists : In C++ , "99Id_Var" is grammar-supported string-of-terminals but is not recognised by any of patterns hence lexical error is reported .
    2. Bad Input Character : $,@,unicode characters may not be supported as a valid character in few programming languages.`

    How to solve the memory error in Python

    Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

    In [3]: sys.getsizeof('usedfor zipper fasten_coat')
    Out[3]: 75

    Doing some rough math:

    75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

    So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

    If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

    How to put a List<class> into a JSONObject and then read that object?

    This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this.( with or without an external library).

     Type collectionType = new TypeToken<List<Class>>() {
                    } // end new
                    String gsonString = 
                    new Gson().toJson(objList, collectionType);

    grant remote access of MySQL database from any IP address

    Use this command:

    GRANT ALL ON yourdatabasename.* TO root@'%' IDENTIFIED BY 'yourRootPassword';



    Then comment out the below line in file "/etc/mysql/mysql.conf.d/mysqld.cnf" (is required!):

    bind-address = 

    Works for me!

    Find all elements on a page whose element ID contains a certain text using jQuery

    If you're finding by Contains then it'll be like this

        $("input[id*='DiscountType']").each(function (i, el) {
             //It'll be an array of elements

    If you're finding by Starts With then it'll be like this

        $("input[id^='DiscountType']").each(function (i, el) {
             //It'll be an array of elements

    If you're finding by Ends With then it'll be like this

         $("input[id$='DiscountType']").each(function (i, el) {
             //It'll be an array of elements

    If you want to select elements which id is not a given string

        $("input[id!='DiscountType']").each(function (i, el) {
             //It'll be an array of elements

    If you want to select elements which name contains a given word, delimited by spaces

         $("input[name~='DiscountType']").each(function (i, el) {
             //It'll be an array of elements

    If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen

         $("input[id|='DiscountType']").each(function (i, el) {
             //It'll be an array of elements

    Unable to start Service Intent

    I've found the same problem. I lost almost a day trying to start a service from OnClickListener method - outside the onCreate and after 1 day, I still failed!!!! Very frustrating! I was looking at the sample example RemoteServiceController. Theirs works, but my implementation does not work!

    The only way that was working for me, was from inside onCreate method. None of the other variants worked and believe me I've tried them all.


    • If you put your service class in different package than the mainActivity, I'll get all kind of errors
    • Also the one "/" couldn't find path to the service, tried starting with Intent(package,className) and nothing , also other type of Intent starting

    • I moved the service class in the same package of the activity Final form that works

    • Hopefully this helps someone by defining the listerners onClick inside the onCreate method like this:

      public void onCreate() {
      //some code......
          Button btnStartSrv  = (Button)findViewById(;
          Button btnStopSrv  = (Button)findViewById(;
          btnStartSrv.setOnClickListener(new OnClickListener() {
              public void onClick(View v) {
                  startService(new Intent("RM_SRV_AIDL"));
          btnStopSrv.setOnClickListener(new OnClickListener() {
              public void onClick(View v) {
                  stopService(new Intent("RM_SRV_AIDL"));
      } // end onCreate

    Also very important for the Manifest file, be sure that service is child of application:

    <application ... >
        <activity ... >
                 <action android:name="RM_SRV_AIDL" />

    Locking pattern for proper use of .NET MemoryCache

    Console example of MemoryCache, "How to save/get simple class objects"

    Output after launching and pressing Any key except Esc :

    Saving to cache!
    Getting from cache!

        class Some
            public String text { get; set; }
            public Some(String text)
                this.text = text;
            public override string ToString()
                return text;
        public static MemoryCache cache = new MemoryCache("cache");
        public static string cache_name = "mycache";
        static void Main(string[] args)
            Some some1 = new Some("some1");
            Some some2 = new Some("some2");
            List<Some> list = new List<Some>();
            do {
                if (cache.Contains(cache_name))
                    Console.WriteLine("Getting from cache!");
                    List<Some> list_c = cache.Get(cache_name) as List<Some>;
                    foreach (Some s in list_c) Console.WriteLine(s);
                    Console.WriteLine("Saving to cache!");
                    cache.Set(cache_name, list, DateTime.Now.AddMinutes(10));                   
            } while (Console.ReadKey(true).Key != ConsoleKey.Escape);

    How to maintain aspect ratio using HTML IMG tag

    Use object-fit: contain in css of html element img.


    img {
        object-fit: contain

    Rerouting stdin and stdout from C

    freopen("/my/newstdin", "r", stdin);
    freopen("/my/newstdout", "w", stdout);
    freopen("/my/newstderr", "w", stderr);
    ... do your stuff
    freopen("/dev/stdin", "r", stdin);

    This peaks the needle on my round-peg-square-hole-o-meter, what are you trying to accomplish?


    Remember that stdin, stdout and stderr are file descriptors 0, 1 and 2 for every newly created process. freopen() should keep the same fd's, just assign new streams to them.

    So, a good way to ensure that this is actually doing what you want it to do would be:

    printf("Stdout is descriptor %d\n", fileno(stdout));
    freopen("/tmp/newstdout", "w", stdout);
    printf("Stdout is now /tmp/newstdout and hopefully still fd %d\n",
    freopen("/dev/stdout", "w", stdout);
    printf("Now we put it back, hopefully its still fd %d\n",

    I believe this is the expected behavior of freopen(), as you can see, you're still only using three file descriptors (and associated streams).

    This would override any shell redirection, as there would be nothing for the shell to redirect. However, its probably going to break pipes. You might want to be sure to set up a handler for SIGPIPE, in case your program finds itself on the blocking end of a pipe (not FIFO, pipe).

    So, ./your_program --stdout /tmp/stdout.txt --stderr /tmp/stderr.txt should be easily accomplished with freopen() and keeping the same actual file descriptors. What I don't understand is why you'd need to put them back once changing them? Surely, if someone passed either option, they would want it to persist until the program terminated?

    Iterating through a range of dates in Python

    This is the most human-readable solution I can think of.

    import datetime
    def daterange(start, end, step=datetime.timedelta(1)):
        curr = start
        while curr < end:
            yield curr
            curr += step

    Find specific string in a text file with VBS script

    Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:

    Option Explicit
    Dim StdIn:  Set StdIn = WScript.StdIn
    Dim StdOut: Set StdOut = WScript
    Sub Main()
    Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
    ForReading = 1
    ForWriting = 2
    Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
    count = 7
    foundFirstMatch = false
    Do until objInputFile.AtEndOfStream
        tmpStr = objInputFile.ReadLine
        If foundStrMatch(tmpStr)=true Then
            If foundFirstMatch = false Then
                index = getIndex(tmpStr)
                foundFirstMatch = true
                text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
            End If
            If index = getIndex(tmpStr) Then
                text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
            ElseIf index < getIndex(tmpStr) Then
                index = getIndex(tmpStr)
                text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
            End If
            text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
        End If
    Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
    End Sub
    Function textSubstitution(tmpStr,index,foundMatch)
    Dim strToAdd
    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
    If foundMatch = "false" Then
        textSubstitution = tmpStr
    ElseIf foundMatch = "true" Then
        textSubstitution = strToAdd & vbCrLf & tmpStr
    End If
    End Function
    Function getIndex(tmpStr)
    Dim substrToFind, charAtPos, char1, char2
    substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
    charAtPos = len(substrToFind) + 1
    char1 = Mid(tmpStr, charAtPos, 1)
    char2 = Mid(tmpStr, charAtPos+1, 1)
    If IsNumeric(char2) Then
        getIndex = CInt(char1 & char2)
        getIndex = CInt(char1)
    End If
    End Function
    Function foundStrMatch(tmpStr)
    Dim substrToFind
    substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
    If InStr(tmpStr, substrToFind) > 0 Then
        foundStrMatch = true
        foundStrMatch = false
    End If
    End Function

    This is the original txt file

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
    <html xmlns="" xml:lang="en" lang="en">
      <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
      <title>Test Suite</title>
    <table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
    <tr><td><b>Test Suite</b></td></tr>
    <tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
    <tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
    <tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
    <tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
    <tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
    <tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
    <tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
    <tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
    <tr><td><a href="../../Login/Logout">Logout</a></td></tr>
    <tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
    <tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
    <tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
    <tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
    <tr><td><a href="../../Login/Logout">Logout</a></td></tr>
    <tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
    <tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
    <tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
    <tr><td><a href="../../Login/Logout">Logout</a></td></tr>
    <tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
    <tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
    <tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
    <tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
    <tr><td><a href="../../Login/Logout">Logout</a></td></tr>
    <tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
    <tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
    <tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
    <tr><td><a href="../../Login/Logout">Logout</a></td></tr>
    <tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
    <tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>

    And this is the result I'm expecting

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
    <html xmlns="" xml:lang="en" lang="en">
      <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
      <title>Test Suite</title>
    <table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
    <tr><td><b>Test Suite</b></td></tr>
    <tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
    <tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
    <tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
    <tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
    <tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
    <tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
    <tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
    <tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
    <tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
    <tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
    <tr><td><a href="../../Login/Logout">Logout</a></td></tr>
    <tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
    <tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
    <tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
    <tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
    <tr><td><a href="../../Login/Logout">Logout</a></td></tr>
    <tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
    <tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
    <tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
    <tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
    <tr><td><a href="../../Login/Logout">Logout</a></td></tr>
    <tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
    <tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
    <tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
    <tr><td><a href="../../Login/Logout">Logout</a></td></tr>
    <tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
    <tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
    <tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
    <tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
    <tr><td><a href="../../Login/Logout">Logout</a></td></tr>
    <tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
    <tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>

    How can I concatenate a string and a number in Python?

    do it like this:

    "abc%s" % 9
    "abc" + str(9)

    How can I save a screenshot directly to a file in Windows?

    Try this:

    From their homepage:

    When you press a hotkey, it captures and saves a snapshot of your screen to a JPG, GIF or BMP file.

    Printing integer variable and string on same line in SQL

    declare @x INT = 1 /* Declares an integer variable named "x" with the value of 1 */
    PRINT 'There are ' + CAST(@x AS VARCHAR) + ' alias combinations did not match a record' /* Prints a string concatenated with x casted as a varchar */

    Setting an environment variable before a command in Bash is not working for the second command in a pipe

    How about exporting the variable, but only inside the subshell?:

    (export FOO=bar && somecommand someargs | somecommand2)

    Keith has a point, to unconditionally execute the commands, do this:

    (export FOO=bar; somecommand someargs | somecommand2)

    AngularJS ng-style with a conditional expression

    @jfredsilva obviously has the simplest answer for the question:

    ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"

    However, you might really want to consider my answer for something more complex.

    Ternary-like example:

    <p ng-style="{width: {true:'100%',false:'0%'}[myObject.value == 'ok']}"></p>

    Something more complex:

    <p ng-style="{
       color:       {blueish: 'blue', greenish: 'green'}[ color ], 
      'font-size':  {0: '12px', 1: '18px', 2: '26px'}[ zoom ]

    If $scope.color == 'blueish', the color will be 'blue'.

    If $scope.zoom == 2, the font-size will be 26px.

    function MyCtrl($scope) {_x000D_
      $scope.color = 'blueish';_x000D_
      $scope.zoom = 2;_x000D_
    <script src=""></script>_x000D_
    <div ng-app="app" ng-controller="MyCtrl" ng-style="{_x000D_
       color:       {blueish: 'blue', greenish: 'green'}[ color ], _x000D_
      'font-size':  {0: '12px', 1: '18px', 2: '26px'}[ zoom ]_x000D_
      color = {{color}}<br>_x000D_
      zoom = {{zoom}}_x000D_

    Disabling the long-running-script message in Internet Explorer

    The unresponsive script dialog box shows when some javascript thread takes too long too complete. Editing the registry could work, but you would have to do it on all client machines. You could use a "recursive closure" as follows to alleviate the problem. It's just a coding structure in which allows you to take a long running for loop and change it into something that does some work, and keeps track where it left off, yielding to the browser, then continuing where it left off until we are done.

    Figure 1, Add this Utility Class RepeatingOperation to your javascript file. You will not need to change this code:

    RepeatingOperation = function(op, yieldEveryIteration) {
      //keeps count of how many times we have run heavytask() 
      //before we need to temporally check back with the browser.
      var count = 0;   
      this.step = function() {
        //Each time we run heavytask(), increment the count. When count
        //is bigger than the yieldEveryIteration limit, pass control back 
        //to browser and instruct the browser to immediately call op() so
        //we can pick up where we left off.  Repeat until we are done.
        if (++count >= yieldEveryIteration) {
          count = 0;
          //pass control back to the browser, and in 1 millisecond, 
          //have the browser call the op() function.  
          setTimeout(function() { op(); }, 1, [])
          //The following return statement halts this thread, it gives 
          //the browser a sigh of relief, your long-running javascript
          //loop has ended (even though technically we havn't yet).
          //The browser decides there is no need to alarm the user of
          //an unresponsive javascript process.

    Figure 2, The following code represents your code that is causing the 'stop running this script' dialog because it takes so long to complete:

    process10000HeavyTasks = function() {
      var len = 10000;  
      for (var i = len - 1; i >= 0; i--) {
        heavytask();   //heavytask() can be run about 20  times before
                       //an 'unresponsive script' dialog appears.
                       //If heavytask() is run more than 20 times in one
                       //javascript thread, the browser informs the user that
                       //an unresponsive script needs to be dealt with.  
                       //This is where we need to terminate this long running
                       //thread, instruct the browser not to panic on an unresponsive
                       //script, and tell it to call us right back to pick up
                       //where we left off.

    Figure 3. The following code is the fix for the problematic code in Figure 2. Notice the for loop is replaced with a recursive closure which passes control back to the browser every 10 iterations of heavytask()

    process10000HeavyTasks = function() {
      var global_i = 10000; //initialize your 'for loop stepper' (i) here.
      var repeater = new this.RepeatingOperation(function() {
        if (--global_i >= 0){     //Your for loop conditional goes here.
          repeater.step();        //while we still have items to process,
                                  //run the next iteration of the loop.
        else {
           alert("we are done");  //when this line runs, the for loop is complete.
      }, 10);                   //10 means process 10 heavytask(), then
                                //yield back to the browser, and have the
                                //browser call us right back.
      repeater.step();          //this command kicks off the recursive closure.

    Adapted from this source:

    Regular expression for a string that does not start with a sequence

    You could use a negative look-ahead assertion:


    Or a negative look-behind assertion:


    Or just plain old character sets and alternations:


    What is the best way to filter a Java Collection?

    I wrote an extended Iterable class that support applying functional algorithms without copying the collection content.


    List<Integer> myList = new ArrayList<Integer>(){ 1, 2, 3, 4, 5 }
    Iterable<Integer> filtered = Iterable.wrap(myList).select(new Predicate1<Integer>()
        public Boolean call(Integer n) throws FunctionalException
            return n % 2 == 0;
    for( int n : filtered )

    The code above will actually execute

    for( int n : myList )
        if( n % 2 == 0 ) 

    fileReader.readAsBinaryString to upload files

    Use fileReader.readAsDataURL( fileObject ), this will encode it to base64, which you can safely upload to your server.

    How to Migrate to WKWebView?

    You have to use WKWebView, which is available as of iOS8 in Framework 'WebKit' to get the speedup. If you need backwards compatibility, you have to use UIWebView for iOS7 and older.

    I set up a little code to provide the UIViewController frame for the new WKWebView. It can be installed via cocoapods. Have a look here:

    STKWebKitViewController on github

    How can I get this ASP.NET MVC SelectList to work?

    This is an option:

    myViewData.PageOptionsDropDown = new[] 
     new SelectListItem { Text = "10", Value = "10" },
     new SelectListItem { Text = "15", Value = "15", Selected = true }
     new SelectListItem { Text = "25", Value = "25" },
     new SelectListItem { Text = "50", Value = "50" },
     new SelectListItem { Text = "100", Value = "100" },
     new SelectListItem { Text = "1000", Value = "1000" },

    Rotate image with javascript

    You can always apply CCS class with rotate property -

    To keep rotated image within your div dimensions you need to adjust CSS as well, there is no needs to use JavaScript except of adding class.

    Make function wait until element exists

    Maybe I'm a little bit late :), but here is a nice and brief solution by chrisjhoughton, which allows to perform a callback function when the wait is over.

    var waitForEl = function(selector, callback) {
      if (jQuery(selector).length) {
      } else {
        setTimeout(function() {
          waitForEl(selector, callback);
        }, 100);
    waitForEl(selector, function() {
      // work the magic

    If you need to pass parameters to a callback function, you can use it this way:

    waitForEl("#" + elDomId, () => callbackFunction(param1, param2));

    But be careful! This solution by default can fall into a trap of an infinite loop.

    Several improvements of the topicstarter's suggestion are also provided in The GitHub thread.


    Import data into Google Colaboratory

    in google colabs if this is your first time,

    from google.colab import drive

    run these codes and go through the outputlink then past the pass-prase to the box

    when you copy you can copy as follows, go to file right click and copy the path ***don't forget to remove " /content "

    f = open("drive/My Drive/RES/dimeric_force_field/Test/python_read/cropped.pdb", "r")

    Tomcat Server Error - Port 8080 already in use

    All I had to do was to change the port numbers. enter image description here

    1. Open Eclipse

    2. Go to Servers panel

    3. Right click on Tomcat Server select Open, Overview window will appear.

    4. Open the Portstab. You will get the following:

      • Tomcat adminport

      • HTTP/1.1

      • AJP/1.3

    5. I changed the port number of HTTP/1.1 (i.e. to 8081)

    6. You might have to also change the port of Tomcat adminport (i.e. to 8006) and of AJP/1.3 (i.e. to 8010).

    7. Access your app in the browser at http://localhost:8081/...

    How to clear all input fields in a specific div with jQuery?

    Here is Beena's answer in ES6 Sans the JQuery dependency.. Thank's Beena!

    let resetFormObject = (elementID)=> {
                switch(input.type) {
                    case 'password':
                    case 'text':
                    case 'textarea':
                    case 'file':
                    case 'select-one':
                    case 'select-multiple':
                    case 'date':
                    case 'number':
                    case 'tel':
                    case 'email':
                        input.value = '';
                    case 'checkbox':
                    case 'radio':
                        input.checked = false;

    How do I unbind "hover" in jQuery?

    I found this works as second argument (function) to .hover()

            // Your code goes here

    The first function (argument to .hover()) is mouseover and will execute your code. The second argument is mouseout which will unbind the hover event from #yourId. Your code will be executed only once.

    Best Practices: working with long, multiline strings in PHP?

    you can also use:

    echo "some text";
    echo "\n";
    // you can also use: 
    some text can be also written here, or maybe HTML:
    echo "you can basically write whatever you want";
    // and then: 
    $long_text = ob_get_clean();

    Split string into array of character strings

    Maybe you can use a for loop that goes through the String content and extract characters by characters using the charAt method.

    Combined with an ArrayList<String> for example you can get your array of individual characters.

    ToggleButton in C# WinForms

    You may also consider the ToolStripButton control if you don't mind hosting it in a ToolStripContainer. I think it can natively support pressed and unpressed states.

    Why do we need to use flatMap?

    It's not an array of arrays. It's an observable of observable(s).

    The following returns an observable stream of string.

      .map(function(requestUrl) {
        return requestUrl;

    While this returns an observable stream of observable stream of json

      .map(function(requestUrl) {
        return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));

    flatMap flattens the observable automatically for us so we can observe the json stream directly

    Karma: Running a single test file from command line

    Even though --files is no longer supported, you can use an env variable to provide a list of files:

    // karma.conf.js
    function getSpecs(specList) {
      if (specList) {
        return specList.split(',')
      } else {
        return ['**/*_spec.js'] // whatever your default glob is
    module.exports = function(config) {
        files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))

    Then in CLI:

    $ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run

    How to check if a process id (PID) exists

    It seems like you want

    wait $PID

    which will return when $pid finishes.

    Otherwise you can use

    ps -p $PID

    to check if the process is still alive (this is more effective than kill -0 $pid because it will work even if you don't own the pid).

    "On Exit" for a Console Application

    This code works to catch the user closing the console window:

    using System;
    using System.Runtime.InteropServices;
    class Program {
        static void Main(string[] args) {
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);
        static bool ConsoleEventCallback(int eventType) {
            if (eventType == 2) {
                Console.WriteLine("Console window closing, death imminent");
            return false;
        static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
        // Pinvoke
        private delegate bool ConsoleEventDelegate(int eventType);
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

    Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

    Error 1046 No database Selected, how to resolve?

    Although this is a pretty old thread, I just found something out. I created a new database, then added a user, and finally went to use phpMyAdmin to upload the .sql file. total failure. The system doesn't recognize which DB I'm aiming at...

    When I start fresh WITHOUT first attaching a new user, and then perform the same phpMyAdmin import, it works fine.

    HTML favicon won't show on google chrome

    The path must be via the URI (full).


    so in your case:

    <!DOCTYPE html>
        <head profile="">
            <link rel="shortcut icon" 
                  href="" />