Programs & Examples On #Npruntime

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library


Format y axis as percent

This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):

import ...
import matplotlib.ticker as mtick

ax = df['myvar'].plot(kind='bar')

PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0).

The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None and '%', respectively. decimals=None will automatically set the number of decimal points based on how much of the axes you are showing.


PercentFormatter was introduced into Matplotlib proper in version 2.1.0.

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

List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
  array[i++] = s;

how to generate public key from windows command prompt

Humm, what? ssh is not something built in to Windows like in most *nix cases.

You'd probably want to use Putty to begin with. And:

laravel foreach loop in controller

Hi, this will throw an error:

foreach ($product->sku as $sku){ 
// Code Here

because you cannot loop a model with a specific column ($product->sku) from the table.
So you must loop on the whole model:

foreach ($product as $p) {
// code

Inside the loop you can retrieve whatever column you want just adding "->[column_name]"

foreach ($product as $p) {
echo $p->sku;

Have a great day

How do I add PHP code/file to HTML(.html) files?

By default you can't use PHP in HTML pages.

To do that, modify your .htacccess file with the following:

AddType application/x-httpd-php .html

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("");  // as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

jquery append external html file into my page

i'm not sure what you're expecting this to refer to in your example.. here's an alternative method:

        <script src="" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                $.get("banner.html", function (data) {
        <div id="appendToThis"></div>

node.js execute system command synchronously

Node.js (since version 0.12 - so for a while) supports execSync:

child_process.execSync(command[, options])

You can now directly do this:

const execSync = require('child_process').execSync;
code = execSync('node -v');

and it'll do what you expect. (Defaults to pipe the i/o results to the parent process). Note that you can also spawnSync now.

SQL Server Creating a temp table for this query

If you want to create a temp table after check exist table.You can use the following code

DROP TABLE IF EXISTS tempdb.dbo.#temptable
CREATE TABLE #temptable
   SiteName             NVARCHAR(50),
   BillingMonth         varchar(10),
   Consumption          INT,

After creating the temporary table, you can insert data into this table as a regular table:

INSERT INTO #temptable


INSERT INTO #temptable
VALUES (value1, value2, value3, ...);

The SELECT statement is used to select data from a temp table.

SELECT * FROM #temptable

you can manually remove the temporary table by using the DROP TABLE statement:

DROP TABLE #temptable;

Getting data from selected datagridview row and which event?

You can use SelectionChanged event since you are using FullRowSelect selection mode. Than inside the handler you can access SelectedRows property and get data from it. Example:

private void dataGridView_SelectionChanged(object sender, EventArgs e) 
    foreach (DataGridViewRow row in dataGridView.SelectedRows) 
        string value1 = row.Cells[0].Value.ToString();
        string value2 = row.Cells[1].Value.ToString();

You can also walk through the column collection instead of typing indexes...

No @XmlRootElement generated by JAXB

This is mentioned at the bottom of the blog post already linked above but this works like a treat for me:

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(new JAXBElement<MyClass>(new QName("uri","local"), MyClass.class, myClassInstance), System.out);

Upgrading PHP in XAMPP for Windows?


In order to run apache server after upgradation PHP 7.4.x requires Microsoft Visual C++ Redistributable for Visual Studio 2019 which can be downloaded here under the heading Other Tools and Frameworks. otherwise apache server won't start.

Sending Arguments To Background Worker?

You need RunWorkerAsync(object) method and DoWorkEventArgs.Argument property.


private void worker_DoWork(object sender, DoWorkEventArgs e) {
    int argument = (int)e.Argument; //5

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

you dont have to use open when you are using for loops.

cursor cur_name is  select * from emp;
for cur_rec in cur_name Loop
end loop;
End ;


cursor cur_name is  select * from emp;
cur_rec emp%rowtype;
Open cur_name;
Fetch cur_name into  Cur_rec;
   Exit when cur_name%notfound;
end loop;
Close cur_name;
End ;

Can attributes be added dynamically in C#?

No, it's not.

Attributes are meta-data and stored in binary-form in the compiled assembly (that's also why you can only use simple types in them).

Python Serial: How to use the read or readline function to read more than 1 character at a time

I use this small method to read Arduino serial monitor with Python

import serial
ser = serial.Serial("COM11", 9600)
while True:

Remove trailing comma from comma-separated string


public class SiftNumberAndEvenNumber {

    public static void main(String[] args) {

        int arr[] = {1,2,3,4,5};
        int arr1[] = new int[arr.length];
        int shiftAmount=3;
        for(int i = 0; i < arr.length; i++){
            int newLocation = (i + (arr.length - shiftAmount)) % arr.length;
            arr1[newLocation] = arr[i];
        for(int i=0;i<arr1.length;i++) {
            if(i==arr1.length-1) {
            }else {
        for(int i=0;i<arr1.length;i++) {
            if(arr1[i]%2==0) {
                System.out.print(arr1[i]+" ");

How to remove index.php from URLs?

Follow the below steps it will helps you.

step 1: Go to to your site root folder and you can find the .htaccess file there. Open it with a text editor and find the line #RewriteBase /magento/. Just replace it with #RewriteBase / take out just the 'magento/'

step 2: Then go to your admin panel and enable the Rewrites(set yes for Use Web Server Rewrites). You can find it at System->Configuration->Web->Search Engine Optimization.

step 3: Then go to Cache management page (system cache management ) and refresh your cache and refresh to check the site.

extract column value based on another column pandas dataframe

It's easier for me to think in these terms, but borrowing from other answers. The value you want is located in the series:


where column and row point to the value you want returned. For your example, column is 'A' and for row you use a mask:

df['B'] == 3

To get the value from the series there are several options:

df['A'][df['B'] == 3].values[0]
df['A'][df['B'] == 3].iloc[0]
df['A'][df['B'] == 3].to_numpy()[0]

CSS: Set a background color which is 50% of the width of the window

Older Browser Support

If older browser support is a must, so you can't go with multiple backgrounds or gradients, you're probably going to want to do something like this on a spare div element:

#background {
    position: fixed;
    top: 0;
    left: 0;
    width: 50%;
    height: 100%;
    background-color: pink; 


The solution uses an extra fixed div that fills half the screen. Since it's fixed, it will remain in position even when your users scroll. You may have to fiddle with some z-indexes later, to make sure your other elements are above the background div, but it shouldn't be too complex.

If you have issues, just make sure the rest of your content has a z-index higher than the background element and you should be good to go.

Modern Browsers

If newer browsers are your only concern, there are a couple other methods you can use:

Linear Gradient:

This is definitely the easiest solution. You can use a linear-gradient in the background property of the body for a variety of effects.

body {
    height: 100%;
    background: linear-gradient(90deg, #FFC0CB 50%, #00FFFF 50%);

This causes a hard cutoff at 50% for each color, so there isn't a "gradient" as the name implies. Try experimenting with the "50%" piece of the style to see the different effects you can achieve.


Multiple Backgrounds with background-size:

You can apply a background color to the html element, and then apply a background-image to the body element and use the background-size property to set it to 50% of the page width. This results in a similar effect, though would really only be used over gradients if you happen to be using an image or two.

html {
    height: 100%;
    background-color: cyan;

body {
    height: 100%;
    background-image: url('');
    background-repeat: repeat-y;
    background-size: 50% auto;


EXTRA NOTE: Notice that both the html and body elements are set to height: 100% in the latter examples. This is to make sure that even if your content is smaller than the page, the background will be at least the height of the user's viewport. Without the explicit height, the background effect will only go down as far as your page content. It's also just a good practice in general.

Sending JSON object to Web API


 data: JSON.stringify({ model: source })


 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

Tab Escape Character?

For someone who needs quick reference of C# Escape Sequences that can be used in string literals:

\t     Horizontal tab (ASCII code value: 9)

\n     Line feed (ASCII code value: 10)

\r     Carriage return (ASCII code value: 13)

\'     Single quotation mark

\"     Double quotation mark

\\     Backslash

\?     Literal question mark

\x12     ASCII character in hexadecimal notation (e.g. for 0x12)

\x1234     Unicode character in hexadecimal notation (e.g. for 0x1234)

It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline which gets adjusted to current OS settings. With .Net Core it gets really important.

When to use pthread_exit() and when to use pthread_join() in Linux?


POSIX pthread_exit description from

After a thread has terminated, the result of access to local (auto) variables of the thread is 
undefined. Thus, references to local variables of the exiting thread should not be used for 
the pthread_exit() value_ptr parameter value.

Which seems contrary to the idea that local main() thread variables will remain accessible.

How to solve privileges issues when restore PostgreSQL Database

You can probably safely ignore the error messages in this case. Failing to add a comment to the public schema and installing plpgsql (which should already be installed) aren't going to cause any real problems.

However, if you want to do a complete re-install you'll need a user with appropriate permissions. That shouldn't be the user your application routinely runs as of course.

How to set component default props on React component

First you need to separate your class from the further extensions ex you cannot extend AddAddressComponent.defaultProps within the class instead move it outside.

I will also recommend you to read about the Constructor and React's lifecycle: see Component Specs and Lifecycle

Here is what you want:

import PropTypes from 'prop-types';

class AddAddressComponent extends React.Component {
  render() {
    let { provinceList, cityList } = this.props;
    if(cityList === undefined || provinceList === undefined){
      console.log('undefined props');

AddAddressComponent.contextTypes = {
  router: PropTypes.object.isRequired

AddAddressComponent.defaultProps = {
  cityList: [],
  provinceList: [],

AddAddressComponent.propTypes = {
  userInfo: PropTypes.object,
  cityList: PropTypes.array.isRequired,
  provinceList: PropTypes.array.isRequired,

export default AddAddressComponent;

How to read/process command line arguments?

You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - Commando

HTML5 event handling(onfocus and onfocusout) using angular 2

If you want to catch the focus event dynamiclly on every input on your component :

import { AfterViewInit, Component, ElementRef } from '@angular/core';

  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
export class AppComponent implements AfterViewInit {

  constructor(private el: ElementRef) {

  ngAfterViewInit() {
       // document.getElementsByTagName('input') : to gell all Docuement imputs
       const inputList = []<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
        inputList.forEach((input: HTMLElement) => {
            input.addEventListener('focus', () => {
                input.setAttribute('placeholder', 'focused');
            input.addEventListener('blur', () => {

Checkout the full code here :

Is there a simple way to use button to navigate page as a link does in angularjs

For me, best solution is to use Angular router native directives with ui-sref like:

<button ui-sref="">Go!!</button>

To understand that directive and get more options visit ui-router docs at:

: )

Query based on multiple where clauses in Firebase

Using Firebase's Query API, you might be tempted to try this:

  .orderBy('lead')                  // !!! THIS LINE WILL RAISE AN ERROR !!!
  .startAt('Jack Nicholson').endAt('Jack Nicholson')
  .on('value', function(snapshot) { 

But as @RobDiMarco from Firebase says in the comments:

multiple orderBy() calls will throw an error

So my code above will not work.

I know of three approaches that will work.

1. filter most on the server, do the rest on the client

What you can do is execute one orderBy().startAt()./endAt() on the server, pull down the remaining data and filter that in JavaScript code on your client.

  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      if (movie.lead == 'Jack Nicholson') {

2. add a property that combines the values that you want to filter on

If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter.

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_lead": "comedy_Jack Nicholson"
}, //...

You're essentially building your own multi-column index that way and can query it with:

  .equalTo('comedy_Jack Nicholson')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();

David East has written a library called QueryBase that helps with generating such properties.

You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure:

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_year": "comedy_1997"
}, //...

And then query for comedies of the 90s with:

  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();

If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25". This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering.

This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property.

A very special variant of this is implemented by the GeoFire library for Firebase. This library combines the latitude and longitude of a location into a so-called Geohash, which can then be used to do realtime range queries on Firebase.

3. create a custom index programmatically

Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node:

      // the same structure you have today
              "Jack Nicholson"
              "Jim Carrey"
              "Jack Nicholson"

There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index:

If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database.

Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries.

Checking Value of Radio Button Group via JavaScript?


var selectedVal;

for( i = 0; i < document.form_name.gender.length; i++ )
    selectedVal = document.form_name.gender[i].value; //male or female

Trim string in JavaScript?

Here's a very simple way:

function removeSpaces(string){
return string.split(' ').join('');

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

ObservableRangeCollection should pass a test like

public void TestAddRangeWhileBoundToListCollectionView()
    int collectionChangedEventsCounter = 0;
    int propertyChangedEventsCounter = 0;
    var collection = new ObservableRangeCollection<object>();

    collection.CollectionChanged += (sender, e) => { collectionChangedEventsCounter++; };
    (collection as INotifyPropertyChanged).PropertyChanged += (sender, e) => { propertyChangedEventsCounter++; };

    var list = new ListCollectionView(collection);

    collection.AddRange(new[] { new object(), new object(), new object(), new object() });

    Assert.AreEqual(4, collection.Count);
    Assert.AreEqual(1, collectionChangedEventsCounter);
    Assert.AreEqual(2, propertyChangedEventsCounter);

otherwise we get

System.NotSupportedException : Range actions are not supported.

while using with a control.

I do not see an ideal solution, but NotifyCollectionChangedAction.Reset instead of Add/Remove partially solve the problem. See as was mentioned by net_prog

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

Most of the time this happens due to less memory space. first check then try some other tricks .

How to remove the default arrow icon from a dropdown list (select element)?

Works for all browsers and all versions:


jQuery(document).ready(function () {    
    var widthOfSelect = $("#first").width();
    widthOfSelect = widthOfSelect - 13;
    jQuery('#first').wrap("<div id='sss' style='width: "+widthOfSelect+"px; overflow: hidden; border-right: #000 1px solid;' width=20></div>");


<select class="first" id="first">

Cannot implicitly convert type 'int?' to 'int'.

Your method's return type is int and you're trying to return an int?.

How to clear exisiting dropdownlist items when its content changes?

Just 2 simple steps to solve your issue

First of all check AppendDataBoundItems property and make it assign false

Secondly clear all the items using property .clear()

ddl1.datasource = sql1;

Can we have multiple <tbody> in same <table>?

Martin Joiner's problem is caused by a misunderstanding of the <caption> tag.

The <caption> tag defines a table caption.

The <caption> tag must be the first child of the <table> tag.

You can specify only one caption per table.

Also, note that the scope attribute should be placed on a <th> element and not on a <tr> element.

The proper way to write a multi-header multi-tbody table would be something like this :

<table id="dinner_table">_x000D_
    <caption>This is the only correct place to put a caption.</caption>_x000D_
        <tr class="header">_x000D_
            <th colspan="2" scope="col">First Half of Table (British Dinner)</th>_x000D_
            <th scope="row">1</th>_x000D_
            <th scope="row">2</th>_x000D_
            <th scope="row">3</th>_x000D_
            <th scope="row">4</th>_x000D_
        <tr class="header">_x000D_
            <th colspan="2" scope="col">Second Half of Table (Italian Dinner)</th>_x000D_
            <th scope="row">5</th>_x000D_
            <th scope="row">6</th>_x000D_
            <th scope="row">7</th>_x000D_
            <th scope="row">8</th>_x000D_

C++ Vector of pointers

I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?

I would guess this is what is intended. The intent is probably that you read the data for one movie, allocate an object with new, fill the object in with the data, and then push the address of the data onto the vector (probably not the best design, but most likely what's intended anyway).

How do I create and read a value from cookie?

I use the following functions, which I have written by taking the best I have found from various sources and weeded out some bugs or discrepancies.

The function setCookie does not have advanced options, just the simple stuff, but the code is easy to understand, which is always a plus:

function setCookie(name, value, daysToLive = 3650) { // 10 years default
  let cookie = name + "=" + encodeURIComponent(value);
  if (typeof daysToLive === "number") {
    cookie += "; max-age=" + (daysToLive * 24 * 60 * 60);
    document.cookie = cookie + ";path=/";
function getCookie(name) {
  let cookieArr = document.cookie.split(";");
  for (let i = 0; i < cookieArr.length; i++) {
    let cookiePair = cookieArr[i].split("=");
    if (name == cookiePair[0].trim()) {
      return decodeURIComponent(cookiePair[1].trim());
  return undefined;
function deleteCookie(name) {
  setCookie(name, '', -1);

C++ deprecated conversion from string constant to 'char*'

The following illustrates the solution, assign your string to a variable pointer to a constant array of char (a string is a constant pointer to a constant array of char - plus length info):

#include <iostream>

void Swap(const char * & left, const char * & right) {
    const char *const temp = left;
    left = right;
    right = temp;

int main() {
    const char * x = "Hello"; // These works because you are making a variable
    const char * y = "World"; // pointer to a constant string
    std::cout << "x = " << x << ", y = " << y << '\n';
    Swap(x, y);
    std::cout << "x = " << x << ", y = " << y << '\n';

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

Need to create database using following command.

CREATE DATABASE database_name CHARACTER SET utf8 COLLATE utf8_general_ci;

and then run following command to migrate database tables.

php artisan migrate

Android Layout Right Align

This is an example for a RelativeLayout:

RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(;
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();

With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.

'heroku' does not appear to be a git repository

For me the answer was to cd into the root directory of the app before running heroku create or git push heroku master

Convert string to int if string is a number

Try this: currentLoad = ConvertToLongInteger(oXLSheet2.Cells(4, 6).Value) with this function:

Function ConvertToLongInteger(ByVal stValue As String) As Long
 On Error GoTo ConversionFailureHandler
 ConvertToLongInteger = CLng(stValue)  'TRY to convert to an Integer value
 Exit Function           'If we reach this point, then we succeeded so exit

 'IF we've reached this point, then we did not succeed in conversion
 'If the error is type-mismatch, clear the error and return numeric 0 from the function
 'Otherwise, disable the error handler, and re-run the code to allow the system to 
 'display the error
 If Err.Number = 13 Then 'error # 13 is Type mismatch
      ConvertToLongInteger = 0
      Exit Function
      On Error GoTo 0
 End If
End Function

I chose Long (Integer) instead of simply Integer because the min/max size of an Integer in VBA is crummy (min: -32768, max:+32767). It's common to have an integer outside of that range in spreadsheet operations.

The above code can be modified to handle conversion from string to-Integers, to-Currency (using CCur() ), to-Decimal (using CDec() ), to-Double (using CDbl() ), etc. Just replace the conversion function itself (CLng). Change the function return type, and rename all occurrences of the function variable to make everything consistent.

When and Why to use abstract classes/methods?

read the following article

Abstract Classes

–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

Use an abstract class

When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.) Use an abstract class to define a common base class for a family of types. Use an abstract class to provide default behavior. Subclass only a base class in a hierarchy to which the class logically belongs.

Rewrite left outer join involving multiple tables from Informix to Oracle

Write one table per join, like this:

select tab1.a,tab2.b,tab3.c,tab4.d 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on = and tab3.desc = "XYZ"
  left join table4 tab4 on tab4.xya = tab3.xya and =
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk

Note that while my query contains actual left join, your query apparently doesn't. Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).

The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.

In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.

So look what happens when you move conditions to the where clause:

select tab1.a,tab2.b,tab3.c,tab4.d 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on =
  left join table4 tab4 on tab4.xya = tab3.xya
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
  tab3.desc = "XYZ" and =

Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.

PS: left join and left outer join are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join to make not the left, but the right table the leading table. And there is and even full [outer] join to return a row if there is data in either table.

How to apply a CSS class on hover to dynamically generated submit buttons?

Add the below code

input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;

If you need only for these button then you can add id name

#paginate input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;


Difference between CR LF, LF and CR line break types?

Systems based on ASCII or a compatible character set use either LF (Line feed, 0x0A, 10 in decimal) or CR (Carriage return, 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A); These characters are based on printer commands: The line feed indicated that one line of paper should feed out of the printer, and a carriage return indicated that the printer carriage should return to the beginning of the current line.

Here is the details.

Passing multiple parameters to function in Python

You can use functools.partial for this (as you suspected):

from functools import partial

def target(lock, iterable_item):
    for item in iterable_item:
        # Do cool stuff
        if (... some condition here ...):
            # Write to stdout or logfile, etc.

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    l = multiprocessing.Lock()
    func = partial(target, l), iterable)


def f(a, b, c):
    print("{} {} {}".format(a, b, c))

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    a = "hi"
    b = "there"
    func = partial(f, a, b), iterable)

if __name__ == "__main__":


hi there 1
hi there 2
hi there 3
hi there 4
hi there 5

Linq to Entities - SQL "IN" clause

I also tried to work with an SQL-IN-like thing - querying against an Entity Data Model. My approach is a string builder to compose a big OR-expression. That's terribly ugly, but I'm afraid it's the only way to go right now.

Now well, that looks like this:

Queue<Guid> productIds = new Queue<Guid>(Products.Select(p => p.Key));
if(productIds.Count > 0)
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("{0}.ProductId = Guid\'{1}\'", entities.Products.Name, productIds.Dequeue());
    while(productIds.Count > 0)
        sb.AppendFormat(" OR {0}.ProductId = Guid\'{1}\'",
          entities.Products.Name, productIds.Dequeue());

Working with GUIDs in this context: As you can see above, there is always the word "GUID" before the GUID ifself in the query string fragments. If you don't add this, ObjectQuery<T>.Where throws the following exception:

The argument types 'Edm.Guid' and 'Edm.String' are incompatible for this operation., near equals expression, line 6, column 14.

Found this in MSDN Forums, might be helpful to have in mind.


... looking forward for the next version of .NET and Entity Framework, when everything get's better. :)

What is the best way to remove the first element from an array?

The size of arrays in Java cannot be changed. So, technically you cannot remove any elements from the array.

One way to simulate removing an element from the array is to create a new, smaller array, and then copy all of the elements from the original array into the new, smaller array.

String[] yourArray = Arrays.copyOfRange(oldArr, 1, oldArr.length);

However, I would not suggest the above method. You should really be using a List<String>. Lists allow you to add and remove items from any index. That would look similar to the following:

List<String> list = new ArrayList<String>(); // or LinkedList<String>();
// add lots of stuff
list.remove(0); // removes the first item

How do you append an int to a string in C++?

You also try concatenate player's number with std::string::push_back :

Example with your code:

int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;

You will see in console:

Player 4

Apache Tomcat Connection refused

There is one more explanation for this Connection Refused problem, that I missed from answers above. In my case I had thread running (quartz scheduler) started from context listener (in contextInitialized), never to be stopped (like in contextDestroyed).

This in turn caused the server port associated to be closed, where as the container kept on running (hence: connection refused on the server port).

I fixed it stopping quartz in contextDestroyed and I didn't experience this issue ever since.

See here for similar issues: Tomcat doesn't stop. How can I debug this?

How to Identify port number of SQL server

To check all the applications listening on all ports, there is command:

netstat -ntpl

RecyclerView vs. ListView

Advantages of RecyclerView over listview :

  1. Contains ViewHolder by default.

  2. Easy animations.

  3. Supports horizontal , grid and staggered layouts

Advantages of listView over recyclerView :

  1. Easy to add divider.

  2. Can use inbuilt arrayAdapter for simple plain lists

  3. Supports Header and footer .

  4. Supports OnItemClickListner .

Insert line break in wrapped cell via code

Yes there are two way to add a line feed:

  1. Use the existing function from VBA vbCrLf in the string you want to add a line feed, as such:

    Dim text As String

    text = "Hello" & vbCrLf & "World!"

    Worksheets(1).Cells(1, 1) = text

  2. Use the Chr() function and pass the ASCII characters 13 and 10 in order to add a line feed, as shown bellow:

    Dim text As String

    text = "Hello" & Chr(13) & Chr(10) & "World!"

    Worksheets(1).Cells(1, 1) = text

In both cases, you will have the same output in cell (1,1) or A1.

HTML5 form validation pattern alphanumeric with spaces?

Use this code to ensure the user doesn't just enter spaces but a valid name:


How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

You can use tr to convert from DOS to Unix; however, you can only do this safely if CR appears in your file only as the first byte of a CRLF byte pair. This is usually the case. You then use:

tr -d '\015' <DOS-file >UNIX-file

Note that the name DOS-file is different from the name UNIX-file; if you try to use the same name twice, you will end up with no data in the file.

You can't do it the other way round (with standard 'tr').

If you know how to enter carriage return into a script (control-V, control-M to enter control-M), then:

sed 's/^M$//'     # DOS to Unix
sed 's/$/^M/'     # Unix to DOS

where the '^M' is the control-M character. You can also use the bash ANSI-C Quoting mechanism to specify the carriage return:

sed $'s/\r$//'     # DOS to Unix
sed $'s/$/\r/'     # Unix to DOS

However, if you're going to have to do this very often (more than once, roughly speaking), it is far more sensible to install the conversion programs (e.g. dos2unix and unix2dos, or perhaps dtou and utod) and use them.

If you need to process entire directories and subdirectories, you can use zip:

zip -r -ll somedir/

This will create a zip archive with line endings changed from CRLF to CR. unzip will then put the converted files back in place (and ask you file by file - you can answer: Yes-to-all). Credits to @vmsnomad for pointing this out.

Decimal to Hexadecimal Converter in Java

The easiest way to do this is:

String hexadecimalString = String.format("%x", integerValue);

SQL left join vs multiple tables on FROM line?

The first way is the older standard. The second method was introduced in SQL-92, The complete standard can be viewed at .

It took many years before database companies adopted the SQL-92 standard.

So the reason why the second method is preferred, it is the SQL standard according the ANSI and ISO standards committee.

svn list of files that are modified in local copy

svn status | grep 'M ' works fine on MacOSX.

I just tested this.

Is it possible to run CUDA on AMD GPUs?

Nope, you can't use CUDA for that. CUDA is limited to NVIDIA hardware. OpenCL would be the best alternative.

Khronos itself has a list of resources. As does the website. For your AMD specific resources, you might want to have a look at AMD's APP SDK page.

Note that at this time there are several initiatives to translate/cross-compile CUDA to different languages and APIs. One such an example is HIP. Note however that this still does not mean that CUDA runs on AMD GPUs.

Add image in pdf using jspdf

The above code not worked for me. I found new solution :

 var pdf = new jsPDF();
 var img = new Image;
 img.onload = function() {
     pdf.addImage(this, 10, 10);"test.pdf");
 img.crossOrigin = "";  
 img.src = "assets/images/logo.png";

Resetting remote to a certain commit

Sourcetree: resetting remote to a certain commit

  1. If you have pushed a bad commit to your remote (origin/feature/1337_MyAwesomeFeature) like below picture

Go to Remotes

  1. Go to Remotes > origin > feature > 1337_MyAwesomeFeature
  2. Right click and choose "Delete origin/feature/1337_MyAwesomeFeature" (Or change name of it if you want a backup and skip step 4.)
  3. Click "Force delete" and "OK".

enter image description here enter image description here

  1. Select your older commit and choose "Reset current branch to this commit"
  2. Choose which mode you want to have (Hard if you don't want your last changes) and "OK".

enter image description here enter image description here

  1. Push this commit to a new origin/feature/1337_MyAwesomeFeature enter image description here

  2. Your local feature branch and your remote feature branch are now on the previous (of your choice) commit enter image description here

Set default format of datetimepicker as dd-MM-yyyy

You can set CustomFormat property to "dd-MM-yyyy" in design mode and use dateTimePicker1.Text property to fetch string in "dd/MM/yyyy" format irrespective of display format.

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

JavaScript variable assignments from tuples

You can do something similar:

var tuple = Object.freeze({ name:'Bob', age:14 })

and then refer to name and age as attributes 

How to merge specific files from Git branches

You can stash and stash pop the file:

git checkout branch1
git checkout branch2
git stash
git checkout branch1
git stash pop

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:

app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.common = {};
  $ = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};

The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.

Link to a great explanation:

Kudos to this answer for showing me the way.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

The thing is all you need is a class

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:


It starts accept thread which means it will start looking for connection.

Now when you call


Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

How do I compile a .c file on my Mac?

You'll need to get a compiler. The easiest way is probably to install XCode development environment from the CDs/DVDs you got with your Mac, which will give you gcc. Then you should be able compile it like

gcc -o mybinaryfile mysourcefile.c

Best way to handle list.index(might-not-exist) in python?

It's been quite some time but it's a core part of the stdlib and has dozens of potential methods so I think it's useful to have some benchmarks for the different suggestions and include the numpy method which can be by far the fastest.

import random
from timeit import timeit
import numpy as np

l = [random.random() for i in range(10**4)]
l[10**4 - 100] = 5

# method 1
def fun1(l:list, x:int, e = -1) -> int:
    return [[i for i,elem in enumerate(l) if elem == x] or [e]][0]

# method 2
def fun2(l:list, x:int, e = -1) -> int:
    for i,elem in enumerate(l):
        if elem == x:
            return i
        return e

# method 3
def fun3(l:list, x:int, e = -1) -> int:
        idx = l.index(x)
    except ValueError:
        idx = e
    return idx

# method 4
def fun4(l:list, x:int, e = -1) -> int:
    return l.index(x) if x in l else e

l2 = np.array(l)
# method 5
def fun5(l:list or np.ndarray, x:int, e = -1) -> int:
    res = np.where(np.equal(l, x))
    if res[0].any():
        return res[0][0]
        return e

if __name__ == "__main__":
    print("Method 1:")
    print(timeit(stmt = "fun1(l, 5)", number = 1000, globals = globals()))
    print("Method 2:")
    print(timeit(stmt = "fun2(l, 5)", number = 1000, globals = globals()))
    print("Method 3:")
    print(timeit(stmt = "fun3(l, 5)", number = 1000, globals = globals()))
    print("Method 4:")
    print(timeit(stmt = "fun4(l, 5)", number = 1000, globals = globals()))
    print("Method 5, numpy given list:")
    print(timeit(stmt = "fun5(l, 5)", number = 1000, globals = globals()))
    print("Method 6, numpy given np.ndarray:")
    print(timeit(stmt = "fun5(l2, 5)", number = 1000, globals = globals()))

When run as main, this results in the following printout on my machine indicating time in seconds to complete 1000 trials of each function:

Method 1: 0.7502102799990098

Method 2: 0.7291318440002215

Method 3: 0.24142152300009911

Method 4: 0.5253471979995084

Method 5, numpy given list: 0.5045417560013448

Method 6, numpy given np.ndarray: 0.011147511999297421

Of course the question asks specifically about lists so the best solution is to use the try-except method, however the speed improvements (at least 20x here compared to try-except) offered by using the numpy data structures and operators instead of python data structures is significant and if building something on many arrays of data that is performance critical then the author should try to use numpy throughout to take advantage of the superfast C bindings. (CPython interpreter, other interpreter performances may vary)

Btw, the reason Method 5 is much slower than Method 6 is because numpy first has to convert the given list to it's own numpy array, so giving it a list doesn't break it it just doesn't fully utilise the speed possible.

How to allow only numeric (0-9) in HTML inputbox using jQuery?

function Numbers(e)
        if(e.keyCode > 47 && e.keyCode < 58)
            return true;
            return false;
        if((e.charCode > 47 && e.charCode < 58) || (e.charCode == 0))
            return true;
            return false;

I hope this will work on all browsers.

How do I get the current GPS location programmatically in Android?

I have made a project from which we can get the accurate location using Google Play Services, GPS and Network providers. This project can be found here.

Strategy in finding the best location is that first get the location from google play services if location is found then check weather it is better or not, if location found is null restart google play services and try to fetch the location from Android Location API. Register the location on change listeners and when ever the better location is found the call back returns it to the main activity.

It is very simple to use and implement in code only two classes we need to embed i.e. LocationManagerInterface and SmartLocationManager, LocationActivity is implementing the interface and using SmartLocationManager to fetch location.

 * Created by Syed Raza Mehdi Naqvi on 8/10/2016.
public interface LocationManagerInterface {
    String TAG = LocationManagerInterface.class.getSimpleName();

    void locationFetched(Location mLocation, Location oldLocation, String time, String locationProvider);


here is the location manager class

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


import java.text.DateFormat;
import java.util.Date;

 * Created by Syed Raza Mehdi Naqvi on 8/9/2016.
public class SmartLocationManager implements
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private static final String TAG = SmartLocationManager.class.getSimpleName();

    private static final int TWO_MINUTES = 1000 * 60 * 2;
    private static final int PERMISSION_REQUEST_CODE = 1000;
    private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    // default value is false but user can change it
    private String mLastLocationUpdateTime;                                                         // fetched location time
    private String locationProvider;                                                                // source of fetched location

    private Location mLastLocationFetched;                                                          // location fetched
    private Location mLocationFetched;                                                              // location fetched
    private Location networkLocation;
    private Location gpsLocation;

    private int mLocationPiority;
    private long mLocationFetchInterval;
    private long mFastestLocationFetchInterval;

    private Context mContext;                                                                       // application context
    private Activity mActivity;                                                                     // activity context
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private LocationManagerInterface mLocationManagerInterface;

    private android.location.LocationManager locationManager;
    private android.location.LocationListener locationListener;

    boolean isGPSEnabled;
    boolean isNetworkEnabled;

    private int mProviderType;
    public static final int NETWORK_PROVIDER = 1;
    public static final int ALL_PROVIDERS = 0;
    public static final int GPS_PROVIDER = 2;

//    private final double STANDARD_LOCATION_ACCURACY = 100.0;
//    private final double STANDARD_LOCATION_SEED_LIMIT = 6.95;

    public static final int LOCATION_PROVIDER_ALL_RESTICTION = 1;
    public static final int LOCATION_PROVIDER_RESTRICTION_NONE = 0;
    public static final int LOCATION_PROVIDER_GPS_ONLY_RESTICTION = 2;
    public static final int LOCATION_PROVIDER_NETWORK_ONLY_RESTICTION = 3;
    private int mForceNetworkProviders = 0;

    public SmartLocationManager(Context context, Activity activity, LocationManagerInterface locationInterface, int providerType, int locationPiority, long locationFetchInterval, long fastestLocationFetchInterval, int forceNetworkProviders) {
        mContext = context;
        mActivity = activity;
        mProviderType = providerType;

        mLocationPiority = locationPiority;
        mForceNetworkProviders = forceNetworkProviders;
        mLocationFetchInterval = locationFetchInterval;
        mFastestLocationFetchInterval = fastestLocationFetchInterval;

        mLocationManagerInterface = locationInterface;


    public void initSmartLocationManager() {

        // 1) ask for permission for Android 6 above to avoid crash
        // 2) check if gps is available
        // 3) get location using awesome strategy

        askLocationPermission();                            // for android version 6 above
        checkNetworkProviderEnable(mForceNetworkProviders);                       //

        if (isGooglePlayServicesAvailable())                // if googleplay services available
            initLocationObjts();                            // init obj for google play service and start fetching location
            getLocationUsingAndroidAPI();                   // otherwise get location using Android API

    private void initLocationObjts() {
        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setInterval(mLocationFetchInterval)                    // 10 seconds, in milliseconds
                .setFastestInterval(mFastestLocationFetchInterval);     // 1 second, in milliseconds

        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(mActivity)

        startLocationFetching();                                        // connect google play services to fetch location

    public void onConnected(Bundle connectionHint) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        } else {
            setNewLocation(getBetterLocation(location, mLocationFetched), mLocationFetched);

    public void onLocationChanged(Location location) {
        if (location == null) {
        } else {
            setNewLocation(getBetterLocation(location, mLocationFetched), mLocationFetched);

    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection suspended");

    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(mActivity, CONNECTION_FAILURE_RESOLUTION_REQUEST); // Start an Activity that tries to resolve the error
                getLocationUsingAndroidAPI();                                                                // try to get location using Android API locationManager
            } catch (IntentSender.SendIntentException e) {
        } else {
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());

    private void setNewLocation(Location location, Location oldLocation) {
        if (location != null) {
            mLastLocationFetched = oldLocation;
            mLocationFetched = location;
            mLastLocationUpdateTime = DateFormat.getTimeInstance().format(new Date());
            locationProvider = location.getProvider();
            mLocationManagerInterface.locationFetched(location, mLastLocationFetched, mLastLocationUpdateTime, location.getProvider());

    private void getLocationUsingAndroidAPI() {
        // Acquire a reference to the system Location Manager
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);


    public void captureLocation() {
        if (Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        try {
            if (mProviderType == SmartLocationManager.GPS_PROVIDER) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            } else if (mProviderType == SmartLocationManager.NETWORK_PROVIDER) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
            } else {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());

    private void setLocationListner() {
        // Define a listener that responds to location updates
        locationListener = new android.location.LocationListener() {
            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location provider.
                if (location == null) {
                } else {
                    setNewLocation(getBetterLocation(location, mLocationFetched), mLocationFetched);
//                    if (isLocationAccurate(location) && location.getAccuracy() < STANDARD_LOCATION_ACCURACY && location.getSpeed() < STANDARD_LOCATION_SEED_LIMIT) {// no use of this if
//                        setNewLocation(getBetterLocation(location, mLocationFetched), mLocationFetched);
//                    } else {
//                        setNewLocation(getBetterLocation(location, mLocationFetched), mLocationFetched);
//                    }

            public void onStatusChanged(String provider, int status, Bundle extras) {

            public void onProviderEnabled(String provider) {

            public void onProviderDisabled(String provider) {

    public Location getAccurateLocation() {
        if (Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        try {
            gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            Location newLocalGPS, newLocalNetwork;
            if (gpsLocation != null || networkLocation != null) {
                newLocalGPS = getBetterLocation(mLocationFetched, gpsLocation);
                newLocalNetwork = getBetterLocation(mLocationFetched, networkLocation);
                setNewLocation(getBetterLocation(newLocalGPS, newLocalNetwork), mLocationFetched);
        } catch (Exception ex) {
            Log.e(TAG, ex.getMessage());
        return mLocationFetched;

    protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    public void startLocationFetching() {
        if (mGoogleApiClient.isConnected()) {

    public void pauseLocationFetching() {
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);


    public void abortLocationFetching() {

        // Remove the listener you previously added
        if (locationManager != null && locationListener != null) {
            if (Build.VERSION.SDK_INT >= 23 &&
                    ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            try {
                locationManager = null;
            } catch (Exception ex) {
                Log.e(TAG, ex.getMessage());


    public void resetLocation() {
        mLocationFetched = null;
        mLastLocationFetched = null;
        networkLocation = null;
        gpsLocation = null;

    //  Android M Permission check
    public void askLocationPermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    ) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION)
                        || ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.ACCESS_FINE_LOCATION)) {

                    final AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setMessage("Please allow all permissions in App Settings for additional functionality.")
                            .setPositiveButton("Allow", new DialogInterface.OnClickListener() {
                                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                                    Toast.makeText(mContext, "Welcome", Toast.LENGTH_SHORT).show();
                            .setNegativeButton("Deny", new DialogInterface.OnClickListener() {
                                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    final AlertDialog alert = builder.create();

                } else
                    ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION
                            , Manifest.permission.ACCESS_FINE_LOCATION
                    }, PERMISSION_REQUEST_CODE);


    public void checkNetworkProviderEnable(int enforceActive) {
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            buildAlertMessageTurnOnLocationProviders("Your location providers seems to be disabled, please enable it", "OK", "Cancel");
        } else if (!isGPSEnabled && mForceNetworkProviders == LOCATION_PROVIDER_GPS_ONLY_RESTICTION) {
            buildAlertMessageTurnOnLocationProviders("Your GPS seems to be disabled, please enable it", "OK", "Cancel");
        } else if (!isNetworkEnabled && mForceNetworkProviders == LOCATION_PROVIDER_NETWORK_ONLY_RESTICTION) {
            buildAlertMessageTurnOnLocationProviders("Your Network location provider seems to be disabled, please enable it", "OK", "Cancel");
        // getting network status

        if (!isGPSEnabled && !isNetworkEnabled) {
            Toast.makeText(mContext, "Location can't be fetched!", Toast.LENGTH_SHORT).show(); // show alert

    private void buildAlertMessageTurnOnLocationProviders(String message, String positiveButtonText, String negativeButtonText) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                .setPositiveButton(positiveButtonText, new DialogInterface.OnClickListener() {
                    public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        Intent mIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                .setNegativeButton(negativeButtonText, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
        final AlertDialog alert = builder.create();;

    public Location getLastKnownLocation() {
        locationProvider = LocationManager.NETWORK_PROVIDER;
        Location lastKnownLocation = null;
        // Or use LocationManager.GPS_PROVIDER
        if (Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return lastKnownLocation;
        try {
            lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
            return lastKnownLocation;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        return lastKnownLocation;

    public boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);

        if (status == ConnectionResult.SUCCESS) {
            return true;
        } else {
            return false;

     * Determines whether one Location reading is better than the current Location fix
     * @param location            The new Location that you want to evaluate
     * @param currentBestLocation The current Location fix, to which you want to compare the new one
    protected Location getBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return location;

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return location;
            // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return currentBestLocation;

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return location;
        } else if (isNewer && !isLessAccurate) {
            return location;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return location;
        return currentBestLocation;

     * Checks whether two providers are the same

    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        return provider1.equals(provider2);

    public boolean isLocationAccurate(Location location) {
        if (location.hasAccuracy()) {
            return true;
        } else {
            return false;

    public Location getStaleLocation() {
        if (mLastLocationFetched != null) {
            return mLastLocationFetched;
        if (Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        if (mProviderType == SmartLocationManager.GPS_PROVIDER) {
            return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } else if (mProviderType == SmartLocationManager.NETWORK_PROVIDER) {
            return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            return getBetterLocation(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER), locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));

we can use it with activity or a fragment, here i am using it with activity

import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.example.raza.locationaware.location.LocationManagerInterface;
import com.example.raza.locationaware.location.SmartLocationManager;

public class LocationActivity extends AppCompatActivity implements LocationManagerInterface {

    public static final String TAG = LocationActivity.class.getSimpleName();

    SmartLocationManager mLocationManager;
    TextView mLocalTV, mLocationProviderTV, mlocationTimeTV;

    protected void onCreate(Bundle savedInstanceState) {
        mLocationManager = new SmartLocationManager(getApplicationContext(), this, this, SmartLocationManager.ALL_PROVIDERS, LocationRequest.PRIORITY_HIGH_ACCURACY, 10 * 1000, 1 * 1000, SmartLocationManager.LOCATION_PROVIDER_RESTRICTION_NONE); // init location manager
        mLocalTV = (TextView) findViewById(;
        mLocationProviderTV = (TextView) findViewById(;
        mlocationTimeTV = (TextView) findViewById(;

    protected void onStart() {

    protected void onStop() {

    protected void onPause() {

    public void locationFetched(Location mLocal, Location oldLocation, String time, String locationProvider) {
        Toast.makeText(getApplication(), "Lat : " + mLocal.getLatitude() + " Lng : " + mLocal.getLongitude(), Toast.LENGTH_LONG).show();
        mLocalTV.setText("Lat : " + mLocal.getLatitude() + " Lng : " + mLocal.getLongitude());

Hope it helps, if you can suggest any improvement kindly post it on git. Thanks.

Casting interfaces for deserialization in JSON.NET

Suppose an autofac setting like the following:

public class AutofacContractResolver : DefaultContractResolver
    private readonly IContainer _container;

    public AutofacContractResolver(IContainer container)
        _container = container;

    protected override JsonObjectContract CreateObjectContract(Type objectType)
        JsonObjectContract contract = base.CreateObjectContract(objectType);

        // use Autofac to create types that have been registered with it
        if (_container.IsRegistered(objectType))
           contract.DefaultCreator = () => _container.Resolve(objectType);

        return contract;

Then, suppose your class is like this:

public class TaskController
    private readonly ITaskRepository _repository;
    private readonly ILogger _logger;

    public TaskController(ITaskRepository repository, ILogger logger)
        _repository = repository;
        _logger = logger;

    public ITaskRepository Repository
        get { return _repository; }

    public ILogger Logger
        get { return _logger; }

Therefore, the usage of the resolver in deserialization could be like:

ContainerBuilder builder = new ContainerBuilder();
builder.Register(c => new LogService(new DateTime(2000, 12, 12))).As<ILogger>();

IContainer container = builder.Build();

AutofacContractResolver contractResolver = new AutofacContractResolver(container);

string json = @"{
      'Logger': {

// ITaskRespository and ILogger constructor parameters are injected by Autofac 
TaskController controller = JsonConvert.DeserializeObject<TaskController>(json, new JsonSerializerSettings
    ContractResolver = contractResolver


You can see more details in

SQL DELETE with JOIN another table for WHERE condition

Due to the locking implementation issues, MySQL does not allow referencing the affected table with DELETE or UPDATE.

You need to make a JOIN here instead:

DELETE  gc.*
FROM    guide_category AS gc 
        guide AS g 
ON      g.id_guide = gc.id_guide
WHERE   g.title IS NULL

or just use a NOT IN:

FROM    guide_category AS gc 
WHERE   id_guide NOT IN
        SELECT  id_guide
        FROM    guide

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {

VBA module that runs other modules

As long as the macros in question are in the same workbook and you verify the names exist, you can call those macros from any other module by name, not by module.

So if in Module1 you had two macros Macro1 and Macro2 and in Module2 you had Macro3 and Macro 4, then in another macro you could call them all:

Sub MasterMacro()
    Call Macro1
    Call Macro2
    Call Macro3
    Call Macro4
End Sub

How to get the height of a body element


html { height: 100%; }
body { min-height: 100%; }

instead of height: 100%.

The result jQuery returns is correct, because you've set the height of the body to 100%, and that's probably the height of the viewport. These three DIVs were causing an overflow, because there weren't enough space for them in the BODY element. To see what I mean, set a border to the BODY tag and check where the border ends.

Turn off iPhone/Safari input element rounding

I used a simple border-radius: 0; to remove the rounded corners for the text input types.

React - Display loading screen while DOM is rendering?

This will happen before ReactDOM.render() takes control of the root <div>. I.e. your App will not have been mounted up to that point.

So you can add your loader in your index.html file inside the root <div>. And that will be visible on the screen until React takes over.

You can use whatever loader element works best for you (svg with animation for example).

You don't need to remove it on any lifecycle method. React will replace any children of its root <div> with your rendered <App/>, as we can see in the GIF below.

Example on CodeSandbox

enter image description here


    .svgLoader {
      animation: spin 0.5s linear infinite;
      margin: auto;
    .divLoader {
      width: 100vw;
      height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }

  <div id="root">
    <div class="divLoader">
      <svg class="svgLoader" viewBox="0 0 1024 1024" width="10em" height="10em">
        <path fill="lightblue"


Using debugger to inspect the page before ReactDOM.render() runs.

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

You can check the schema at

Search for xsd:complexType name="StyleType"

This will list out all the possible Styles you can use.

Specific to your question however, you can use the Format style.


Specify the data format to use for values that appear in the textbox.

Valid values include Default, Number, Date, Time, Percentage, and Currency.

Link to MSDN:

Eclipse Indigo - Cannot install Android ADT Plugin

The best answer (by Sathya) is also applicable in Eclipse Juno.

The best node module for XML parsing

You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.

Here are some other options:

  1. libxmljs
  2. xml-stream
  3. xmldoc
  4. cheerio – implements a subset of core jQuery for XML (and HTML)

I have used xml2js and it has worked fine for me. The rest you might have to try out for yourself.

Bash function to find newest file matching pattern

The combination of find and ls works well for

  • filenames without newlines
  • not very large amount of files
  • not very long filenames

The solution:

find . -name "my-pattern" -print0 |
    xargs -r -0 ls -1 -t |
    head -1

Let's break it down:

With find we can match all interesting files like this:

find . -name "my-pattern" ...

then using -print0 we can pass all filenames safely to the ls like this:

find . -name "my-pattern" -print0 | xargs -r -0 ls -1 -t

additional find search parameters and patterns can be added here

find . -name "my-pattern" ... -print0 | xargs -r -0 ls -1 -t

ls -t will sort files by modification time (newest first) and print it one at a line. You can use -c to sort by creation time. Note: this will break with filenames containing newlines.

Finally head -1 gets us the first file in the sorted list.

Note: xargs use system limits to the size of the argument list. If this size exceeds, xargs will call ls multiple times. This will break the sorting and probably also the final output. Run

xargs  --show-limits

to check the limits on you system.

Note 2: use find . -maxdepth 1 -name "my-pattern" -print0 if you don't want to search files through subfolders.

Note 3: As pointed out by @starfry - -r argument for xargs is preventing the call of ls -1 -t, if no files were matched by the find. Thank you for the suggesion.

How to get a list column names and datatypes of a table in PostgreSQL?

To make this topic 'more complete'.

I required the column names and data types on a SELECT statement (not a table).

If you want to do this on a SELECT statement instead of an actual existing table, you can do the following:

-- your select statement here!
FROM foo
-- end your select statement

select column_name, data_type 
from information_schema.columns 
where table_name = 'abc';

Short explanation, it makes a (temp) table of your select statement, which you can 'call' upon via the query provided by (among others) @a_horse_with_no_name and @selva.

Hope this helps.

How to prevent Google Colab from disconnecting?

The javascript below works for me. Credits to

function ColabReconnect() {
    var dialog = document.querySelector("colab-dialog.yes-no-dialog");
    var dialogTitle = dialog && dialog.querySelector("div.content-area>h2");
    if (dialogTitle && dialogTitle.innerText == "Runtime disconnected") {
    } else {
        console.log("ColabReconnect is in service.");
timerId = setInterval(ColabReconnect, 60000);

In the Colab notebook, click on Ctrl + Shift + the i key simultaneously. Copy and paste the script into the prompt line. Then hit Enter before closing the editor.

By doing so, the function will check every 60 seconds to see if the onscreen connection dialog is shown, and if it is, the function would then click the ok button automatically for you.

How to implement a Map with multiple keys?

See Google Collections. Or, as you suggest, use a map internally, and have that map use a Pair. You'll have to write or find Pair<>; it's pretty easy but not part of the standard Collections.

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

I suggest using:

command $(echo $(tr '\n' ' ' < parameters.cfg))

Simply trim the end-line characters and replace them with spaces, and then push the resulting string as possible separate arguments with echo.

Get key and value of object in JavaScript?

$.each(top_brands, function() {
  var key = Object.keys(this)[0];
  var value = this[key];
  brand_options.append($("<option />").val(key).text(key + " "  + value));

This page didn't load Google Maps correctly. See the JavaScript console for technical details

There are 2 possibilities for this problem :

  1. you didn't enter the API KEY for map browser
  2. you didn't enabling the API Library especially for this Google Maps JavaScript API

just check on your Google developer console for that 2 items

Transfer data between iOS and Android via Bluetooth?

You could use p2pkit, or the free solution it was based on: Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.

How to detect a mobile device with JavaScript?

A pretty simple solution is to check for the screen width. Since almost all mobile devices have a max screen width of 480px (at present), it's pretty reliable:

if( screen.width <= 480 ) {
    location.href = '/mobile.html';

The user-agent string is also a place to look. However, the former solution is still better since even if some freaking device does not respond correctly for the user-agent, the screen width doesn't lie.

The only exception here are tablet pc's like the ipad. Those devices have a higher screen width than smartphones and I would probably go with the user-agent-string for those.

JavaScript ternary operator example with functions

The ternary style is generally used to save space. Semantically, they are identical. I prefer to go with the full if/then/else syntax because I don't like to sacrifice readability - I'm old-school and I prefer my braces.

The full if/then/else format is used for pretty much everything. It's especially popular if you get into larger blocks of code in each branch, you have a muti-branched if/else tree, or multiple else/ifs in a long string.

The ternary operator is common when you're assigning a value to a variable based on a simple condition or you are making multiple decisions with very brief outcomes. The example you cite actually doesn't make sense, because the expression will evaluate to one of the two values without any extra logic.

Good ideas:

this > that ? alert(this) : alert(that);  //nice and short, little loss of meaning

if(expression)  //longer blocks but organized and can be grasped by humans
    //35 lines of code here
else if (something_else)
    //40 more lines here
else if (another_one)  /etc, etc

Less good:

this > that ? testFucntion() ? thirdFunction() ? imlost() : whathappuh() : lostinsyntax() : thisisprobablybrokennow() ? //I'm lost in my own (awful) example by now.
//Not complete... or for average humans to read.

if(this != that)  //Ternary would be done by now
    x = this;
    x = this + 2;

A really basic rule of thumb - can you understand the whole thing as well or better on one line? Ternary is OK. Otherwise expand it.

How can I have two fixed width columns with one flexible column in the center?

Despite setting up dimensions for the columns, they still seem to shrink as the window shrinks.

An initial setting of a flex container is flex-shrink: 1. That's why your columns are shrinking.

It doesn't matter what width you specify (it could be width: 10000px), with flex-shrink the specified width can be ignored and flex items are prevented from overflowing the container.

I'm trying to set up a flexbox with 3 columns where the left and right columns have a fixed width...

You will need to disable shrinking. Here are some options:

.left, .right {
     width: 230px;
     flex-shrink: 0;


.left, .right {
     flex-basis: 230px;
     flex-shrink: 0;

OR, as recommended by the spec:

.left, .right {
    flex: 0 0 230px;    /* don't grow, don't shrink, stay fixed at 230px */

7.2. Components of Flexibility

Authors are encouraged to control flexibility using the flex shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.

More details here: What are the differences between flex-basis and width?

An additional thing I need to do is hide the right column based on user interaction, in which case the left column would still keep its fixed width, but the center column would fill the rest of the space.

Try this:

.center { flex: 1; }

This will allow the center column to consume available space, including the space of its siblings when they are removed.

Revised Fiddle

Array to Hash Ruby

Or if you have an array of [key, value] arrays, you can do:

[[1, 2], [3, 4]].inject({}) do |r, s|
  r.merge!({s[0] => s[1]})
end # => { 1 => 2, 3 => 4 }

How to loop and render elements in React.js without an array of objects to map?

You can still use map if you can afford to create a makeshift array:

    new Array(this.props.level).fill(0).map((_, index) => (
        <span className='indent' key={index}></span>

This works because new Array(n).fill(x) creates an array of size n filled with x, which can then aid map.


Difference between F5, Ctrl + F5 and click on refresh button?

CTRL+F5 Reloads the current page, ignoring cached content and generating the expected result.

Service vs IntentService in the Android platform

If someone can show me an example of something that you can be done with an IntentService and can not be done with a service and the other way around.

IntentService can not be used for Long Time Listening, Like for XMPP Listeners, its a single time operator, do the job and wave goodbye.

Also it has just one threadworker, but with a trick, you can use it as unlimited.

Select the top N values by group

I prefer @Ista solution, cause needs no extra package and is simple.
A modification of the data.table solution also solve my problem, and is more general.
My data.frame is

> str(df)
'data.frame':   579 obs. of  11 variables:
 $ trees     : num  2000 5000 1000 2000 1000 1000 2000 5000 5000 1000 ...
 $ interDepth: num  2 3 5 2 3 4 4 2 3 5 ...
 $ minObs    : num  6 4 1 4 10 6 10 10 6 6 ...
 $ shrinkage : num  0.01 0.001 0.01 0.005 0.01 0.01 0.001 0.005 0.005 0.001     ...
 $ G1        : num  0 2 2 2 2 2 8 8 8 8 ...
 $ qx        : num  0.44 0.43 0.419 0.439 0.43 ...
 $ efet      : num  43.1 40.6 39.9 39.2 38.6 ...
 $ prec      : num  0.606 0.593 0.587 0.582 0.574 0.578 0.576 0.579 0.588 0.585 ...
 $ sens      : num  0.575 0.57 0.573 0.575 0.587 0.574 0.576 0.566 0.542 0.545 ...
 $ acu       : num  0.631 0.645 0.647 0.648 0.655 0.647 0.619 0.611 0.591 0.594 ...

The data.table solution needs order on i to do the job:

> require(data.table)
> dt1 <- data.table(df)
> dt2 = dt1[order(-efet, G1, G2), head(.SD, 3), by = .(G1, G2)]
> dt2
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 5:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 6:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 7:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
 8:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
 9:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
10:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
11:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
12:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
13:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635
14:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621  

By some reason, it does not order the way pointed (probably because ordering by the groups). So, another ordering is done.

> dt2[order(G1, G2)]
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621
 5:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 6:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 7:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 8:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
 9:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
10:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
11:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
12:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
13:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
14:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635

How to send Basic Auth with axios

Hi you can do this in the following way

var username = '';
var password = ''

const token = `${username}:${password}`;
const encodedToken = Buffer.from(token).toString('base64');
const session_url = 'http://api_address/api/session_endpoint';

var config = {
  method: 'get',
  url: session_url,
  headers: { 'Authorization': 'Basic '+ encodedToken }

.then(function (response) {
.catch(function (error) {

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

For windows Go inside MongoDB\Server\4.0\bin folder and open mongod.cfg file in any text editor. Then locate the line that specifies the dbPath param. The line looks something similar

dbPath: D:\Program Files\MongoDB\Server\4.0\data

Mongodb: Failed to connect to, reason: errno:10061

Change file permission to 755 for the file:


Why is JsonRequestBehavior needed?

Improving upon the answer of @Arjen de Mooij a bit by making the AllowJsonGetAttribute applicable to mvc-controllers (not just individual action-methods):

using System.Web.Mvc;
public sealed class AllowJsonGetAttribute : ActionFilterAttribute, IActionFilter
    void IActionFilter.OnActionExecuted(ActionExecutedContext context)
        var jsonResult = context.Result as JsonResult;
        if (jsonResult == null) return;

        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

    public override void OnResultExecuting(ResultExecutingContext filterContext)
        var jsonResult = filterContext.Result as JsonResult;
        if (jsonResult == null) return;

        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

round up to 2 decimal places in java?

public static float roundFloat(float in) {
    return ((int)((in*100f)+0.5f))/100f;

Should be ok for most cases. You can still changes types if you want to be compliant with doubles for instance.

What is Join() in jQuery?

That's not a jQuery function - it's the regular Array.join function.

It converts an array to a string, putting the argument between each element.

How to get javax.comm API?

On ubuntu

 sudo apt-get install librxtx-java then 

add RXTX jars to the project which are in


Adding system header search path to Xcode

We have two options.

  1. Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.

  2. Set HEADER_SEARCH_PATHS parameter in build settings on project info. I added "${SRCROOT}" here without recursion. This setting works well for most projects.

About 2nd option:

Xcode uses Clang which has GCC compatible command set. GCC has an option -Idir which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS in Xcode project build setting.

However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.

But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}".

Or just use . to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.

The ${SRCROOT} is predefined value by Xcode. This means source directory. You can find more values in Reference document.

PS. Actually you don't have to use braces {}. I get same result with $SRCROOT. If you know the difference, please let me know.

Go: panic: runtime error: invalid memory address or nil pointer dereference

Make sure that you handle all the errors by sending a return value.

`if err!=nil{
    return nil, err

Convert LocalDateTime to LocalDateTime in UTC

I personally prefer;

as it is the most readable option.

Merge development branch with master

It would be great if you can use the Git Flow workflow. It can merge develop branch into master easily.

What you want to do is just follow the git-flow instruction mentioned here:


  • setup the git-flow project
  • create branches and merge everything to develop
  • run the command git flow release start <version_number>
  • then provide a meaningful message for the release
  • run the command git flow release finish <version_number>
  • it will merge everything into master and change the branch to master.
  • run the command git push to publish the changes to the remote master.

For more information, visit the page -

time data does not match format

To compare date time, you can try this. Datetime format can be changed

from datetime import datetime

>>> a = datetime.strptime("10/12/2013", "%m/%d/%Y")
>>> b = datetime.strptime("10/15/2013", "%m/%d/%Y")
>>> a>b

how to make a specific text on TextView BOLD

I came here to provide a more up-to-date solution, because I wasn't satisfied with the existing answers. I needed something that would work for translated texts and does not have the performance hit of using Html.fromHtml(). If you're using Kotlin, here is an extension function which will easily set multiple parts of your text to bold. This works just like Markdown, and could be extended to support other Markdown tags, if need be.

val yourString = "**This** is your **string**.".makePartialTextsBold()
val anotherString = getString(R.string.something).makePartialTextsBold()

 * This function requires that the parts of the string that need
 * to be bolded are wrapped in ** and ** tags
fun String.makePartialTextsBold(): SpannableStringBuilder {
    var copy = this
    return SpannableStringBuilder().apply {
        var setSpan = true
        var next: String
        do {
            setSpan = !setSpan
            next = if (length == 0) copy.substringBefore("**", "") else copy.substringBefore("**")
            val start = length
            if (setSpan) {
                setSpan(StyleSpan(Typeface.BOLD), start, length,
            copy = copy.removePrefix(next).removePrefix("**")
        } while (copy.isNotEmpty())

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

I got your point that you don't wanna use the built-in functions for merging or remove duplicates from the ArrayList. Your first code is running forever because the outer for loop condition is 'Always True'. Since you are adding elements to plusArray, so the size of the plusArray is increasing with every addition and hence 'i' is always less than it. As a result the condition never fails and the program runs forever. Tip: Try to first merge the list and then from the merged list remove the duplicate elements. :)

What is the parameter "next" used for in Express?

I also had problem understanding next() , but this helped

var app = require("express")();

app.get("/", function(httpRequest, httpResponse, next){
    next(); //remove this and see what happens 

app.get("/", function(httpRequest, httpResponse, next){
    httpResponse.write(" World !!!");


Android ListView Divider

The android docs warn about things dissappearing due to round-off error... Perhaps try dp instead of px, and perhaps also try > 1 first to see if it is the round-off problem.


for the section "Images with 1 pixel height/width"

What is AF_INET, and why do I need it?

You need arguments like AF_UNIX or AF_INET to specify which type of socket addressing you would be using to implement IPC socket communication. AF stands for Address Family.

As in BSD standard Socket (adopted in Python socket module) addresses are represented as follows:

  1. A single string is used for the AF_UNIX/AF_LOCAL address family. This option is used for IPC on local machines where no IP address is required.

  2. A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like '' or an IPv4 address like '', and port is an integer. Used to communicate between processes over the Internet.

AF_UNIX , AF_INET6 , AF_NETLINK , AF_TIPC , AF_CAN , AF_BLUETOOTH , AF_PACKET , AF_RDS are other option which could be used instead of AF_INET.

This thread about the differences between AF_INET and PF_INET might also be useful.

package javax.servlet.http does not exist

If you are using Ant and trying to build then you need to :

  1. Specify tomcat location by <property name="tomcat-home" value="C:\xampp\tomcat" />

  2. Add tomcat libs to your already defined path for jars by

    <path id="libs"> <fileset includes="*.jar" dir="${WEB-INF}/lib" /> <fileset includes="*.jar" dir="${tomcat-home}/bin" /> <fileset includes="*.jar" dir="${tomcat-home}/lib" /> </path>

Error in : figure margins too large, Scatter plot

Just clear the plots and try executing the code again...It worked for me

Does JavaScript have a built in stringbuilder class?

I have defined this function:

function format() {
        var args = arguments;
        if (args.length <= 1) { 
            return args;
        var result = args[0];
        for (var i = 1; i < args.length; i++) {
            result = result.replace(new RegExp("\\{" + (i - 1) + "\\}", "g"), args[i]);
        return result;

And can be called like c#:

 var text = format("hello {0}, your age is {1}.",  "John",  29);


hello John, your age is 29.

Why is the default value of the string type null instead of an empty string?

Since string is a reference type and the default value for reference type is null.

Android: How to open a specific folder via Intent and show its content in a file browser?

Thread is old but I needed this kind of feature in my application and I found a way to do it so I decided to post it if it can help anyone in my situation.

As our device fleet is composed only by Samsung Galaxy Tab 2, I just had to find the file explorer's package name, give the right path and I succeed open my file explorer where I wanted to. I wish I could use Intent.CATEGORY_APP_FILES but it is only available in API 29.

  Intent intent = context.getPackageManager().getLaunchIntentForPackage("");
  Uri uri = Uri.parse(rootPath);
  if (intent != null) {

As I said, it was easy for me because our clients have the same device but it may help others to find a workaround for their own situation.

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

Apple has announced that Swift apps will be backward compatible with iOS 7 and OS X Mavericks. The WWDC app is written in Swift.

filtering a list using LINQ

EDIT: better yet, do it like that:

var filteredProjects = 
    projects.Where(p => filteredTags.All(tag => p.Tags.Contains(tag)));

EDIT2: Honestly, I don't know which one is better, so if performance is not critical, choose the one you think is more readable. If it is, you'll have to benchmark it somehow.

Probably Intersect is the way to go:

void Main()
    var projects = new List<Project>();
    projects.Add(new Project { Name = "Project1", Tags = new int[] { 2, 5, 3, 1 } });
    projects.Add(new Project { Name = "Project2", Tags = new int[] { 1, 4, 7 } });
    projects.Add(new Project { Name = "Project3", Tags = new int[] { 1, 7, 12, 3 } });

    var filteredTags = new int []{ 1, 3 };
    var filteredProjects = projects.Where(p => p.Tags.Intersect(filteredTags).Count() == filteredTags.Length);  

class Project {
    public string Name;
    public int[] Tags;

Although that seems a little ugly at first. You may first apply Distinct to filteredTags if you aren't sure whether they are all unique in the list, otherwise the counts comparison won't work as expected.

"Too many characters in character literal error"

A char can hold a single character only, a character literal is a single character in single quote, i.e. '&' - if you have more characters than one you want to use a string, for that you have to use double quotes:

case "&&": 

Undefined reference to sqrt (or other mathematical functions)

I had the same issue, but I simply solved it by adding -lm after the command that runs my code. Example. gcc code.c -lm

Recording video feed from an IP camera over a network

Why don't you consider it supports image upload and online viewer

Sending POST data without form

function redir(data) {_x000D_
  document.getElementById('redirect').innerHTML = '<form style="display:none;" position="absolute" method="post" action="location.php"><input id="redirbtn" type="submit" name="value" value=' + data + '></form>';_x000D_
<button onclick="redir('dataToBeSent');">Next Page</button>_x000D_
<div id="redirect"></div>

You can use this method which creates a new hidden form whose "data" is sent by "post" to "location.php" when a button[Next Page] is clicked.

How to overcome root domain CNAME restrictions?

The reason this question still often arises is because, as you mentioned, somewhere somehow someone presumed as important wrote that the RFC states domain names without subdomain in front of them are not valid. If you read the RFC carefully, however, you'll find that this is not exactly what it says. In fact, RFC 1912 states:

Don't go overboard with CNAMEs. Use them when renaming hosts, but plan to get rid of them (and inform your users).

Some DNS hosts provide a way to get CNAME-like functionality at the zone apex (the root domain level, for the naked domain name) using a custom record type. Such records include, for example:

  • ALIAS at DNSimple
  • ANAME at DNS Made Easy
  • ANAME at easyDNS
  • CNAME at CloudFlare

For each provider, the setup is similar: point the ALIAS or ANAME entry for your apex domain to, just as you would with a CNAME record. Depending on the DNS provider, an empty or @ Name value identifies the zone apex.


If your DNS provider does not support such a record-type, and you are unable to switch to one that does, you will need to use subdomain redirection, which is not that hard, depending on the protocol or server software that needs to do it.

I strongly disagree with the statement that it's done only by "amateur admins" or such ideas. It's a simple "What does the name and its service need to do?" deal, and then to adapt your DNS config to serve those wishes; If your main services are web and e-mail, I don' t see any VALID reason why dropping the CNAMEs for-good would be problematic. After all, who would prefer over ? Who needs "www" if you're already set with the protocol itself? It's illogical to assume that use of a root-domainname would be invalid.

Long Press in JavaScript?

You can check the time to identify Click or Long Press [jQuery]

function AddButtonEventListener() {
try {
    var mousedowntime;
    var presstime;
    $("button[id$='" + buttonID + "']").mousedown(function() {
        var d = new Date();
        mousedowntime = d.getTime();
    $("button[id$='" + buttonID + "']").mouseup(function() {
        var d = new Date();
        presstime = d.getTime() - mousedowntime;
        if (presstime > 999/*You can decide the time*/) {
        else {
catch (err) {

how to remove untracked files in Git?

To remove untracked files / directories do:

git clean -fdx

-f - force

-d - directories too

-x - remove ignored files too ( don't use this if you don't want to remove ignored files)

Use with Caution!
These commands can permanently delete arbitrary files, that you havn't thought of at first. Please double check and read all the comments below this answer and the --help section, etc., so to know all details to fine-tune your commands and surely get the expected result.

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

i Just enabled TCP/IP,VIA,Named Pipes in Sql Server Configuration manager , My problem got solved refer this for more info Resolving Named Pipes Error 40

How to replicate background-attachment fixed on iOS

It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.

Check this comment by @PaulIrish:

Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.

you can see workarounds to this in this posts:

Fixed background image with ios7

Fixed body background scrolls with the page on iOS7

How to read a file and write into a text file?

    An example of reading a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for reading
Open "C:\Test.txt" For Input As #iFileNo
'change this filename to an existing file! (or run the example below first)

'read the file until we reach the end
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
'show the text (you will probably want to replace this line as appropriate to your program!)
MsgBox sFileText

'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
(note: an alternative to Input # is Line Input # , which reads whole lines).

An example of writing a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for writing
Open "C:\Test.txt" For Output As #iFileNo
'please note, if this file already exists it will be overwritten!

'write some example text to the file
Print #iFileNo, "first line of text"
Print #iFileNo, " second line of text"
Print #iFileNo, "" 'blank line
Print #iFileNo, "some more text!"

'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo

From Here

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Sometime you API backend could not respect the contract, and send plain text (ie. Proxy error: Could not proxy request ..., or <html><body>NOT FOUND</body></html>).

In this case, you will need to handle both cases: 1) a valid json response error, or 2) text payload as fallback (when response payload is not a valid json).

I would suggest this to handle both cases:

  // parse response as json, or else as txt
  static consumeResponseBodyAs(response, jsonConsumer, txtConsumer) {
    (async () => {
      var responseString = await response.text();
        if (responseString && typeof responseString === "string"){
         var responseParsed = JSON.parse(responseString);
         if (Api.debug) {
            console.log("RESPONSE(Json)", responseParsed);
         return jsonConsumer(responseParsed);
      } catch(error) {
        // text is not a valid json so we will consume as text
      if (Api.debug) {
        console.log("RESPONSE(Txt)", responseString);
      return txtConsumer(responseString);

then it become more easy to tune the rest handler:

class Api {
  static debug = true;

  static contribute(entryToAdd) {
    return new Promise((resolve, reject) => {
        { method: 'POST',
          headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
          body: JSON.stringify(entryToAdd) })
      .then(response => Api.consumeResponseBodyAs(response,
          (json) => {
            if (!response.ok) {
              // valid json: reject will use error.details or error.message or http status
              reject((json && json.details) || (json && json.message) || response.status);
            } else {
          (txt) => reject(txt)// not json: reject with text payload

How can I parse a local JSON file from assets folder into a ListView?

If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this. In our case we use applicationContext.
So in Utility class you can define all extension functions.


fun Context.loadJSONFromAssets(fileName: String): String {
    return { reader ->


You can define private function for load JSON data from assert like this:

 lateinit var facilityModelList: ArrayList<FacilityModel>
 private fun bindJSONDataInFacilityList() {
    facilityModelList = ArrayList<FacilityModel>()
    val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
    for (i in 0 until facilityJsonArray.length()){
        val facilityModel = FacilityModel()
        val facilityJSONObject = facilityJsonArray.getJSONObject(i)
        facilityModel.Facility = facilityJSONObject.getString("Facility")
        facilityModel.District = facilityJSONObject.getString("District")
        facilityModel.Province = facilityJSONObject.getString("Province")
        facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
        facilityModel.code = facilityJSONObject.getInt("code")
        facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
        facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")


You have to pass facilityModelList in your ListView


class FacilityModel: Serializable {
    var District: String = ""
    var Facility: String = ""
    var Province: String = ""
    var Subdistrict: String = ""
    var code: Int = 0
    var gps_latitude: Double= 0.0
    var gps_longitude: Double= 0.0

In my case JSON response start with JSONArray

    "code": 875933,
    "Province": "Eastern Cape",
    "District": "Amathole DM",
    "Subdistrict": "Amahlathi LM",
    "Facility": "Amabele Clinic",
    "gps_latitude": -32.6634,
    "gps_longitude": 27.5239

    "code": 455242,
    "Province": "Eastern Cape",
    "District": "Amathole DM",
    "Subdistrict": "Amahlathi LM",
    "Facility": "Burnshill Clinic",
    "gps_latitude": -32.7686,
    "gps_longitude": 27.055

stopPropagation vs. stopImmediatePropagation

Here is a demo to illustrate the difference:

document.querySelectorAll("button")[0].addEventListener('click', e=>{
document.querySelectorAll("button")[1].addEventListener('click', e=>{
document.querySelectorAll("button")[0].addEventListener('click', e=>{
document.querySelectorAll("button")[1].addEventListener('click', e=>{
<div onclick="alert(3)">

Notice that you can attach multiple event handlers to an event on an element.


First we should know the order of execution of Clauses i.e FROM > WHERE > GROUP BY > HAVING > DISTINCT > SELECT > ORDER BY. Since WHERE Clause gets executed before GROUP BY Clause the records cannot be filtered by applying WHERE to a GROUP BY applied records.

"HAVING is same as the WHERE clause but is applied on grouped records".

first the WHERE clause fetches the records based on the condition then the GROUP BY clause groups them accordingly and then the HAVING clause fetches the group records based on the having condition.

change figure size and figure format in matplotlib

If you need to change the figure size after you have created it, use the methods

fig = plt.figure()

where value_height and value_width are in inches. For me this is the most practical way.

Selecting non-blank cells in Excel with VBA

The following VBA code should get you started. It will copy all of the data in the original workbook to a new workbook, but it will have added 1 to each value, and all blank cells will have been ignored.

Option Explicit

Public Sub exportDataToNewBook()
    Dim rowIndex As Integer
    Dim colIndex As Integer
    Dim dataRange As Range
    Dim thisBook As Workbook
    Dim newBook As Workbook
    Dim newRow As Integer
    Dim temp

    '// set your data range here
    Set dataRange = Sheet1.Range("A1:B100")

    '// create a new workbook
    Set newBook = Excel.Workbooks.Add

    '// loop through the data in book1, one column at a time
    For colIndex = 1 To dataRange.Columns.Count
        newRow = 0
        For rowIndex = 1 To dataRange.Rows.Count
            With dataRange.Cells(rowIndex, colIndex)

            '// ignore empty cells
            If .value <> "" Then
                newRow = newRow + 1
                temp = doSomethingWith(.value)
                newBook.ActiveSheet.Cells(newRow, colIndex).value = temp
                End If

            End With
        Next rowIndex
    Next colIndex
End Sub

Private Function doSomethingWith(aValue)

    '// This is where you would compute a different value
    '// for use in the new workbook
    '// In this example, I simply add one to it.
    aValue = aValue + 1

    doSomethingWith = aValue
End Function

How to get the values of a ConfigurationSection of type NameValueSectionHandler

Here are some examples from this blog mentioned earlier:

      <add key="ConnectionString" value="data source=.;initial catalog=NorthWind;integrated security=SSPI"/>    

get values:

 NameValueCollection db = (NameValueCollection)ConfigurationSettings.GetConfig("Database");         
    labelConnection2.Text = db["ConnectionString"];


Another example:

   ProcessedDirectory ="C:\Import\Processed"
   RejectedDirectory ="C:\Import\Rejected"

get value:

Hashtable loc = (Hashtable)ConfigurationSettings.GetConfig("Locations"); 

labelImport2.Text = loc["ImportDirectory"].ToString();
labelProcessed2.Text = loc["ProcessedDirectory"].ToString();

ImportError: cannot import name main when running pip --version command in windows7 32 bit

A simple solution that works with Ubuntu, but may fix the problem on windows too:

Just call

pip install --upgrade pip

How to enable scrolling of content inside a modal?

This is how I did it purely with CSS overriding some classes:

.modal {
  height: 60%;

  .modal-body {
    height: 80%;
    overflow-y: scroll;

Hope it helps you.

How to make HTML open a hyperlink in another window or tab?

<a href="" target="_blank">Starfall</a>

Whether it opens in a tab or another window though is up to how a user has configured her browser.

Custom toast on Android: a simple example

//A custom toast class where you can show custom or default toast as desired)

public class ToastMessage {
    private Context context;
    private static ToastMessage instance;

     * @param context
    private ToastMessage(Context context) {
        this.context = context;

     * @param context
     * @return
    public synchronized static ToastMessage getInstance(Context context) {
        if (instance == null) {
            instance = new ToastMessage(context);
        return instance;

     * @param message
    public void showLongMessage(String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

     * @param message
    public void showSmallMessage(String message) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();

     * The Toast displayed via this method will display it for short period of time
     * @param message
    public void showLongCustomToast(String message) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(;
        TextView msgTv = (TextView) layout.findViewById(;
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);


     * The toast displayed by this class will display it for long period of time
     * @param message
    public void showSmallCustomToast(String message) {

        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(;
        TextView msgTv = (TextView) layout.findViewById(;
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);


BLOB to String, SQL Server

The accepted answer works for me only for the first 30 characters. This works for me:

select convert(varchar(max), convert(varbinary(max),myBlobColumn)) FROM table_name

Delete an element from a dictionary

    species = {'HI': {'1': (1215.671, 0.41600000000000004),
  '10': (919.351, 0.0012),
  '1025': (1025.722, 0.0791),
  '11': (918.129, 0.0009199999999999999),
  '12': (917.181, 0.000723),
  '1215': (1215.671, 0.41600000000000004),
  '13': (916.429, 0.0005769999999999999),
  '14': (915.824, 0.000468),
  '15': (915.329, 0.00038500000000000003),
 'CII': {'1036': (1036.3367, 0.11900000000000001), '1334': (1334.532, 0.129)}}

The following code will make a copy of dict species and delete items which are not in trans_HI

for transition in species['HI'].copy().keys():
    if transition not in trans_HI:

Delete all documents from index/type without deleting type

The above answers no longer work with ES 6.2.2 because of Strict Content-Type Checking for Elasticsearch REST Requests. The curl command which I ended up using is this:

curl -H'Content-Type: application/json' -XPOST 'localhost:9200/yourindex/_doc/_delete_by_query?conflicts=proceed' -d' { "query": { "match_all": {} }}'

Add php variable inside echo statement as href link address?

Try like


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

Or even you can try like

echo "<a href='$link_address'>Link</a>";

Or you can use PHP in HTML like


<a href="<?php echo $link_address;?>"> Link </a>

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

The Mike R's solution works for me. This is the full set of commands:

Xvfb :99 -ac -screen 0 1280x1024x24 &
export DISPLAY=:99
nice -n 10 x11vnc 2>&1 &

Later you can run google-chrome:

google-chrome --no-sandbox &

Or start google chrome via selenium driver (for example):

ng e2e --serve true --port 4200 --watch true

Protractor.conf file:

capabilities: {
    'browserName': 'chrome',
    'chromeOptions': {
        'args': ['no-sandbox']

What does "Could not find or load main class" mean?

I got this error after doing mvn eclipse:eclipse This messed up my .classpath file a little bit.

Had to change the lines in .classpath from

<classpathentry kind="src" path="src/main/java" including="**/*.java"/>
<classpathentry kind="src" path="src/main/resources" excluding="**/*.java"/>


<classpathentry kind="src" path="src/main/java" output="target/classes" />
<classpathentry kind="src" path="src/main/resources" excluding="**"  output="target/classes" />

Difference between Spring MVC and Struts MVC

Spring's Web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files. The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method. This can already be used for application controllers, but you will prefer the included implementation hierarchy, consisting of, for example AbstractController, AbstractCommandController and SimpleFormController. Application controllers will typically be subclasses of those. Note that you can choose an appropriate base class: if you don't have a form, you don't need a form controller. This is a major difference to Struts

What do Clustered and Non clustered index actually mean?

Clustered Index

Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.

The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.


Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value. The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.

You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, and execute fully covered, indexed, queries. For more information, see Create Indexes with Included Columns. For details about index key limits see Maximum Capacity Specifications for SQL Server.


Get filename in batch for loop

or Just %~F will give you the full path and full file name.

For example, if you want to register all *.ax files in the current directory....

FOR /R C:. %F in (*.ax) do regsvr32 "%~F"

This works quite nicely in Win7 (64bit) :-)

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

What you ask for is the join operation. With the how argument, you can define how unique indices are handled. Here, some article, which looks helpful concerning this point. In the example below, I left out cosmetics (like renaming columns) for simplicity.


import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )

df3 = df1.join(df2, how='outer', lsuffix='_df1', rsuffix='_df2')


               a_df1     b_df1     c_df1     a_df2     b_df2     c_df2
2014-01-01       NaN       NaN       NaN  0.109898  1.107033 -1.045376
2014-01-02  0.573754  0.169476 -0.580504 -0.664921 -0.364891 -1.215334
2014-01-03 -0.766361 -0.739894 -1.096252  0.962381 -0.860382 -0.703269
2014-01-04  0.083959 -0.123795 -1.405974  1.825832 -0.580343  0.923202
2014-01-05  1.019080 -0.086650  0.126950 -0.021402 -1.686640  0.870779
2014-01-06 -1.036227 -1.103963 -0.821523 -0.943848 -0.905348  0.430739
2014-01-07       NaN       NaN       NaN  0.312005  0.586585  1.531492
2014-01-08       NaN       NaN       NaN -0.077951 -1.189960  0.995123

How to "z-index" to make a menu always on top of the content

#right { 
  background-color: red;
  height: 300px;
  width: 300px;
  z-index: 9999;
  margin-top: 0px;
  position: absolute;

position: absolute; top:0; right:0; do the work here! :) Also remove the floating!

Create mysql table directly from CSV file using the CSV Storage engine?

There is an easier way if you are using phpMyAdmin as your MySQL front end:

  1. Create a database with the default settings.
  2. Select the database.
  3. Click "Import" at the top of the screen.
  4. Select "CSV" under "Format".
  5. Choose the options appropriate to your CSV file, open the CSV file in a text editor and reference it to get the "appropriate" options.

If you have problems, no problem, simply drop the database and try again.

Pandas count(distinct) equivalent

Using crosstab, this will return more information than groupby nunique

201301      2  1  0
201302      1  2  1

After a little bit modify ,yield the result

201301    2
201302    3
dtype: int64

jQuery: Get the cursor position of text in input without browser specific code?

You can't do this without some browser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.

For your code to get the position you could do something like this:

$("#myTextInput").bind("keydown keypress mousemove", function() {
  alert("Current position: " + $(this).caret().start);

You can test it here.

Enabling HTTPS on express.js

In express.js (since version 3) you should use that syntax:

var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

// your express configuration here

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);


In that way you provide express middleware to the native http/https server

If you want your app running on ports below 1024, you will need to use sudo command (not recommended) or use a reverse proxy (e.g. nginx, haproxy).

What does the DOCKER_HOST variable do?

It points to the docker host! I followed these steps:

$ boot2docker start

Waiting for VM and Docker daemon to start...

To connect the Docker client to the Docker daemon, please set:
    export DOCKER_HOST=tcp://

$ export DOCKER_HOST=tcp://

$ docker run ubuntu:14.04 /bin/echo 'Hello world'
Unable to find image 'ubuntu:14.04' locally
Pulling repository ubuntu
9cbaf023786c: Download complete 
511136ea3c5a: Download complete 
97fd97495e49: Download complete 
2dcbbf65536c: Download complete 
6a459d727ebb: Download complete 
8f321fc43180: Download complete 
03db2b23cf03: Download complete 
Hello world


Passing parameter to controller action from a Html.ActionLink

You are using incorrect overload. You should use this overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes

And the correct code would be

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

Laravel Advanced Wheres how to pass variable into function?

If you are using Laravel eloquent you may try this as well.

$result = self::select('*')
                    ->where('subscriptionPlan', function($query) use($activated){
                        $query->where('activated', '=', $roleId);

Converting camel case to underscore case in ruby

Rails' ActiveSupport adds underscore to the String using the following:

class String
  def underscore
    self.gsub(/::/, '/').
    tr("-", "_").

Then you can do fun stuff:

=> "camel_case"

How to find if an array contains a string

Another simple way using JOIN and INSTR

Sub Sample()
    Dim Mainfram(4) As String, strg As String
    Dim cel As Range
    Dim Delim As String

    Delim = "#"

    Mainfram(0) = "apple"
    Mainfram(1) = "pear"
    Mainfram(2) = "orange"
    Mainfram(3) = "fruit"

    strg = Join(Mainfram, Delim)
    strg = Delim & strg

    For Each cel In Selection
        If InStr(1, strg, Delim & cel.Value & Delim, vbTextCompare) Then _
        Rows(cel.Row).Style = "Accent1"
    Next cel
End Sub

failed to lazily initialize a collection of role

Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.

You can avoid this problem by

  • accessing the lazy collection within a transaction.
  • Initalizing the collection using Hibernate.initialize(obj);
  • Fetch the collection in another transaction
  • Use Fetch profiles to select lazy/non-lazy fetching runtime
  • Set fetch to non-lazy (which is generally not recommended)

Further I would recommend looking at the related links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.

How to check the function's return value if true or false

ValidateForm returns boolean,not a string.
When you do this if(ValidateForm() == 'false'), is the same of if(false == 'false'), which is not true.

function post(url, formId) {
    if(!ValidateForm()) {
        // False
    } else {
        // True

Converting VS2012 Solution to VS2010

I had a similar problem and none of the solutions above worked, so I went with an old standby that always works:

  1. Rename the folder containing the project
  2. Make a brand new project with the same name with 2010
  3. Diff the two folders and->
  4. Copy all source files directly
  5. Ignore bin/debug/release etc
  6. Diff the .csproj and copy over all lines that are relevant.
  7. If the .sln file only has one project, ignore it. If it's complex, then diff it as well.

That almost always works if you've spent 10 minutes at it and can't get it.

Note that for similar problems with older versions (2008, 2005) you can usually get away with just changing the version in the .csproj and either changing the version in the .sln or discarding it, but this doesn't seem to work for 2013.

top nav bar blocking top content of the page

The bootstrap v4 starter template css uses:

body {
  padding-top: 5rem;

What are the obj and bin folders (created by Visual Studio) used for?

I would encourage you to see this youtube video which demonstrates the difference between C# bin and obj folders and also explains how we get the benefit of incremental/conditional compilation.

C# compilation is a two-step process, see the below diagram for more details:

  1. Compiling: In compiling phase individual C# code files are compiled into individual compiled units. These individual compiled code files go in the OBJ directory.
  2. Linking: In the linking phase these individual compiled code files are linked to create single unit DLL and EXE. This goes in the BIN directory.

C# bin vs obj folders

If you compare both bin and obj directory you will find greater number of files in the "obj" directory as it has individual compiled code files while "bin" has a single unit.

bin vs obj

What are the differences between a superkey and a candidate key?

In nutshell: CANDIDATE KEY is a minimal SUPER KEY.

Where Super key is the combination of columns(or attributes) that uniquely identify any record(or tuple) in a relation(table) in RDBMS.

For instance, consider the following dependencies in a table having columns A, B, C, and D (Giving this table just for a quick example so not covering all dependencies that R could have).

Attribute set (Determinant)---Can Identify--->(Dependent)

A-----> AD

B-----> ABCD

C-----> CD





Now, B, AB, ABC, BCD identifies all columns so those four qualify for the super key.

But, B?AB; B?ABC; B?BCD hence AB, ABC, and BCD disqualified for CANDIDATE KEY as their subsets could identify the relation, so they aren't minimal and hence only B is the candidate key, not the others.

One more thing Primary key is any one among the candidate keys.

Thanks for asking

How to use order by with union all in sql?

Not an OP direct response, but I thought I would jimmy in here responding to the the OP's ERROR messsage, which may point you in another direction entirely!

All these answers are referring to an overall ORDER BY once the record set has been retrieved and you sort the lot.

What if you want to ORDER BY each portion of the UNION independantly, and still have them "joined" in the same SELECT?

SELECT pass1.* FROM 
 (SELECT TOP 1000 tblA.ID, tblA.CustomerName 
SELECT pass2.* FROM 
  (SELECT TOP 1000 tblB.ID, tblB.CustomerName 
   FROM TABLE_B AS tblB ORDER BY 2) AS pass2

Note the TOP 1000 is an arbitary number. Use a big enough number to capture all of the data you require.

Hbase quickly count number of rows

You can use the count method in hbase to count the number of rows. But yes, counting rows of a large table can be slow.count 'tablename' [interval]

Return value is the number of rows.

This operation may take a LONG time (Run ‘$HADOOP_HOME/bin/hadoop jar hbase.jar rowcount’ to run a counting mapreduce job). Current count is shown every 1000 rows by default. Count interval may be optionally specified. Scan caching is enabled on count scans by default. Default cache size is 10 rows. If your rows are small in size, you may want to increase this parameter.


hbase> count 't1'

hbase> count 't1', INTERVAL => 100000

hbase> count 't1', CACHE => 1000

hbase> count 't1', INTERVAL => 10, CACHE => 1000

The same commands also can be run on a table reference. Suppose you had a reference to table 't1', the corresponding commands would be:

hbase> t.count

hbase> t.count INTERVAL => 100000

hbase> t.count CACHE => 1000

hbase> t.count INTERVAL => 10, CACHE => 1000

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

How to retrieve data from a SQL Server database in C#?

 public Person SomeMethod(string fName)
            var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();

            Person matchingPerson = new Person();
            using (SqlConnection myConnection = new SqlConnection(con))
                string oString = "Select * from Employees where FirstName=@fName";
                SqlCommand oCmd = new SqlCommand(oString, myConnection);
                oCmd.Parameters.AddWithValue("@Fname", fName);           
                using (SqlDataReader oReader = oCmd.ExecuteReader())
                    while (oReader.Read())
                        matchingPerson.firstName = oReader["FirstName"].ToString();
                        matchingPerson.lastName = oReader["LastName"].ToString();                       

            return matchingPerson;

Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.

I've changed this to:

  "Select * from Employees where FirstName=@fName"
  oCmd.Parameters.AddWithValue("@fname", fName);  

So what this block of code is going to do is:

Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided. If that is the case, that person will be stored in a Person object (see below in my answer for the class). If there is no match, the properties of the Person object will be null.

Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you. If you want to be able to store this data, you can add them to a List<Person> .

Person class to make it cleaner:

 public class Person
            public string firstName { get; set; }
            public string lastName { get; set; }

Now to call the method:

Person x = SomeMethod("John");

You can then fill your textboxes with values coming from the Person object like so:

txtLastName.Text = x.LastName;

JDBC connection to MSSQL server in windows authentication mode

From your exception trace, it looks like there is multiple possibility for this problem

1). You have to check that your port "1433" is blocked by firewall or not. If you find that it is blocked then you should have to write "Inbound Rule". It if found in control panel -> windows firewall -> Advance Setting (Option found at Left hand side) -> Inbound Rule.

2). In SQL Server configuration Manager, your TCP/IP protocol will find in disable mode. So, you should have to enable it.

How do I remove blank pages coming between two chapters in Appendix?

In my case, I still wanted the open on odd pages option but this would produce a blank page with the chapter name in the header. I didn't want the header. And so to avoid this I used this at the end of the chapter:



This let's you keep the blank page on the last even page of the chapter but without the header.

Why use @PostConstruct?

Also constructor based initialisation will not work as intended whenever some kind of proxying or remoting is involved.

The ct will get called whenever an EJB gets deserialized, and whenever a new proxy gets created for it...

How to make flexbox items the same size?

Set them so that their flex-basis is 0 (so all elements have the same starting point), and allow them to grow:

flex: 1 1 0px

Your IDE or linter might mention that the unit of measure 'px' is redundant. If you leave it out (like: flex: 1 1 0), IE will not render this correctly. So the px is required to support Internet Explorer, as mentioned in the comments by @fabb;

How to get raw text from pdf file using java

Extracting all keywords from PDF(from a web page) file on your local machine or Base64 encoded string:

import org.apache.commons.codec.binary.Base64;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.util.HashMap;
import java.util.Map;

public class WebPagePdfExtractor {

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();

        System.out.println("From file:   " + webPagePdfExtractor.processRecord(createByteArray()).get("text"));

        System.out.println("From string: " + webPagePdfExtractor.processRecord(getArrayFromBase64EncodedString()).get("text"));

    public Map<String, Object> processRecord(byte[] byteArray) {
        Map<String, Object> map = new HashMap<>();
        try {
            PDFTextStripper stripper = new PDFTextStripper();

            PDDocument document = PDDocument.load(byteArray);
            String text = stripper.getText(document);
            map.put("text", text.replaceAll("\n|\r|\t", " "));
        } catch (Exception exception) {
        return map;

    private static byte[] getArrayFromBase64EncodedString() {
        String encodedContent = "data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0aCA1IDAgUiAvRmlsdGVyIC9GbGF0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Ek63D8xikjaUZLZ7BiNhtjRqy10846gERo7u9EC0RKRGyV0Bx0nDL3pxzg5TJANrleZEdlZMH31ytXrvWtWrPZ3Xx3fUjSneeTmNSlbyjuuX+9Y2JDmF3JOffzxqVOfnuefBXggNmb/gJTtvpCqWQ/TIVSFZ+mQh6ZvkPcRlF+MIr8Ud2SoHvC3OKne1KZ9UU0FiYzVhUqaQgvaGIoMTWwoxnKM67KFOU1BZrGTpfh/uBhz4LEnVtb5/RmvL3ljl7C/Z6ywv3H9W2/0rJYsPTtK5l6W5daN+qqWDHh+6oicYqKpyD9kyocpRTtSXcR8Em1J7muwlW1LexrtSs5JZLuScwa5pXgGyx/hdZxIeA" +
                "JTPMvxBMSaYoSmQ+nHtDywiJbzyzTe7xcfDmR5vTBcyPsKv7yBPEyXopGDxCAHOoUoppRILPQiribnP/IqOjlLka3XEo5eIbu8bCTCqRmej6+99ib/lF6im3/13ItnD8OtF4LyxN+YxQq0iwTyqjsx0mwIFVUkLkZSWbX1dmiLORxlVBGTIWSC" +
                "NNE0wTAxNnJCdIHTeHOcTzt1nM80dUbxARJ9r/0+T2BoAA0leOYPHXrlpnIwoYmg8NPdo9LFdJYupavSQ9JD09Xpmtzw3IjcyNyo3OjcmNzY3LhcWzVUi9WsWqpWVYdUh1arqzXecG+EN9Ib5Y32xnhjvXFem5POpPLJEh5Ff6LMf2vVqgwKOx" +
                "IeHbu64vXswkn3v54zdkzOzp2Oubnjy6B7dMEZfqlnubDymyWVX/SsEFbeWCy3YknJ0NxCWddt/CFxKspCjmFZ7tgfY1ibvokegcNxGL9GKZGsUI5imYqJoV/8GMZcsm0pXJhNRtkbfuofdPmBA3IYu/rV+/Oa6I3VNatqa1fVrF7Xc1xSe4um" +
        String content = encodedContent.substring("data:application/pdf;base64," .length());
        return Base64.decodeBase64(content);

    public static byte[] createByteArray() {
        String pathToBinaryData = "/bla-bla/src/main/resources/small.pdf";

        File file = new File(pathToBinaryData);
        if (!file.exists()) {
            System.out.println(" could not be found in folder " + pathToBinaryData);
            return null;

        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
        } catch (FileNotFoundException e) {

        byte fileContent[] = new byte[(int) file.length()];

        try {
        } catch (IOException e) {

        return fileContent;

What is a plain English explanation of "Big O" notation?

TLDR: Big O explains performance of an algorithm in mathematical terms.

Slower algorithms tend to run at n to the power of x or many, depending on depth of it, whereas faster ones like binary search run at O(log n), which makes it run faster as data set gets larger. Big O could be explained with other terms using n, or not even using n too (ie: O(1) ).

One can calculate Big O Looking at the most complex lines of the algorithm.

With small or unsorted datasets Big O can be surprising, as n log n complexity algorithms like binary search can be slow for smaller or unsorted sets, for a simple running example of linear search versus binary search, take a look at my JavaScript example: (algorithms written below)

function lineerSearch() {
  var t = timer('lineerSearch benchmark');
  var input =;
  for(var i = 0;i<unsortedhaystack.length - 1;i++) {
    if (unsortedhaystack[i] === input) {
      document.getElementById('result').innerHTML = 'result is... "' + unsortedhaystack[i] + '", on index: ' + i + ' of the unsorted array. Found' + ' within ' + i + ' iterations';
      return unsortedhaystack[i]; 

function binarySearch () {
  var t = timer('binarySearch benchmark');
  var firstIndex = 0;
  var lastIndex = haystack.length-1;
  var input =;

  //currently point in the half of the array
  var currentIndex = (haystack.length-1)/2 | 0;
  var iterations = 0;

  while (firstIndex <= lastIndex) {
    currentIndex = (firstIndex + lastIndex)/2 | 0;
    if (haystack[currentIndex]  < input) {
      firstIndex = currentIndex + 1;
      //console.log(currentIndex + " added, fI:"+firstIndex+", lI: "+lastIndex);
    } else if (haystack[currentIndex] > input) {
      lastIndex = currentIndex - 1;
      //console.log(currentIndex + " substracted, fI:"+firstIndex+", lI: "+lastIndex);
    } else {
      document.getElementById('result').innerHTML = 'result is... "' + haystack[currentIndex] + '", on index: ' + currentIndex + ' of the sorted array. Found' + ' within ' + iterations + ' iterations';
      return true;

How to implement a property in an interface

You should use abstract class to initialize a property. You can't inititalize in Inteface .

How to log PostgreSQL queries?

I was trying to set the log_statement in some postgres config file but in fact the file was not read by our postgres.

I confirmed that using the request :

select *
from pg_settings

log_statement   none # That was not the value i was expected for !!!

I use this way

command: postgres -c config_file=/etc/postgresql.conf

Inserting the iframe into react component

With ES6 you can now do it like this

Example Codepen URl to load

const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="">fx.</a> by ycw(<a href="">@ycw</a>) on <a href="">CodePen</a>.</iframe>'; 

A function component to load Iframe

function Iframe(props) {
  return (<div dangerouslySetInnerHTML={ {__html:  props.iframe?props.iframe:""}} />);


import React from "react";
import ReactDOM from "react-dom";
function App() {
  return (
    <div className="App">
      <h1>Iframe Demo</h1>
      <Iframe iframe={iframe} />,

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit on CodeSandbox:

Convert UNIX epoch to Date object

With library(lubridate), numeric representations of date and time saved as the number of seconds since 1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime():


[1] "2012-11-04 22:32:00 UTC"

How can I make git show a list of the files that are being tracked?

If you want to list all the files currently being tracked under the branch master, you could use this command:

git ls-tree -r master --name-only

If you want a list of files that ever existed (i.e. including deleted files):

git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'

How do I solve this error, "error while trying to deserialize parameter"

Do you have this namespace setup? You will have to ensure that this namespace matches the message namespace. If you can update your question with the xml input and possibly your data object that would be helpful.

[DataContract(Namespace = "")]
public class CustomFields
  // ...

Can I do Model->where('id', ARRAY) multiple where conditions?

You could use one of the below solutions:

$items = Item::whereIn('id', [1,2,..])->get();


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

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp


umount overflow

Convert floats to ints in Pandas?

Expanding on @Ryan G mentioned usage of the pandas.DataFrame.astype(<type>) method, one can use the errors=ignore argument to only convert those columns that do not produce an error, which notably simplifies the syntax. Obviously, caution should be applied when ignoring errors, but for this task it comes very handy.

>>> df = pd.DataFrame(np.random.rand(3, 4), columns=list('ABCD'))
>>> df *= 10
>>> print(df)
...           A       B       C       D
... 0   2.16861 8.34139 1.83434 6.91706
... 1   5.85938 9.71712 5.53371 4.26542
... 2   0.50112 4.06725 1.99795 4.75698

>>> df['E'] = list('XYZ')
>>> df.astype(int, errors='ignore')
>>> print(df)
...     A   B   C   D   E
... 0   2   8   1   6   X
... 1   5   9   5   4   Y
... 2   0   4   1   4   Z

From pandas.DataFrame.astype docs:

errors : {‘raise’, ‘ignore’}, default ‘raise’

Control raising of exceptions on invalid data for provided dtype.

  • raise : allow exceptions to be raised
  • ignore : suppress exceptions. On error return original object

New in version 0.20.0.

Password masking console application

Here's a version that adds support for the Escape key (which returns a null string)

public static string ReadPassword()
    string password = "";
    while (true)
        ConsoleKeyInfo key = Console.ReadKey(true);
        switch (key.Key)
            case ConsoleKey.Escape:
                return null;
            case ConsoleKey.Enter:
                return password;
            case ConsoleKey.Backspace:
                if (password.Length > 0) 
                    password = password.Substring(0, (password.Length - 1));
                    Console.Write("\b \b");
                password += key.KeyChar;

How to write macro for Notepad++?

I'm not sure if this helps, but I needed to create a macro to hold a snippet, so I simply recorded myself inserting the items and set a shortcut to it. Granted, I'm not using version 5.9 so there might be some slight version differences. To access the macro recorder go to Macro > Start Recording. Then you will perform your action and then go to Macro > Stop Recording. I'd recommend playing it back to ensure it's correct and then save and set your shortcut key.

Hope the helps.

C# LINQ select from list

The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.

Let's say you have a list of integers, and want to find the items that match those integers.

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var items = from p in context.Items
                 where numbers.Contains(p.ItemId)
                select p;

Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0

How to configure Docker port mapping to use Nginx as an upstream proxy?

Using docker links, you can link the upstream container to the nginx container. An added feature is that docker manages the host file, which means you'll be able to refer to the linked container using a name rather than the potentially random ip.

What is this: [Ljava.lang.Object;?

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

The naming scheme is documented in Class.getName():

If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

Element Type        Encoding
boolean             Z
byte                B
char                C
double              D
float               F
int                 I
long                J
short               S 
class or interface  Lclassname;

Yours is the last on that list. Here are some examples:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).

On a more "useful" toString for arrays

java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

Here are some examples:

int[] nums = { 1, 2, 3 };

// [I@xxxxx

// [1, 2, 3]

int[][] table = {
        { 1, },
        { 2, 3, },
        { 4, 5, 6, },

// [[I@xxxxx, [I@yyyyy, [I@zzzzz]

// [[1], [2, 3], [4, 5, 6]]

There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

Related questions