Programs & Examples On #Media url

Playing m3u8 Files with HTML Video Tag

<html>
<body>
    <video width="600" height="400" controls>
        <source src="index.m3u8" type="application/x-mpegURL">
    </video>
</body> 

Stream HLS or m3u8 files using above code. it works for desktop: ms edge browser (not working with desktop chrome) and mobile: chrome,opera mini browser.

To play on all browser use flash based media player. media player to support all browser

What is the difference between a field and a property?

Fields are ordinary member variables or member instances of a class. Properties are an abstraction to get and set their values. Properties are also called accessors because they offer a way to change and retrieve a field if you expose a field in the class as private. Generally, you should declare your member variables private, then declare or define properties for them.

  class SomeClass
  {
     int numbera; //Field

     //Property 
    public static int numbera { get; set;}

  }

Why is &#65279; appearing in my HTML?

Just use notepad ++ with encoding UTF-8 without BOM.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

Rails 4 - Strong Parameters - Nested Objects

Permitting a nested object :

params.permit( {:school => [:id , :name]}, 
               {:student => [:id, 
                            :name, 
                            :address, 
                            :city]},
                {:records => [:marks, :subject]})

How to initialize an array in Kotlin with values?

You can create an Int Array like this:

val numbers = IntArray(5, { 10 * (it + 1) })

5 is the Int Array size. the lambda function is the element init function. 'it' range in [0,4], plus 1 make range in [1,5]

origin function is:

 /**
 * An array of ints. When targeting the JVM, instances of this class are 
 * represented as `int[]`.
 * @constructor Creates a new array of the specified [size], with all elements 
 *  initialized to zero.
 */
 public class IntArray(size: Int) {
       /**
        * Creates a new array of the specified [size], where each element is 
        * calculated by calling the specified
        * [init] function. The [init] function returns an array element given 
        * its index.
        */
      public inline constructor(size: Int, init: (Int) -> Int)
  ...
 }

IntArray class defined in the Arrays.kt

JavaScript implementation of Gzip

Here are some other compression algorithms implemented in Javascript:

LINQ to Entities does not recognize the method

If anyone is looking for a VB.Net answer (as I was initially), here it is:

Public Function IsSatisfied() As Expression(Of Func(Of Charity, String, String, Boolean))

Return Function(charity, name, referenceNumber) (String.IsNullOrWhiteSpace(name) Or
                                                         charity.registeredName.ToLower().Contains(name.ToLower()) Or
                                                         charity.alias.ToLower().Contains(name.ToLower()) Or
                                                         charity.charityId.ToLower().Contains(name.ToLower())) And
                                                    (String.IsNullOrEmpty(referenceNumber) Or
                                                     charity.charityReference.ToLower().Contains(referenceNumber.ToLower()))
End Function

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Convert List to Pandas Dataframe Column

if your list looks like this: [1,2,3] you can do:

lst = [1,2,3]
df = pd.DataFrame([lst])
df.columns =['col1','col2','col3']
df

to get this:

    col1    col2    col3
0   1       2       3

alternatively you can create a column as follows:

import numpy as np
df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']
df

to get this:

  col1
0   1
1   2
2   3

Generating UML from C++ code?

If its just diagrams that you want, doxygen does a pretty good job.

Why specify @charset "UTF-8"; in your CSS file?

One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.

How should I copy Strings in Java?

String str1="this is a string";
String str2=str1.clone();

How about copy like this? I think to get a new copy is better, so that the data of str1 won't be affected when str2 is reference and modified in futher action.

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

static and extern global variables in C and C++

Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

const int varGlobal = 7;

And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

Header included by multiple files:

extern int varGlobal;

In one of your source files:

int varGlobal = 7;

How to concatenate characters in java?

I don't really consider myself a Java programmer, but just thought I'd add it here "for completeness"; using the (C-inspired) String.format static method:

String s = String.format("%s%s", 'a', 'b'); // s is "ab"

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

PHP float with 2 decimal places: .00

try this

$result = number_format($FloatNumber, 2);

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

Send request to curl with post data sourced from a file

If you are using form data to upload file,in which a parameter name must be specified , you can use:

curl -X POST -i -F "parametername=@filename" -F "additional_parm=param2" host:port/xxx

Adjusting and image Size to fit a div (bootstrap)

Most of the time,bootstrap project uses jQuery, so you can use jQuery.

Just get the width and height of parent with JQuery.offsetHeight() and JQuery.offsetWidth(), and set them to the child element with JQuery.width() and JQuery.height().

If you want to make it responsive, repeat the above steps in the $(window).resize(func), as well.

invalid use of non-static data member

In C++, nested classes are not connected to any instance of the outer class. If you want bar to access non-static members of foo, then bar needs to have access to an instance of foo. Maybe something like:

class bar {
  public:
    int getA(foo & f ) {return foo.a;}
};

Or maybe

class bar {
  private:
    foo & f;

  public:
    bar(foo & g)
    : f(g)
    {
    }

    int getA() { return f.a; }
};

In any case, you need to explicitly make sure you have access to an instance of foo.

How to install PyQt4 in anaconda?

Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:

conda install pyqt=4

This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example

conda install pyqt=4.11

would install the latest (or last) release of version 4.11.

Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.

SQL query to get the deadlocks in SQL SERVER 2008

You can use a deadlock graph and gather the information you require from the log file.

The only other way I could suggest is digging through the information by using EXEC SP_LOCK (Soon to be deprecated), EXEC SP_WHO2 or the sys.dm_tran_locks table.

SELECT  L.request_session_id AS SPID, 
    DB_NAME(L.resource_database_id) AS DatabaseName,
    O.Name AS LockedObjectName, 
    P.object_id AS LockedObjectId, 
    L.resource_type AS LockedResource, 
    L.request_mode AS LockType,
    ST.text AS SqlStatementText,        
    ES.login_name AS LoginName,
    ES.host_name AS HostName,
    TST.is_user_transaction as IsUserTransaction,
    AT.name as TransactionName,
    CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
    JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
    JOIN sys.objects O ON O.object_id = P.object_id
    JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
    JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
    JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
    JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
    CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph

http://weblogs.sqlteam.com/mladenp/archive/2008/04/29/SQL-Server-2005-Get-full-information-about-transaction-locks.aspx

Add marker to Google Map on Click

In 2017, the solution is:

map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
});

function placeMarker(position, map) {
    var marker = new google.maps.Marker({
        position: position,
        map: map
    });
    map.panTo(position);
}

How to read data of an Excel file using C#?

Using OlebDB, we can read excel file in C#, easily, here is the code while working with Web-Form, where FileUpload1 is file uploading tool

   string path = Server.MapPath("~/Uploads/");
  if (!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}
//get file path
filePath = path + Path.GetFileName(FileUpload1.FileName);
//get file extenstion
string extension = Path.GetExtension(FileUpload1.FileName);
//save file on "Uploads" folder of project
FileUpload1.SaveAs(filePath);

string conString = string.Empty;
//check file extension
switch (extension)
{
    case ".xls": //Excel 97-03.
        conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Excel03ConString;Extended Properties='Excel 8.0;HDR=YES'";
        break;
    case ".xlsx": //Excel 07 and above.
        conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Excel07ConString;Extended Properties='Excel 8.0;HDR=YES'";
        break;
}

//create datatable object
DataTable dt = new DataTable();
conString = string.Format(conString, filePath);

//Use OldDb to read excel
using (OleDbConnection connExcel = new OleDbConnection(conString))
{
    using (OleDbCommand cmdExcel = new OleDbCommand())
    {
        using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
        {
            cmdExcel.Connection = connExcel;

            //Get the name of First Sheet.
            connExcel.Open();
            DataTable dtExcelSchema;
            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
            connExcel.Close();

            //Read Data from First Sheet.
            connExcel.Open();
            cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
            odaExcel.SelectCommand = cmdExcel;
            odaExcel.Fill(dt);
            connExcel.Close();
        }
    }
}

//bind datatable with GridView
GridView1.DataSource = dt;
GridView1.DataBind();

Source : https://qawithexperts.com/article/asp-net/read-excel-file-and-import-data-into-gridview-using-datatabl/209

Console application similar code example https://qawithexperts.com/article/c-sharp/read-excel-file-in-c-console-application-example-using-oledb/168

If you need don't want to use OleDB, you can try https://github.com/ExcelDataReader/ExcelDataReader which seems to have the ability to handle both formats (.xls and .xslx)

How do I format a number with commas in T-SQL?

Please try with below query:

SELECT FORMAT(987654321,'#,###,##0')

Format with right decimal point :

SELECT FORMAT(987654321,'#,###,##0.###\,###')

Changing the page title with Jquery

I use this one:

document.title = "your_customize_title";

isolating a sub-string in a string before a symbol in SQL Server 2008

DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';

SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
       SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2

Fixed footer in Bootstrap

You can do this by wrapping the page contents in a div with the following id styling applied:

<style>
#wrap {
   min-height: 100%;
   height: auto !important;
   height: 100%;
   margin: 0 auto -60px;
}
</style>

<div id="wrap">
    <!-- Your page content here... -->
</div>

Worked for me.

How to create an object property from a variable value in JavaScript?

Ecu, if you do myObj.a, then it looks for the property named a of myObj. If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.

Where can I find "make" program for Mac OS X Lion?

It appears you can install the command line tools without getting Xcode from Downloads for Apple Developers. It required me to login with my apple account.

Alternatively, once you install Xcode from the app store, you might notice the command line tools are not installed by default. Open Xcode, go to preferences, click to the "downloads" tab, and from there you can download and install command line tools.

What is the difference between a function expression vs declaration in JavaScript?

Regarding 3rd definition:

var foo = function foo() { return 5; }

Heres an example which shows how to use possibility of recursive call:

a = function b(i) { 
  if (i>10) {
    return i;
  }
  else {
    return b(++i);
  }
}

console.log(a(5));  // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15

Edit: more interesting example with closures:

a = function(c) {
 return function b(i){
  if (i>c) {
   return i;
  }
  return b(++i);
 }
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

TypeScript error TS1005: ';' expected (II)

The issue was in my code.

In large code base, issue was not clear.

A simplified code is below:

Bad:

 collection.insertMany(
    [[],
    function (err, result) {
    });

Good:

collection.insertMany(
    [],
    function (err, result) {
    });

That is, the first one has [[], instead of normal array []

TS error was not clear enough, and it showed error in the last line with });

Hope this helps.

What is the equivalent of Select Case in Access SQL?

Consider the Switch Function as an alternative to multiple IIf() expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE approach you referenced but which is not available in Access SQL.

If you want to display a calculated field as commission:

SELECT
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        ) AS commission
FROM YourTable;

If you want to store that calculated value to a field named commission:

UPDATE YourTable
SET commission =
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        );

Either way, see whether you find Switch() easier to understand and manage. Multiple IIf()s can become mind-boggling as the number of conditions grows.

wget/curl large file from google drive

the easy way to down file from google drive you can also download file on colab

pip install gdown

import gdown

Then

url = 'https://drive.google.com/uc?id=0B9P1L--7Wd2vU3VUVlFnbTgtS2c'
output = 'spam.txt'
gdown.download(url, output, quiet=False)

or

fileid='0B9P1L7Wd2vU3VUVlFnbTgtS2c'

gdown https://drive.google.com/uc?id=+fileid

Document https://pypi.org/project/gdown/

Receiver not registered exception error?

Lets assume your broadcastReceiver is defined like this:

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        // your code

    }
};

If you are using LocalBroadcast in an Activity, then this is how you'll unregister:

LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);

If you are using LocalBroadcast in a Fragment, then this is how you'll unregister:

LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);

If you are using normal broadcast in an Activity, then this is how you'll unregister:

unregisterReceiver(broadcastReceiver);

If you are using normal broadcast in a Fragment, then this is how you'll unregister:

getActivity().unregisterReceiver(broadcastReceiver);

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

I'm going to expand your question a bit and also include the compile function.

  • compile function - use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive. (If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link' attribute is ignored if the 'compile' attribute is defined.)

  • link function - normally use for registering listener callbacks (i.e., $watch expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned. E.g., inside an <li ng-repeat...>, the link function is executed after the <li> template (tElement) has been cloned (into an iElement) for that particular <li> element. A $watch allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.

  • controller function - must be used when another directive needs to interact with this directive. E.g., on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.

    For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this (rather than on $scope), please see 'this' vs $scope in AngularJS controllers.

In general, you can put methods, $watches, etc. into either the directive's controller or link function. The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives). As Josh mentioned in a comment, you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.

How do I clear all options in a dropdown box?

The simplest solutions are the best, so You just need:

_x000D_
_x000D_
var list = document.getElementById('list');_x000D_
while (list.firstChild) {_x000D_
    list.removeChild(list.firstChild);_x000D_
}
_x000D_
<select id="list">_x000D_
  <option value="0">0</option>_x000D_
  <option value="1">1</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How get data from material-ui TextField, DropDownMenu components?

The strategy of the accepted answer is correct, but here's a generalized example that works with the current version of React and Material-UI.

The flow of data should be one-way:

  • the initialState is initialized in the constructor of the MyForm control
  • the TextAreas are populated from this initial state
  • changes to the TextAreas are propagated to the state via the handleChange callback.
  • the state is accessed from the onClick callback---right now it just writes to the console. If you want to add validation it could go there.
import * as React from "react";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";

const initialState = {
    error: null, // you could put error messages here if you wanted
    person: {
        firstname: "",
        lastname: ""
    }
};

export class MyForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = initialState;
        // make sure the "this" variable keeps its scope
        this.handleChange = this.handleChange.bind(this);
        this.onClick = this.onClick.bind(this);
    }

    render() {
        return (
            <div>
                <div>{this.state.error}</div>
                <div>
                    <TextField
                        name="firstname"
                        value={this.state.person.firstname}
                        floatingLabelText="First Name"
                        onChange={this.handleChange}/>
                    <TextField
                        name="lastname"
                        value={this.state.person.lastname}
                        floatingLabelText="Last Name"
                        onChange={this.handleChange}/>
                </div>
                <div>
                    <RaisedButton onClick={this.onClick} label="Submit!" />
                </div>
            </div>
        );
    }

    onClick() {
        console.log("when clicking, the form data is:");
        console.log(this.state.person);
    }

    handleChange(event, newValue): void {
        event.persist(); // allow native event access (see: https://facebook.github.io/react/docs/events.html)
        // give react a function to set the state asynchronously.
        // here it's using the "name" value set on the TextField
        // to set state.person.[firstname|lastname].            
        this.setState((state) => state.person[event.target.name] = newValue);

    }

}


React.render(<MyForm />, document.getElementById('app'));

(Note: You may want to write one handleChange callback per MUI Component to eliminate that ugly event.persist() call.)

Populating a ListView using an ArrayList?

Try the below answer to populate listview using ArrayList

public class ExampleActivity extends Activity
{
    ArrayList<String> movies;

    public void onCreate(Bundle saveInstanceState)
    {
       super.onCreate(saveInstanceState);
       setContentView(R.layout.list);

       // Get the reference of movies
       ListView moviesList=(ListView)findViewById(R.id.listview);

       movies = new ArrayList<String>();
       getMovies();

       // Create The Adapter with passing ArrayList as 3rd parameter
       ArrayAdapter<String> arrayAdapter =      
                 new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, movies);
       // Set The Adapter
       moviesList.setAdapter(arrayAdapter); 

       // register onClickListener to handle click events on each item
       moviesList.setOnItemClickListener(new OnItemClickListener()
       {
           // argument position gives the index of item which is clicked
           public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
           {
               String selectedmovie=movies.get(position);
               Toast.makeText(getApplicationContext(), "Movie Selected : "+selectedmovie,   Toast.LENGTH_LONG).show();
           }
        });
    }

    void getmovies()
    {
        movies.add("X-Men");
        movies.add("IRONMAN");
        movies.add("SPIDY");
        movies.add("NARNIA");
        movies.add("LIONKING");
        movies.add("AVENGERS");   
    }
}

jQuery - prevent default, then continue default

Use jQuery.one()

Attach a handler to an event for the elements. The handler is executed at most once per element per event type

$('form').one('submit', function(e) {
    e.preventDefault();
    // do your things ...

    // and when you done:
    $(this).submit();
});

The use of one prevent also infinite loop because this custom submit event is detatched after the first submit.

How to check if a column exists in a SQL Server table?

IF NOT EXISTS( SELECT NULL
            FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_name = 'TableName'
             AND table_schema = 'SchemaName'
             AND column_name = 'ColumnName')  BEGIN

  ALTER TABLE [SchemaName].[TableName] ADD [ColumnName] int(1) NOT NULL default '0';

END;

What is an AssertionError? In which case should I throw it from my own code?

I'm really late to party here, but most of the answers seem to be about the whys and whens of using assertions in general, rather than using AssertionError in particular.

assert and throw new AssertionError() are very similar and serve the same conceptual purpose, but there are differences.

  1. throw new AssertionError() will throw the exception regardless of whether assertions are enabled for the jvm (i.e., through the -ea switch).
  2. The compiler knows that throw new AssertionError() will exit the block, so using it will let you avoid certain compiler errors that assert will not.

For example:

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            throw new AssertionError();
        }
        System.out.println("n = " + n);
    }

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            assert false;
        }
        System.out.println("n = " + n);
    }

The first block, above, compiles just fine. The second block does not compile, because the compiler cannot guarantee that n has been initialized by the time the code tries to print it out.

Easiest way to convert a List to a Set in Java

I would perform a Null check before converting to set.

if(myList != null){
Set<Foo> foo = new HashSet<Foo>(myList);
}

With MySQL, how can I generate a column containing the record index in a table?

I know the OP is asking for a mysql answer but since I found the other answers not working for me,

  • Most of them fail with order by
  • Or they are simply very inefficient and make your query very slow for a fat table

So to save time for others like me, just index the row after retrieving them from database

example in PHP:

$users = UserRepository::loadAllUsersAndSortByScore();

foreach($users as $index=>&$user){
    $user['rank'] = $index+1;
}

example in PHP using offset and limit for paging:

$limit = 20; //page size
$offset = 3; //page number

$users = UserRepository::loadAllUsersAndSortByScore();

foreach($users as $index=>&$user){
    $user['rank'] = $index+1+($limit*($offset-1));
}

What does EntityManager.flush do and why do I need to use it?

EntityManager.persist() makes an entity persistent whereas EntityManager.flush() actually runs the query on your database.

So, when you call EntityManager.flush(), queries for inserting/updating/deleting associated entities are executed in the database. Any constraint failures (column width, data types, foreign key) will be known at this time.

The concrete behaviour depends on whether flush-mode is AUTO or COMMIT.

TabLayout tab selection

By default if you select a tab it will be highlighted. If you want to select Explicitly means use the given commented code under onTabSelected(TabLayout.Tab tab) with your specified tab index position. This code will explains about change fragment on tab selected position using viewpager.

public class GalleryFragment extends Fragment implements TabLayout.OnTabSelectedListener 
{
private ViewPager viewPager;public ViewPagerAdapter adapter;private TabLayout tabLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new PaymentCardFragment(), "PAYMENT CARDS");
adapter.addFragment(new LoyaltyCardFragment(), "LOYALTY CARDS");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.setOnTabSelectedListener(this);
}

@Override
public void onTabSelected(TabLayout.Tab tab) {
    //This will be called 2nd when you select a tab or swipe using viewpager
    final int position = tab.getPosition();
    Log.i("card", "Tablayout pos: " + position);
    //TabLayout.Tab tabdata=tabLayout.getTabAt(position);
    //tabdata.select();
    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            if (position == 0) {
                PaymentCardFragment paymentCardFragment = getPaymentCardFragment();
                if (paymentCardFragment != null) {
                   VerticalViewpager vp = paymentCardFragment.mypager;
                    if(vp!=null)
                    {
                      //vp.setCurrentItem(position,true);
                      vp.setCurrentItem(vp.getAdapter().getCount()-1,true);
                    }
                  }
            }
            if (position == 1) {
               LoyaltyCardFragment loyaltyCardFragment = getLoyaltyCardFragment();
                if (loyaltyCardFragment != null) {
                   VerticalViewpager vp = loyaltyCardFragment.mypager;
                    if(vp!=null)
                    {
                        vp.setCurrentItem(position);
                    }
                  }
            }
        }
    });
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {
 //This will be called 1st when you select a tab or swipe using viewpager
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
  //This will be called only when you select the already selected tab(Ex: selecting 3rd tab again and again)
}
 private PaymentCardFragment getLoyaltyCardFragment() {
    Fragment f = adapter.mFragmentList.get(viewPager.getCurrentItem());

   if(f instanceof PaymentCardFragment)
   {
    return (PaymentCardFragment) f;
   }
   return null;
 }
private LoyaltyCardFragment getPaymentCardFragment() {
    Fragment f = adapter.mFragmentList.get(viewPager.getCurrentItem());
    if(f instanceof LoyaltyCardFragment)
   {
    return (LoyaltyCardFragment) f;
   }
   return null;
 }
  class ViewPagerAdapter extends FragmentPagerAdapter {
   public List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
   public void addFragment(Fragment fragment, String title) {
   mFragmentList.add(fragment);
   mFragmentTitleList.add(title);
  }
 }
}

How do I include negative decimal numbers in this regular expression?

If you have this val="-12XXX.0abc23" and you want to extract only the decimal number, in this case this regex (^-?[0-9]\d*(\.\d+)?$) will not help you to achieve it.
this is the proper code with the correct detection regex:

_x000D_
_x000D_
var val="-12XXX.0abc23";_x000D_
val = val.replace(/^\.|[^-?\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');_x000D_
console.log(val);
_x000D_
_x000D_
_x000D_

How to fix git error: RPC failed; curl 56 GnuTLS

Additionally,this error may occurs in you are using any proxy in command line.

if you export any proxy before , unset it .

$ unset all_proxy && unset ALL_PROXY

How to make an element width: 100% minus padding?

Assuming i'm in a container with 15px padding, this is what i always use for the inner part:

width:auto;
right:15px;
left:15px;

That will stretch the inner part to whatever width it should be less the 15px either side.

Is it possible for UIStackView to scroll?

Just add this to viewdidload:

let insets = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)
scrollVIew.contentInset = insets
scrollVIew.scrollIndicatorInsets = insets

source: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/LayoutUsingStackViews.html

What is the difference between int, Int16, Int32 and Int64?

Nothing. The sole difference between the types is their size (and, hence, the range of values they can represent).

Disable time in bootstrap date time picker

This is for: Eonasdan's Bootstrap Datetimepicker

First of all I would provide an id attribute for the <input> and then initialize the datetimepicker directly for that <input> (and not for the parent container):

<div class="container">
  <input data-format="yyyy-MM-dd" type="text" id="datetimepicker"/>
</div>
<script type="text/javascript">
  $(function() {
    // Bootstrap DateTimePicker v3
    $('#datetimepicker').datetimepicker({
      pickTime: false
    });
    // Bootstrap DateTimePicker v4
    $('#datetimepicker').datetimepicker({
      format: 'DD/MM/YYYY'
    });
  });
</script>

For v3: Contrary to Ck Maurya's answer:

  • pickDate: false will disable the date and only allow to pick a time
  • pickTime: false will disable the time and only allow to pick a date (which is what you want).

For v4: Bootstrap Datetimepicker now uses the format to determine if a time-component is present. If no time component is present, it won't let you choose a time (and hide the clock icon).

Sql Server : How to use an aggregate function like MAX in a WHERE clause

As you've noticed, the WHERE clause doesn't allow you to use aggregates in it. That's what the HAVING clause is for.

HAVING t1.field3=MAX(t1.field3)

How to clear the logs properly for a Docker container?

On Docker for Windows and Mac, and probably others too, it is possible to use the tail option. For example:

docker logs -f --tail 100

This way, only the last 100 lines are shown, and you don't have first to scroll through 1M lines...

(And thus, deleting the log is probably unnecessary)

Jquery href click - how can I fire up an event?

It doesn't because the href value is not sign_up.It is #sign_up. Try like below, You need to add "#" to indicate the id of the href value.

$('a[href="#sign_up"]').click(function(){
  alert('Sign new href executed.'); 
}); 

DEMO: http://jsfiddle.net/pnGbP/

Use Mockito to mock some methods but not others

Partial mocking of a class is also supported via Spy in mockito

List list = new LinkedList();
List spy = spy(list);

//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);

//using the spy calls real methods
spy.add("one");
spy.add("two");

//size() method was stubbed - 100 is printed
System.out.println(spy.size());

Check the 1.10.19 and 2.7.22 docs for detailed explanation.

Difference between "or" and || in Ruby?

and/or are for control flow.

Ruby will not allow this as valid syntax:

false || raise "Error"

However this is valid:

false or raise "Error"

You can make the first work, with () but using or is the correct method.

false || (raise "Error")

How to call a .NET Webservice from Android using KSOAP2?

If more than one result is expected, then the getResponse() method will return a Vector containing the various responses.

In which case the offending code becomes:

Object result = envelope.getResponse();

// treat result as a vector
String resultText = null;
if (result instanceof Vector)
{
    SoapPrimitive element0 = (SoapPrimitive)((Vector) result).elementAt(0);
    resultText = element0.toString();
}

tv.setText(resultText);

Answer based on the ksoap2-android (mosabua fork)

Html.DropdownListFor selected value not being set

For me was not working so worked this way:

Controller:

int selectedId = 1;

ViewBag.ItemsSelect = new SelectList(db.Items, "ItemId", "ItemName",selectedId);

View:

@Html.DropDownListFor(m => m.ItemId,(SelectList)ViewBag.ItemsSelect)

JQuery:

$("document").ready(function () {
    $('#ItemId').val('@Model.ItemId');
});

How to create NSIndexPath for TableView

For Swift 3 it's now: IndexPath(row: rowIndex, section: sectionIndex)

Lookup City and State by Zip Google Geocode Api

couple of months back, I had the same requirement for one of my projects. I searched a bit for it and found out the following solution. This is not the only solution but I found it to one of the simpler one.

Use the webservice at http://www.webservicex.net/uszip.asmx.
Specifically GetInfoByZIP() method.

You will be able to query by any zipcode (ex: 40220) and you will have a response back as the following...

<?xml version="1.0" encoding="UTF-8"?>
 <NewDataSet>
  <Table>
   <CITY>Louisville</CITY> 
   <STATE>KY</STATE> 
   <ZIP>40220</ZIP> 
   <AREA_CODE>502</AREA_CODE> 
   <TIME_ZONE>E</TIME_ZONE> 
  </Table> 
</NewDataSet>

Hope this helps...

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

How to go to each directory and execute a command?

  #!/bin.bash
for folder_to_go in $(find . -mindepth 1 -maxdepth 1 -type d \( -name "*" \) ) ; 
                                    # you can add pattern insted of * , here it goes to any folder 
                                    #-mindepth / maxdepth 1 means one folder depth   
do
cd $folder_to_go
  echo $folder_to_go "########################################## "
  
  whatever you want to do is here

cd ../ # if maxdepth/mindepath = 2,  cd ../../
done

#you can try adding many internal for loops with many patterns, this will sneak anywhere you want

phpinfo() is not working on my CentOS server

My solution was uninstalling and installing the PHP instance (7.0 in my case) again:

sudo apt-get purge php7.0
sudo apt-get install php7.0

After that you will need to restart the Apache service:

sudo service apache2 restart

Finally, verify again in your browser with your localhost or IP address.

How to use \n new line in VB msgbox() ...?

An alternative to Environment.NewLine is to use :

Regex.Unescape("\n\tHello World\n")

from System.Text.RegularExpressions

This allows you to escape Text without Concatenating strings as you can in C#, C, java

CSS: background image on background color

Based on MDN Web Docs you can set multiple background using shorthand background property or individual properties except for background-color. In your case, you can do a trick using linear-gradient like this:

background-image: url('images/checked.png'), linear-gradient(to right, #6DB3F2, #6DB3F2);

The first item (image) in the parameter will be put on top. The second item (color background) will be put underneath the first. You can also set other properties individually. For example, to set the image size and position.

background-size: 30px 30px;
background-position: bottom right;
background-repeat: no-repeat;

Benefit of this method is you can implement it for other cases easily, for example, you want to make the blue color overlaying the image with certain opacity.

background-image: linear-gradient(to right, rgba(109, 179, 242, .6), rgba(109, 179, 242, .6)), url('images/checked.png');
background-size: cover, contain;
background-position: center, right bottom;
background-repeat: no-repeat, no-repeat;

Individual property parameters are set respectively. Because the image is put underneath the color overlay, its property parameters are also placed after color overlay parameters.

How to add a new column to a CSV file?

This code will suffice your request and I have tested on the sample code.

import csv

with open(in_path, 'r') as f_in, open(out_path, 'w') as f_out:
    csv_reader = csv.reader(f_in, delimiter=';')
    writer = csv.writer(f_out)

    for row in csv_reader:
    writer.writerow(row + [row[0]]

How to create a GUID/UUID using iOS

I've uploaded my simple but fast implementation of a Guid class for ObjC here: obj-c GUID

Guid* guid = [Guid randomGuid];
NSLog("%@", guid.description);

It can parse to and from various string formats as well.

import sun.misc.BASE64Encoder results in error compiled in Eclipse

That error is caused by your Eclipse configuration. You can reduce it to a warning. Better still, use a Base64 encoder that isn't part of a non-public API. Apache Commons has one, or when you're already on Java 1.8, then use java.util.Base64.

Conda environments not showing up in Jupyter Notebook

We have struggle a lot with this issue, and here's what works for us. If you use the conda-forge channel, it's important to make sure you are using updated packages from conda-forge, even in your Miniconda root environment.

So install Miniconda, and then do:

conda config --add channels conda-forge --force
conda update --all  -y
conda install nb_conda_kernels -y
conda env create -f custom_env.yml -q --force
jupyter notebook

and your custom environment will show up in Jupyter as an available kernel, as long as ipykernel was listed for installation in your custom_env.yml file, like this example:

name: bqplot
channels:
- conda-forge
- defaults
dependencies:
- python>=3.6
- bqplot
- ipykernel

Just to prove it working with a bunch of custom environments, here's a screen grab from Windows:

enter image description here

TreeMap sort by value

This can't be done by using a Comparator, as it will always get the key of the map to compare. TreeMap can only sort by the key.

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

Converting string format to datetime in mm/dd/yyyy

I did like this

var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);

Get the current date in java.sql.Date format

new java.sql.Date(Calendar.getInstance().getTimeInMillis());

Should we @Override an interface's method implementation?

I believe that javac behaviour has changed - with 1.5 it prohibited the annotation, with 1.6 it doesn't. The annotation provides an extra compile-time check, so if you're using 1.6 I'd go for it.

DateTimePicker: pick both date and time

I'm afraid the DateTimePicker control doesn't have the ability to do those things. It's a pretty basic (and frustrating!) control. Your best option may be to find a third-party control that does what you want.

For the option of typing the date and time manually, you could build a custom component with a TextBox/DateTimePicker combination to accomplish this, and it might work reasonably well, if third-party controls are not an option.

display HTML page after loading complete

you can also go for this.... this will only show the HTML section once javascript has loaded.

<!-- Adds the hidden style and removes it when javascript has loaded -->
<style type="text/css">
    .hideAll  {
        visibility:hidden;
     }
</style>

<script type="text/javascript">
    $(window).load(function () {
        $("#tabs").removeClass("hideAll");
    });
</script>

<div id="tabs" class="hideAll">
   ##Content##
</div>

How does Task<int> become an int?

Does an implicit conversion occur between Task<> and int?

Nope. This is just part of how async/await works.

Any method declared as async has to have a return type of:

  • void (avoid if possible)
  • Task (no result beyond notification of completion/failure)
  • Task<T> (for a logical result of type T in an async manner)

The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length - you can't make the method just return int, as the actual method will return when it hits the first await expression which hasn't already completed. So instead, it returns a Task<int> which will complete when the async method itself completes.

Note that await does the opposite - it unwraps a Task<T> to a T value, which is how this line works:

string urlContents = await getStringTask;

... but of course it unwraps it asynchronously, whereas just using Result would block until the task had completed. (await can unwrap other types which implement the awaitable pattern, but Task<T> is the one you're likely to use most often.)

This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:

public async Task<int> AccessTheWebAndDoubleAsync()
{
    var task = AccessTheWebAsync();
    int result = await task;
    return result * 2;
}

(Or simply return await AccessTheWebAsync() * 2; of course.)

How can I count text lines inside an DOM element? Can I?

getClientRects return the client rects like this and if you want to get the lines, use the follow function like this

function getRowRects(element) {
    var rects = [],
        clientRects = element.getClientRects(),
        len = clientRects.length,
        clientRect, top, rectsLen, rect, i;

    for(i=0; i<len; i++) {
        has = false;
        rectsLen = rects.length;
        clientRect = clientRects[i];
        top = clientRect.top;
        while(rectsLen--) {
            rect = rects[rectsLen];
            if (rect.top == top) {
                has = true;
                break;
            }
        }
        if(has) {
            rect.right = rect.right > clientRect.right ? rect.right : clientRect.right;
            rect.width = rect.right - rect.left;
        }
        else {
            rects.push({
                top: clientRect.top,
                right: clientRect.right,
                bottom: clientRect.bottom,
                left: clientRect.left,
                width: clientRect.width,
                height: clientRect.height
            });
        }
    }
    return rects;
}

C# Foreach statement does not contain public definition for GetEnumerator

Your CarBootSaleList class is not a list. It is a class that contain a list.

You have three options:

Make your CarBootSaleList object implement IEnumerable

or

make your CarBootSaleList inherit from List<CarBootSale>

or

if you are lazy this could almost do the same thing without extra coding

List<List<CarBootSale>>

PHPmailer sending HTML CODE

or if you have still problems you can use this

$mail->Body =  html_entity_decode($Body);

Python conversion between coordinates

The existing answers can be simplified:

from numpy import exp, abs, angle

def polar2z(r,theta):
    return r * exp( 1j * theta )

def z2polar(z):
    return ( abs(z), angle(z) )

Or even:

polar2z = lambda r,?: r * exp( 1j * ? )
z2polar = lambda z: ( abs(z), angle(z) )

Note these also work on arrays!

rS, thetaS = z2polar( [z1,z2,z3] )
zS = polar2z( rS, thetaS )

How do I print the elements of a C++ vector in GDB?

A little late to the party, so mostly a reminder to me next time I do this search!

I have been able to use:

p/x *(&vec[2])@4

to print 4 elements (as hex) from vec starting at vec[2].

Set CSS property in Javascript?

This works well with most CSS properties if there are no hyphens in them.

var element = document.createElement('select');
element.style.width = "100px";

For properties with hyphens in them like max-width, you should convert the sausage-case to camelCase

var element = document.createElement('select');
element.style.maxWidth = "100px";

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

The solution would be to install redistributable packages on build server agent. It can be accomplished multiple ways, out of which 3 are described below. Pick one that suits you best.

Use installer with UI

this is the original answer

Right now, in 2017, you can install WebApplication redists with MSBuildTools. Just go to this page that will download MSBuild 2017 Tools and while installation click Web development build tools to get these targets installed as well: enter image description here

This will lead to installing missing libraries in C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Microsoft\VisualStudio\v15.0\WebApplications by default

Use command line

disclaimer I haven't tested any of the following proposals

As @PaulHicks and @WaiHaLee suggested in comments, it can also be installed in headless mode (no ui) from CLI, that might actually be preferable way of solving the problem on remove server.

  • Solution A - using package manager (choco)
choco install visualstudio2017-workload-webbuildtools
  • Solution B - run installer in headless mode

    Notice, this is the same installer that has been proposed to be used in original answer

vs_BuildTools.exe --add Microsoft.VisualStudio.Workload.WebBuildTools --passive

How to get the URL of the current page in C#

Just sharing as this was my solution thanks to Canavar's post.

If you have something like this:

"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"

or like this:

"https://www.something.com/index.html?a=123&b=4567"

and you only want the part that a user would type in then this will work:

String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");

which would result in these:

"http://localhost:1234/"
"https://www.something.com/"

What is difference between cacerts and keystore?

Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security. Your JAVA_HOME should always be ../JAVA/JDK.

What difference does .AsNoTracking() make?

AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers).

This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.

For these cases the "key" can be set to any non-nullable column but then AsNoTracking() must be used with every query else records (duplicate by key) will be skipped.

Use ffmpeg to add text subtitles

I tried using MP4Box for this task, but it couldn't handle the M4V I was dealing with. I had success embedding the SRT as soft subtitles with ffmpeg with the following command line:

ffmpeg -i input.m4v -i input.srt -vcodec copy -acodec copy -scodec copy -map 0:0 -map 0:1 -map 1:0 -y output.mkv

Like you I had to use an MKV output file - I wasn't able to create an M4V file.

Twitter bootstrap float div right

<p class="pull-left">Text left</p>
<p class="text-right">Text right in same line</p>

This work for me.

edit: An example with your snippet:

_x000D_
_x000D_
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.css');_x000D_
 .container {_x000D_
    margin-top: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
    <div class="row-fluid">_x000D_
        <div class="span6 pull-left">_x000D_
            <p>Text left</p>_x000D_
        </div>_x000D_
        <div class="span6 text-right">_x000D_
            <p>text right</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

Thunks versus Sagas

Redux-Thunk and Redux-Saga differ in a few important ways, both are middleware libraries for Redux (Redux middleware is code that intercepts actions coming into the store via the dispatch() method).

An action can be literally anything, but if you're following best practices, an action is a plain javascript object with a type field, and optional payload, meta, and error fields. e.g.

const loginRequest = {
    type: 'LOGIN_REQUEST',
    payload: {
        name: 'admin',
        password: '123',
    }, };

Redux-Thunk

In addition to dispatching standard actions, Redux-Thunk middleware allows you to dispatch special functions, called thunks.

Thunks (in Redux) generally have the following structure:

export const thunkName =
   parameters =>
        (dispatch, getState) => {
            // Your application logic goes here
        };

That is, a thunk is a function that (optionally) takes some parameters and returns another function. The inner function takes a dispatch function and a getState function -- both of which will be supplied by the Redux-Thunk middleware.

Redux-Saga

Redux-Saga middleware allows you to express complex application logic as pure functions called sagas. Pure functions are desirable from a testing standpoint because they are predictable and repeatable, which makes them relatively easy to test.

Sagas are implemented through special functions called generator functions. These are a new feature of ES6 JavaScript. Basically, execution jumps in and out of a generator everywhere you see a yield statement. Think of a yield statement as causing the generator to pause and return the yielded value. Later on, the caller can resume the generator at the statement following the yield.

A generator function is one defined like this. Notice the asterisk after the function keyword.

function* mySaga() {
    // ...
}

Once the login saga is registered with Redux-Saga. But then the yield take on the the first line will pause the saga until an action with type 'LOGIN_REQUEST' is dispatched to the store. Once that happens, execution will continue.

For more details see this article.

Calling the base class constructor from the derived class constructor

but I can't initialize my derived class, I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ?? so I'm thinking maybe in the PetStore default constructor I can call Farm()... so any Idea ???

Don't panic.

Farm constructor will be called in the constructor of PetStore, automatically.

See the base class inheritance calling rules: What are the rules for calling the superclass constructor?

how to read System environment variable in Spring applicationContext

You are close :o) Spring 3.0 adds Spring Expression Language. You can use

<util:properties id="dbProperties" 
    location="classpath:config_#{systemProperties['env']}/db.properties" />

Combined with java ... -Denv=QA should solve your problem.

Note also a comment by @yiling:

In order to access system environment variable, that is OS level variables as amoe commented, we can simply use "systemEnvironment" instead of "systemProperties" in that EL. Like #{systemEnvironment['ENV_VARIABLE_NAME']}

Java: Local variable mi defined in an enclosing scope must be final or effectively final

As I can see the array is of String only.For each loop can be used to get individual element of the array and put them in local inner class for use.

Below is the code snippet for it :

     //WorkAround 
    for (String color : colors ){

String pos = Character.toUpperCase(color.charAt(0)) + color.substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(color));

Jmi.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JMenuItem item = (JMenuItem) e.getSource();
            IconA icon = (IconA) item.getIcon();
            // HERE YOU USE THE String color variable and no errors!!!
            Color kolorIkony = getColour(color); 
            textArea.setForeground(kolorIkony);
        }
    });

    mnForeground.add(Jmi);
}

}

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

C# get and set properties for a List Collection

Your setters are strange, which is why you may be seeing a problem.

First, consider whether you even need these setters - if so, they should take a List<string>, not just a string:

set
{
    _subHead = value;
}

These lines:

newSec.subHead.Add("test string");

Are calling the getter and then call Add on the returned List<string> - the setter is not invoked.

How can I format DateTime to web UTC format?

Why don't just use The Round-trip ("O", "o") Format Specifier?

The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.

The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. In this string, the pairs of single quotation marks that delimit individual characters, such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot be changed. The apostrophes do not appear in the output string.

The O" or "o" standard format specifier (and the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string) takes advantage of the three ways that ISO 8601 represents time zone information to preserve the Kind property of DateTime values:

public class Example
{
   public static void Main()
   {
       DateTime dat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                   DateTimeKind.Unspecified);
       Console.WriteLine("{0} ({1}) --> {0:O}", dat, dat.Kind); 

       DateTime uDat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                    DateTimeKind.Utc);
       Console.WriteLine("{0} ({1}) --> {0:O}", uDat, uDat.Kind);

       DateTime lDat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                    DateTimeKind.Local);
       Console.WriteLine("{0} ({1}) --> {0:O}\n", lDat, lDat.Kind);

       DateTimeOffset dto = new DateTimeOffset(lDat);
       Console.WriteLine("{0} --> {0:O}", dto);
   }
}
// The example displays the following output: 
//    6/15/2009 1:45:30 PM (Unspecified) --> 2009-06-15T13:45:30.0000000 
//    6/15/2009 1:45:30 PM (Utc) --> 2009-06-15T13:45:30.0000000Z 
//    6/15/2009 1:45:30 PM (Local) --> 2009-06-15T13:45:30.0000000-07:00 
//     
//    6/15/2009 1:45:30 PM -07:00 --> 2009-06-15T13:45:30.0000000-07:00

How to cin to a vector

You can simply do this with the help of for loop
->Ask on runtime from a user (how many inputs he want to enter) and the treat same like arrays.

int main() {
        int sizz,input;
        std::vector<int> vc1;

        cout<< "How many Numbers you want to enter : ";
        cin >> sizz;
        cout << "Input Data : " << endl;
        for (int i = 0; i < sizz; i++) {//for taking input form the user
            cin >> input;
            vc1.push_back(input);
        }
        cout << "print data of vector : " << endl;
        for (int i = 0; i < sizz; i++) {
            cout << vc1[i] << endl;
        }
     }

Stopping a thread after a certain amount of time

If you want the threads to stop when your program exits (as implied by your example), then make them daemon threads.

If you want your threads to die on command, then you have to do it by hand. There are various methods, but all involve doing a check in your thread's loop to see if it's time to exit (see Nix's example).

How to make Twitter Bootstrap menu dropdown on hover rather than click

This is built into Bootstrap 3. Just add this to your CSS:

.dropdown:hover .dropdown-menu {
    display: block;
}

How can I save application settings in a Windows Forms application?

I don't like the proposed solution of using web.config or app.config. Try reading your own XML. Have a look at XML Settings Files – No more web.config.

Apache HttpClient Interim Error: NoHttpResponseException

I have faced same issue, I resolved by adding "connection: close" as extention,

Step 1: create a new class ConnectionCloseExtension

import com.github.tomakehurst.wiremock.common.FileSource;
import com.github.tomakehurst.wiremock.extension.Parameters;
import com.github.tomakehurst.wiremock.extension.ResponseTransformer;
import com.github.tomakehurst.wiremock.http.HttpHeader;
import com.github.tomakehurst.wiremock.http.HttpHeaders;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.Response;

public class ConnectionCloseExtension extends ResponseTransformer {
  @Override
  public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
    return Response.Builder
        .like(response)
        .headers(HttpHeaders.copyOf(response.getHeaders())
            .plus(new HttpHeader("Connection", "Close")))
        .build();
  }

  @Override
  public String getName() {
    return "ConnectionCloseExtension";
  }
}

Step 2: set extension class in wireMockServer like below,

final WireMockServer wireMockServer = new WireMockServer(options()
                .extensions(ConnectionCloseExtension.class)
                .port(httpPort));

cannot call member function without object

just add static keyword at the starting of the function return type.. and then you can access the member function of the class without object:) for ex:

static void Name_pairs::read_names()
{
   cout << "Enter name: ";
   cin >> name;
   names.push_back(name);
   cout << endl;
}

Is it possible to have placeholders in strings.xml for runtime values?

When you want to use a parameter from the actual strings.xml file without using any Java code:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
  <!ENTITY appname "WhereDat">
  <!ENTITY author "Oded">
]>

<resources>
    <string name="app_name">&appname;</string>
    <string name="description">The &appname; app was created by &author;</string>
</resources>

This does not work across resource files, i.e. variables must be copied into each XML file that needs them.

Deleting a local branch with Git

Like others mentioned you cannot delete current branch in which you are working.

In my case, I have selected "Test_Branch" in Visual Studio and was trying to delete "Test_Branch" from Sourcetree (Git GUI). And was getting below error message.

Cannot delete branch 'Test_Branch' checked out at '[directory location]'.

Switched to different branch in Visual Studio and was able to delete "Test_Branch" from Sourcetree.

I hope this helps someone who is using Visual Studio & Sourcetree.

WebView link click open default browser

You can use an Intent for this:

Uri uriUrl = Uri.parse("http://www.google.com/"); 
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);  
startActivity(launchBrowser);  

How do you delete a column by name in data.table?

Very simple option in case you have many individual columns to delete in a data table and you want to avoid typing in all column names #careadviced

dt <- dt[, -c(1,4,6,17,83,104)]

This will remove columns based on column number instead.

It's obviously not as efficient because it bypasses data.table advantages but if you're working with less than say 500,000 rows it works fine

.war vs .ear file

A WAR (Web Archive) is a module that gets loaded into a Web container of a Java Application Server. A Java Application Server has two containers (runtime environments) - one is a Web container and the other is a EJB container.

The Web container hosts Web applications based on JSP or the Servlets API - designed specifically for web request handling - so more of a request/response style of distributed computing. A Web container requires the Web module to be packaged as a WAR file - that is a special JAR file with a web.xml file in the WEB-INF folder.

An EJB container hosts Enterprise java beans based on the EJB API designed to provide extended business functionality such as declarative transactions, declarative method level security and multiprotocol support - so more of an RPC style of distributed computing. EJB containers require EJB modules to be packaged as JAR files - these have an ejb-jar.xml file in the META-INF folder.

Enterprise applications may consist of one or more modules that can either be Web modules (packaged as a WAR file), EJB modules (packaged as a JAR file), or both of them. Enterprise applications are packaged as EAR files - these are special JAR files containing an application.xml file in the META-INF folder.

Basically, EAR files are a superset containing WAR files and JAR files. Java Application Servers allow deployment of standalone web modules in a WAR file, though internally, they create EAR files as a wrapper around WAR files. Standalone web containers such as Tomcat and Jetty do not support EAR files - these are not full-fledged Application servers. Web applications in these containers are to be deployed as WAR files only.

In application servers, EAR files contain configurations such as application security role mapping, EJB reference mapping and context root URL mapping of web modules.

Apart from Web modules and EJB modules, EAR files can also contain connector modules packaged as RAR files and Client modules packaged as JAR files.

Tomcat view catalina.out log file

Just be aware also that catalina.out can be renamed - it can be set in /bin/catalina.sh with the CATALINA_OUT environment variable.

Capturing Groups From a Grep RegEx

I prefer the one line python or perl command, both often included in major linux disdribution

echo $'
<a href="http://stackoverflow.com">
</a>
<a href="http://google.com">
</a>
' |  python -c $'
import re
import sys
for i in sys.stdin:
  g=re.match(r\'.*href="(.*)"\',i);
  if g is not None:
    print g.group(1)
'

and to handle files:

ls *.txt | python -c $'
import sys
import re
for i in sys.stdin:
  i=i.strip()
  f=open(i,"r")
  for j in f:
    g=re.match(r\'.*href="(.*)"\',j);
    if g is not None:
      print g.group(1)
  f.close()
'

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

This is an addition to the answer by Abdull somewhere in this thread:

I had to modify instead of adding a port

semanage port -m -t http_port_t -p tcp 5000

because I get this error on adding the port

ValueError: Port tcp/5000 already defined

How much overhead does SSL impose?

Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]

Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.

So, to summarize:

Transfer on established connection:

  • Delay: nearly none
  • CPU: negligible
  • Bandwidth: negligible

First connection establishment:

  • Delay: additional round-trips
  • Bandwidth: several kilobytes (certificates)
  • CPU on client: medium
  • CPU on server: high

Subsequent connection establishments:

  • Delay: additional round-trip (not sure if one or multiple, may be implementation-dependant)
  • Bandwidth: negligible
  • CPU: nearly none

How to "perfectly" override a dict?

How can I make as "perfect" a subclass of dict as possible?

The end goal is to have a simple dict in which the keys are lowercase.

  • If I override __getitem__/__setitem__, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?

  • Am I preventing pickling from working, and do I need to implement __setstate__ etc?

  • Do I need repr, update and __init__?

  • Should I just use mutablemapping (it seems one shouldn't use UserDict or DictMixin)? If so, how? The docs aren't exactly enlightening.

The accepted answer would be my first approach, but since it has some issues, and since no one has addressed the alternative, actually subclassing a dict, I'm going to do that here.

What's wrong with the accepted answer?

This seems like a rather simple request to me:

How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.

The accepted answer doesn't actually subclass dict, and a test for this fails:

>>> isinstance(MyTransformedDict([('Test', 'test')]), dict)
False

Ideally, any type-checking code would be testing for the interface we expect, or an abstract base class, but if our data objects are being passed into functions that are testing for dict - and we can't "fix" those functions, this code will fail.

Other quibbles one might make:

  • The accepted answer is also missing the classmethod: fromkeys.
  • The accepted answer also has a redundant __dict__ - therefore taking up more space in memory:

    >>> s.foo = 'bar'
    >>> s.__dict__
    {'foo': 'bar', 'store': {'test': 'test'}}
    

Actually subclassing dict

We can reuse the dict methods through inheritance. All we need to do is create an interface layer that ensures keys are passed into the dict in lowercase form if they are strings.

If I override __getitem__/__setitem__, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?

Well, implementing them each individually is the downside to this approach and the upside to using MutableMapping (see the accepted answer), but it's really not that much more work.

First, let's factor out the difference between Python 2 and 3, create a singleton (_RaiseKeyError) to make sure we know if we actually get an argument to dict.pop, and create a function to ensure our string keys are lowercase:

from itertools import chain
try:              # Python 2
    str_base = basestring
    items = 'iteritems'
except NameError: # Python 3
    str_base = str, bytes, bytearray
    items = 'items'

_RaiseKeyError = object() # singleton for no-default behavior

def ensure_lower(maybe_str):
    """dict keys can be any hashable object - only call lower if str"""
    return maybe_str.lower() if isinstance(maybe_str, str_base) else maybe_str

Now we implement - I'm using super with the full arguments so that this code works for Python 2 and 3:

class LowerDict(dict):  # dicts take a mapping or iterable as their optional first argument
    __slots__ = () # no __dict__ - that would be redundant
    @staticmethod # because this doesn't make sense as a global function.
    def _process_args(mapping=(), **kwargs):
        if hasattr(mapping, items):
            mapping = getattr(mapping, items)()
        return ((ensure_lower(k), v) for k, v in chain(mapping, getattr(kwargs, items)()))
    def __init__(self, mapping=(), **kwargs):
        super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
    def __getitem__(self, k):
        return super(LowerDict, self).__getitem__(ensure_lower(k))
    def __setitem__(self, k, v):
        return super(LowerDict, self).__setitem__(ensure_lower(k), v)
    def __delitem__(self, k):
        return super(LowerDict, self).__delitem__(ensure_lower(k))
    def get(self, k, default=None):
        return super(LowerDict, self).get(ensure_lower(k), default)
    def setdefault(self, k, default=None):
        return super(LowerDict, self).setdefault(ensure_lower(k), default)
    def pop(self, k, v=_RaiseKeyError):
        if v is _RaiseKeyError:
            return super(LowerDict, self).pop(ensure_lower(k))
        return super(LowerDict, self).pop(ensure_lower(k), v)
    def update(self, mapping=(), **kwargs):
        super(LowerDict, self).update(self._process_args(mapping, **kwargs))
    def __contains__(self, k):
        return super(LowerDict, self).__contains__(ensure_lower(k))
    def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
        return type(self)(self)
    @classmethod
    def fromkeys(cls, keys, v=None):
        return super(LowerDict, cls).fromkeys((ensure_lower(k) for k in keys), v)
    def __repr__(self):
        return '{0}({1})'.format(type(self).__name__, super(LowerDict, self).__repr__())

We use an almost boiler-plate approach for any method or special method that references a key, but otherwise, by inheritance, we get methods: len, clear, items, keys, popitem, and values for free. While this required some careful thought to get right, it is trivial to see that this works.

(Note that haskey was deprecated in Python 2, removed in Python 3.)

Here's some usage:

>>> ld = LowerDict(dict(foo='bar'))
>>> ld['FOO']
'bar'
>>> ld['foo']
'bar'
>>> ld.pop('FoO')
'bar'
>>> ld.setdefault('Foo')
>>> ld
{'foo': None}
>>> ld.get('Bar')
>>> ld.setdefault('Bar')
>>> ld
{'bar': None, 'foo': None}
>>> ld.popitem()
('bar', None)

Am I preventing pickling from working, and do I need to implement __setstate__ etc?

pickling

And the dict subclass pickles just fine:

>>> import pickle
>>> pickle.dumps(ld)
b'\x80\x03c__main__\nLowerDict\nq\x00)\x81q\x01X\x03\x00\x00\x00fooq\x02Ns.'
>>> pickle.loads(pickle.dumps(ld))
{'foo': None}
>>> type(pickle.loads(pickle.dumps(ld)))
<class '__main__.LowerDict'>

__repr__

Do I need repr, update and __init__?

We defined update and __init__, but you have a beautiful __repr__ by default:

>>> ld # without __repr__ defined for the class, we get this
{'foo': None}

However, it's good to write a __repr__ to improve the debugability of your code. The ideal test is eval(repr(obj)) == obj. If it's easy to do for your code, I strongly recommend it:

>>> ld = LowerDict({})
>>> eval(repr(ld)) == ld
True
>>> ld = LowerDict(dict(a=1, b=2, c=3))
>>> eval(repr(ld)) == ld
True

You see, it's exactly what we need to recreate an equivalent object - this is something that might show up in our logs or in backtraces:

>>> ld
LowerDict({'a': 1, 'c': 3, 'b': 2})

Conclusion

Should I just use mutablemapping (it seems one shouldn't use UserDict or DictMixin)? If so, how? The docs aren't exactly enlightening.

Yeah, these are a few more lines of code, but they're intended to be comprehensive. My first inclination would be to use the accepted answer, and if there were issues with it, I'd then look at my answer - as it's a little more complicated, and there's no ABC to help me get my interface right.

Premature optimization is going for greater complexity in search of performance. MutableMapping is simpler - so it gets an immediate edge, all else being equal. Nevertheless, to lay out all the differences, let's compare and contrast.

I should add that there was a push to put a similar dictionary into the collections module, but it was rejected. You should probably just do this instead:

my_dict[transform(key)]

It should be far more easily debugable.

Compare and contrast

There are 6 interface functions implemented with the MutableMapping (which is missing fromkeys) and 11 with the dict subclass. I don't need to implement __iter__ or __len__, but instead I have to implement get, setdefault, pop, update, copy, __contains__, and fromkeys - but these are fairly trivial, since I can use inheritance for most of those implementations.

The MutableMapping implements some things in Python that dict implements in C - so I would expect a dict subclass to be more performant in some cases.

We get a free __eq__ in both approaches - both of which assume equality only if another dict is all lowercase - but again, I think the dict subclass will compare more quickly.

Summary:

  • subclassing MutableMapping is simpler with fewer opportunities for bugs, but slower, takes more memory (see redundant dict), and fails isinstance(x, dict)
  • subclassing dict is faster, uses less memory, and passes isinstance(x, dict), but it has greater complexity to implement.

Which is more perfect? That depends on your definition of perfect.

Specify the from user when sending email using the mail command

You can append sendmail options to the end of the mail command by first adding --. -f is the command on sendmail to set the from address. So you can do this:

mail [email protected] -- -f [email protected]

How to run a single RSpec test?

Not sure how long this has bee available but there is an Rspec configuration for run filtering - so now you can add this to your spec_helper.rb:

RSpec.configure do |config|
  config.filter_run_when_matching :focus
end

And then add a focus tag to the it, context or describe to run only that block:

it 'runs a test', :focus do
  ...test code
end

RSpec documentation:

https://www.rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration#filter_run_when_matching-instance_method

How to select the Date Picker In Selenium WebDriver

You can directly use following javascript

((JavascriptExecutor)driver).executeScript("document.getElementById('fromDate').setAttribute('value','10 Jan 2013')")

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

Always Use your selection as List

Eg:

var tempGroupOfFiles = Entities.Submited_Files.Where(r => r.FileStatusID == 10 && r.EventID == EventId).ToList();

Then Loop through the Collection while save changes

 foreach (var item in tempGroupOfFiles)
             {
                 var itemToUpdate = item;
                 if (itemToUpdate != null)
                 {
                     itemToUpdate.FileStatusID = 8;
                     itemToUpdate.LastModifiedDate = DateTime.Now;
                 }
                 Entities.SaveChanges();

             }

How to handle notification when app in background in Firebase

Using this code you can get the notification in background/foreground and also put action:

//Data should come in this format from the notification
{
  "to": "/xyz/Notifications",
  "data": {
      "key1": "title notification",
      "key2": "description notification"
  }
}

In-App use this code:

  @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
      String key1Data = remoteMessage.getData().get("key1");
      // use key1Data to according to your need
    }

100% Min Height CSS layout

First you should create a div with id='footer' after your content div and then simply do this.

Your HTML should look like this:

<html>
    <body>
        <div id="content">
            ...
        </div>
        <div id="footer"></div>
    </body>
</html>

And the CSS:

?html, body {
    height: 100%;   
}
#content {
    height: 100%;
}
#footer {
    clear: both;        
}

Is System.nanoTime() completely useless?

Java is crossplatform, and nanoTime is platform-dependent. If you use Java - when don't use nanoTime. I found real bugs across different jvm implementations with this function.

cast or convert a float to nvarchar?

If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.

So instead of:

select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009

You would use:

select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890

In these examples the innermost cast(1234567890 as float) is used in place of selecting a value from the appropriate column.

I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?

select cast(0100884555 as float)
100884555

Whoops! We just stored an incorrect phone number...

How to allow download of .json file with ASP.NET

Add the JSON MIME type to IIS 6. Follow the directions at MSDN's Configure MIME Types (IIS 6.0).

  • Extension: .json
  • MIME type: application/json

Don't forget to restart IIS after the change.

UPDATE: There are easy ways to do this on IIS7 and newer. The op specifically asked for IIS6 help so I'm leaving this answer as-is. But this answer is still getting a lot of traffic even though IIS6 is very old now. Hopefully you're using something newer, so I wanted to mention that if you have a newer IIS7 or newer version see @ProVega's answer below for a simpler solution for those newer versions.

WPF Application that only has a tray icon

I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.

If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.

  • Rich ToolTips rather than text
  • WPF context menus and popups
  • Command support and routed events
  • Flexible data binding
  • Rich balloon messages rather than the default messages provides by the OS

Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.

Class not registered Error

I had run into the same problem. I added reference of Microsoft.Office.Interop.Excel COM component's dll but Office was not installed on my system it wont give compile time error. I moved my application to another system and ran it..it worked successfully.

So, I can say in my case it was the system environment which was causing this issue.

pip install from git repo branch

Using pip with git+ to clone a repository can be extremely slow (test with https://github.com/django/django@stable/1.6.x for example, it will take a few minutes). The fastest thing I've found, which works with GitHub and BitBucket, is:

pip install https://github.com/user/repository/archive/branch.zip

which becomes for Django master:

pip install https://github.com/django/django/archive/master.zip

for Django stable/1.7.x:

pip install https://github.com/django/django/archive/stable/1.7.x.zip

With BitBucket it's about the same predictable pattern:

pip install https://bitbucket.org/izi/django-admin-tools/get/default.zip

Here, the master branch is generally named default. This will make your requirements.txt installing much faster.

Some other answers mention variations required when placing the package to be installed into your requirements.txt. Note that with this archive syntax, the leading -e and trailing #egg=blah-blah are not required, and you can just simply paste the URL, so your requirements.txt looks like:

https://github.com/user/repository/archive/branch.zip

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • How do you run your own code alongside Tkinter's event loop?

    When writing your own loop, as in the simulation (I assume), you need to call the update function which does what the mainloop does: updates the window with your changes, but you do it in your loop.

    def task():
       # do something
       root.update()
    
    while 1:
       task()  
    

    How to save all files from source code of a web site?

    Try Winhttrack

    ...offline browser utility.

    It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.

    WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...

    Remove warning messages in PHP

    To suppress warnings while leaving all other error reporting enabled:

    error_reporting(E_ALL ^ E_WARNING); 
    

    Where to download visual studio express 2005?

    For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html

    EDIT: In case that blog dies, here are the links from the blog.

    All the bellow files are more them 400MB.

    Visual Web Developer 2005 Express Edition
    449,848 KB
    .IMG File | .ISO File

    Visual Basic 2005 Express Edition
    445,282 KB
    .IMG File | .ISO File

    Visual C# 2005 Express Edition
    445,282 KB
    .IMG File | .ISO File

    Visual C++ 2005 Express Edition
    474,686 KB
    .IMG File | .ISO File

    Visual J# 2005 Express Edition
    448,702 KB
    .IMG File | .ISO File

    Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

    Are you using express?

    Check your path(note the "/" after /public/):

    app.use(express.static(__dirname + "/public/"));
    

    //note: you do not need the "/" before "css" because its already included above:

    rel="stylesheet" href="css/style.css
    

    Hope this helps

    VBA ADODB excel - read data from Recordset

    I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

    Set cn = CreateObject("ADODB.Connection")
    With cn
     .Provider = "Microsoft.Jet.OLEDB.4.0"
      .ConnectionString = "Data Source=D:\test.xls " & _
      ";Extended Properties=""Excel 8.0;HDR=Yes;"""
    .Open
    End With
    strQuery = "SELECT * FROM [Sheet1$E36:E38]"
    Set rs = cn.Execute(strQuery)
    Do While Not rs.EOF
      For i = 0 To rs.Fields.Count - 1
        Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
        strNaam = rs.Fields(0).Value
      Next
      rs.MoveNext
    Loop
    rs.Close
    

    There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

    adb uninstall failed

    In my case I often get this issue when I first complise a app in debug mode and later try to install the google signed app.

    That is because both apps have the same package name but diffent signatures. Since I upgraded to Android lollypop I sometimes even get this error if I uninstall the app via the settings\Apps. If you have this problem check if the app is installed in a other User profile and uninstall it in all user accounts.

    How do I install and use curl on Windows?

    1. Download cURL (Win64 ia64 zip binary with SSL)
    2. Extract curl.exe into "C:\Windows\System32"
    3. Done

    Even more easier:

    Download the Win64 2000/XP x86_64 MSI installer provided by Edward LoPinto.

    At the time of writing file curl-7.46.0-win64.exe was the most recent. Tested with Windows 10.

    How to use a jQuery plugin inside Vue

    First install jquery using npm,

    npm install jquery --save
    

    I use:

    global.jQuery = require('jquery');
    var $ = global.jQuery;
    window.$ = $;
    

    How can I concatenate two arrays in Java?

    ArrayList<String> both = new ArrayList(Arrays.asList(first));
    both.addAll(Arrays.asList(second));
    
    both.toArray(new String[0]);
    

    How to Sign an Already Compiled Apk

    You use jarsigner to sign APK's. You don't have to sign with the original keystore, just generate a new one. Read up on the details: http://developer.android.com/guide/publishing/app-signing.html

    Checking if a date is valid in javascript

    Try this:

    var date = new Date();
    console.log(date instanceof Date && !isNaN(date.valueOf()));
    

    This should return true.

    UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

    Android design support library for API 28 (P) not working

    open file gradle.properties and add these two lines to it:

    android.useAndroidX = true
    android.enableJetifier = true
    

    clean and build

    Table row and column number in jQuery

    Off the top of my head, one way would be to grab all previous elements and count them.

    $('td').click(function(){ 
        var colIndex = $(this).prevAll().length;
        var rowIndex = $(this).parent('tr').prevAll().length;
    });
    

    Playing HTML5 video on fullscreen in android webview

    It seems that in lollipop and up (or maybe just a different WebView Version) that calling cprcrack's onHideCustomView() method does not work. It works if it is called from the exit fullscreen button but when you specifically call the method it will only exit fullscreen but the webView stays blank. A way around it is to simply add these lines of code to onHideCustomView():

    String js = "javascript:";
    js += "var _ytrp_html5_video = document.getElementsByTagName('video')[0];";
    js += "_ytrp_html5_video.webkitExitFullscreen();";
    webView.loadUrl(js);
    

    This will notify the webView that fullscreen has exited.

    popup form using html/javascript/css

    Look at easiest example to create popup using css and javascript.

    1. Create HREF link using HTML.
    2. Create a popUp by HTML and CSS
    3. Write CSS
    4. Call JavaScript mehod

    See the full example at this link http://makecodeeasy.blogspot.in/2012/07/popup-in-java-script-and-css.html

    Exporting the values in List to excel

    Using ClosedXML library( there is no need to install MS Excel

    I just write a simple example to show you how you can name the file, the worksheet and select cells:

        var workbook = new XLWorkbook();
        workbook.AddWorksheet("sheetName");
        var ws = workbook.Worksheet("sheetName");
    
        int row = 1;
        foreach (object item in itemList)
        {
            ws.Cell("A" + row.ToString()).Value = item.ToString();
            row++;
        }
    
        workbook.SaveAs("yourExcel.xlsx");
    

    If you prefer you can create a System.Data.DataSet or a System.Data.DataTable with all data and then just add it as a workseet with workbook.AddWorksheet(yourDataset) or workbook.AddWorksheet(yourDataTable);

    How to send email to multiple recipients using python smtplib?

    This really works, I spent a lot of time trying multiple variants.

    import smtplib
    from email.mime.text import MIMEText
    
    s = smtplib.SMTP('smtp.uk.xensource.com')
    s.set_debuglevel(1)
    msg = MIMEText("""body""")
    sender = '[email protected]'
    recipients = ['[email protected]', '[email protected]']
    msg['Subject'] = "subject line"
    msg['From'] = sender
    msg['To'] = ", ".join(recipients)
    s.sendmail(sender, recipients, msg.as_string())
    

    User Control - Custom Properties

    Just add public properties to the user control.

    You can add [Category("MyCategory")] and [Description("A property that controls the wossname")] attributes to make it nicer, but as long as it's a public property it should show up in the property panel.

    Override valueof() and toString() in Java enum

    The following is a nice generic alternative to valueOf()

    public static RandomEnum getEnum(String value) {
      for (RandomEnum re : RandomEnum.values()) {
        if (re.description.compareTo(value) == 0) {
          return re;
        }
      }
      throw new IllegalArgumentException("Invalid RandomEnum value: " + value);
    }
    

    problem with <select> and :after with CSS in WebKit

    <div class="select">
    <select name="you_are" id="dropdown" class="selection">
    <option value="0" disabled selected>Select</option>
    <option value="1">Student</option>
    <option value="2">Full-time Job</option>
    <option value="2">Part-time Job</option>
    <option value="3">Job-Seeker</option>
    <option value="4">Nothing Yet</option>
    </select>
    </div>
    

    Insted of styling the select why dont you add a div out-side the select.

    and style then in CSS

    .select{
        width: 100%;
        height: 45px;
        position: relative;
    }
    .select::after{
        content: '\f0d7';
        position: absolute;
        top: 0px;
        right: 10px;
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
        color: #0b660b;
        font-size: 45px;
        z-index: 2;
    
    }
    #dropdown{
        -webkit-appearance: button;
           -moz-appearance: button;
                appearance: button;
                height: 45px;
                width: 100%;
            outline: none;
            border: none;
            border-bottom: 2px solid #0b660b;
            font-size: 20px;
            background-color: #0b660b23;
            box-sizing: border-box;
            padding-left: 10px;
            padding-right: 10px;
    }
    

    Print raw string from variable? (not getting the answers)

    Your particular string won't work as typed because of the escape characters at the end \", won't allow it to close on the quotation.

    Maybe I'm just wrong on that one because I'm still very new to python so if so please correct me but, changing it slightly to adjust for that, the repr() function will do the job of reproducing any string stored in a variable as a raw string.

    You can do it two ways:

    >>>print("C:\\Windows\Users\alexb\\")
    
    C:\Windows\Users\alexb\
    
    >>>print(r"C:\\Windows\Users\alexb\\")
    C:\\Windows\Users\alexb\\
    

    Store it in a variable:

    test = "C:\\Windows\Users\alexb\\"
    

    Use repr():

    >>>print(repr(test))
    'C:\\Windows\Users\alexb\\'
    

    or string replacement with %r

    print("%r" %test)
    'C:\\Windows\Users\alexb\\'
    

    The string will be reproduced with single quotes though so you would need to strip those off afterwards.

    Can you explain the HttpURLConnection connection process?

    On which point does HTTPURLConnection try to establish a connection to the given URL?

    It's worth clarifying, there's the 'UrlConnection' instance and then there's the underlying Tcp/Ip/SSL socket connection, 2 different concepts. The 'UrlConnection' or 'HttpUrlConnection' instance is synonymous with a single HTTP page request, and is created when you call url.openConnection(). But if you do multiple url.openConnection()'s from the one 'url' instance then if you're lucky, they'll reuse the same Tcp/Ip socket and SSL handshaking stuff...which is good if you're doing lots of page requests to the same server, especially good if you're using SSL where the overhead of establishing the socket is very high.

    See: HttpURLConnection implementation

    How do I make a column unique and index it in a Ruby on Rails migration?

    add_index :table_name, :column_name, unique: true
    

    To index multiple columns together, you pass an array of column names instead of a single column name.

    "This SqlTransaction has completed; it is no longer usable."... configuration error?

    I have recently ran across similar situation. To debug in any VS IDE version, open exceptions from Debug (Ctrl + D, E) - check all checkboxes against the column "Thrown", and run the application in debug mode. I have realized that one of the tables was not imported properly in the new database, so internal Sql Exception was killing the connection, thus results into this error.

    Gist of the story is, If Previously working code returns this error on a new database, this could be database schema missing issue, realize by above debugging tip,

    Hope It Helps, HydTechie

    Static method in a generic class?

    Since static variables are shared by all instances of the class. For example if you are having following code

    class Class<T> {
      static void doIt(T object) {
        // using T here 
      }
    }
    

    T is available only after an instance is created. But static methods can be used even before instances are available. So, Generic type parameters cannot be referenced inside static methods and variables

    How to print a number with commas as thousands separators in JavaScript

    Let me try to improve uKolka's answer and maybe help others save some time.

    Use Numeral.js.

    _x000D_
    _x000D_
    document.body.textContent = numeral(1234567).format('0,0');
    _x000D_
    <script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>
    _x000D_
    _x000D_
    _x000D_

    You should go with Number.prototype.toLocaleString() only if its browser compatibilty is not an issue.

    Add SUM of values of two LISTS into new LIST

    Perhaps the simplest approach:

    first = [1,2,3,4,5]
    second = [6,7,8,9,10]
    three=[]
    
    for i in range(0,5):
        three.append(first[i]+second[i])
    
    print(three)
    

    How to define an empty object in PHP

    stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

    When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

    <?php
    // ways of creating stdClass instances
    $x = new stdClass;
    $y = (object) null;        // same as above
    $z = (object) 'a';         // creates property 'scalar' = 'a'
    $a = (object) array('property1' => 1, 'property2' => 'b');
    ?>
    

    stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

    <?php
    // CTest does not derive from stdClass
    class CTest {
        public $property1;
    }
    $t = new CTest;
    var_dump($t instanceof stdClass);            // false
    var_dump(is_subclass_of($t, 'stdClass'));    // false
    echo get_class($t) . "\n";                   // 'CTest'
    echo get_parent_class($t) . "\n";            // false (no parent)
    ?>
    

    You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

    You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

    (tested on PHP 5.2.8)

    How do I automatically play a Youtube video (IFrame API) muted?

    You can select the video player and then set its volume:

    var mp = iframe.getElementById('movie_player');
    mp.setVolume(0);
    

    Source: http://userscripts.org/scripts/review/49366

    How do you configure an OpenFileDialog to select folders?

    Better to use the FolderBrowserDialog for that.

    using (FolderBrowserDialog dlg = new FolderBrowserDialog())
    {
        dlg.Description = "Select a folder";
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show("You selected: " + dlg.SelectedPath);
        }
    }
    

    How to list all the files in android phone by using adb shell?

    just to add the full command:

    adb shell ls -R | grep filename
    

    this is actually a pretty fast lookup on Android

    Arduino error: does not name a type?

    The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!

    Two notes from experience which might be helpful:

    1. You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.

    2. If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.

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

    This works better for me:

    Simple:

    ApplicationController.helpers.my_helper_method
    

    Advance:

    class HelperProxy < ActionView::Base
      include ApplicationController.master_helper_module
    
      def current_user
        #let helpers act like we're a guest
        nil
      end       
    
      def self.instance
        @instance ||= new
      end
    end
    

    Source: http://makandracards.com/makandra/1307-how-to-use-helper-methods-inside-a-model

    how can I enable PHP Extension intl?

    I wrote this post if anyone come across this question for PrestaShop, I don't know if it will work for Magento2. I solved enabling PHP extension intl for the PrestaShop installation by:

    1. Open XAMPP Control Pane.
    2. Stop the Apache server if it was started.
    3. Then from Config button click on PHP (php.ini) item.

    enter image description here

    1. Php.ini will open in Notepad (or a default text editor), click Ctrl + F and search for ;extension=intl and remove the semicolon.

    enter image description here

    1. Then save and close Notepad and re-start the Apache server.

    These steps for me solved the issue.

    Note (2): I'm using XAMPP v3.2.3 and PrestaShop v1.7.5.1

    enter image description here

    Drawing an SVG file on a HTML5 canvas

    EDIT Dec 16th, 2019

    Path2D is supported by all major browsers now

    EDIT November 5th, 2014

    You can now use ctx.drawImage to draw HTMLImageElements that have a .svg source in some but not all browsers. Chrome, IE11, and Safari work, Firefox works with some bugs (but nightly has fixed them).

    var img = new Image();
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
    }
    img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";
    

    Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg> element inserted into the DOM for reference.

    You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:

    var path = new Path2D('M 100,100 h 50 v 50 h 50');
    ctx.stroke(path);
    

    Live example of that here.


    Old posterity answer:

    There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.

    I'd suggest looking in to canvg:

    http://code.google.com/p/canvg/

    http://canvg.googlecode.com/svn/trunk/examples/index.htm

    string in namespace std does not name a type

    Nouns.h doesn't include <string>, but it needs to. You need to add

    #include <string>
    

    at the top of that file, otherwise the compiler doesn't know what std::string is when it is encountered for the first time.

    Set element width or height in Standards Mode

    Try declaring the unit of width:

    e1.style.width = "400px"; // width in PIXELS
    

    Using new line(\n) in string and rendering the same in HTML

    I had the following problem where I was fetching data from a database and wanted to display a string containing \n. None of the solutions above worked for me and I finally came up with a solution: https://stackoverflow.com/a/61484190/7251208

    How to write to a file without overwriting current contents?

    Instead of "w" use "a" (append) mode with open function:

    with open("games.txt", "a") as text_file:
    

    Pandas DataFrame column to list

    The above solution is good if all the data is of same dtype. Numpy arrays are homogeneous containers. When you do df.values the output is an numpy array. So if the data has int and float in it then output will either have int or float and the columns will loose their original dtype. Consider df

    a  b 
    0  1  4
    1  2  5 
    2  3  6 
    
    a    float64
    b    int64 
    

    So if you want to keep original dtype, you can do something like

    row_list = df.to_csv(None, header=False, index=False).split('\n')
    

    this will return each row as a string.

    ['1.0,4', '2.0,5', '3.0,6', '']
    

    Then split each row to get list of list. Each element after splitting is a unicode. We need to convert it required datatype.

    def f(row_str): 
      row_list = row_str.split(',')
      return [float(row_list[0]), int(row_list[1])]
    
    df_list_of_list = map(f, row_list[:-1])
    
    [[1.0, 4], [2.0, 5], [3.0, 6]]
    

    Text on image mouseover?

    For people coming from the future, you can now do this purely in CSS.

    _x000D_
    _x000D_
    .tooltip {
      position: relative;
      display: inline-block;
      border-bottom: 1px dotted black; 
      margin: 5rem;
    }
    
    /* Tooltip text */
    .tooltip .tooltiptext {
      visibility: hidden;
      background-color: black;
      color: #fff;
      text-align: center;
      padding: 5px 0;
      border-radius: 6px;
    
      width: 120px;
      bottom: 100%;
      left: 50%;
      margin-left: -60px;
    
      position: absolute;
      z-index: 1;
    }
    
    /* Show the tooltip text when you mouse over the tooltip container */
    .tooltip:hover .tooltiptext {
      visibility: visible;
    }
    _x000D_
    <div class="tooltip">Hover over me
      <span class="tooltiptext">Tooltip text</span>
    </div>
    _x000D_
    _x000D_
    _x000D_

    How to nicely format floating numbers to string without unnecessary decimal 0's

    I am using this for formatting numbers without trailing zeroes in our JSF application. The original built-in formatters required you to specify max numbers of fractional digits which could be useful here also in case you have too many fractional digits.

    /**
     * Formats the given Number as with as many fractional digits as precision
     * available.<br>
     * This is a convenient method in case all fractional digits shall be
     * rendered and no custom format / pattern needs to be provided.<br>
     * <br>
     * This serves as a workaround for {@link NumberFormat#getNumberInstance()}
     * which by default only renders up to three fractional digits.
     *
     * @param number
     * @param locale
     * @param groupingUsed <code>true</code> if grouping shall be used
     *
     * @return
     */
    public static String formatNumberFraction(final Number number, final Locale locale, final boolean groupingUsed)
    {
        if (number == null)
            return null;
    
        final BigDecimal bDNumber = MathUtils.getBigDecimal(number);
    
        final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
        numberFormat.setMaximumFractionDigits(Math.max(0, bDNumber.scale()));
        numberFormat.setGroupingUsed(groupingUsed);
    
        // Convert back for locale percent formatter
        return numberFormat.format(bDNumber);
    }
    
    /**
     * Formats the given Number as percent with as many fractional digits as
     * precision available.<br>
     * This is a convenient method in case all fractional digits shall be
     * rendered and no custom format / pattern needs to be provided.<br>
     * <br>
     * This serves as a workaround for {@link NumberFormat#getPercentInstance()}
     * which does not renders fractional digits.
     *
     * @param number Number in range of [0-1]
     * @param locale
     *
     * @return
     */
    public static String formatPercentFraction(final Number number, final Locale locale)
    {
        if (number == null)
            return null;
    
        final BigDecimal bDNumber = MathUtils.getBigDecimal(number).multiply(new BigDecimal(100));
    
        final NumberFormat percentScaleFormat = NumberFormat.getPercentInstance(locale);
        percentScaleFormat.setMaximumFractionDigits(Math.max(0, bDNumber.scale() - 2));
    
        final BigDecimal bDNumberPercent = bDNumber.multiply(new BigDecimal(0.01));
    
        // Convert back for locale percent formatter
        final String strPercent = percentScaleFormat.format(bDNumberPercent);
    
        return strPercent;
    }
    

    Where does the iPhone Simulator store its data?

    You can try using the below code

    NSString *fileName = @"Demo.pdf";
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
        NSLog(@"File path%@",pdfFileName);
    

    Android list view inside a scroll view

    Ok, here 's my answer. The method that fixes the ListView height is closed enough, but not perfect. In case that most of the items are the same height, that work well. But in case that's not, then there's a big problem. I've tried many time, and when I put out the value of listItem.getMeasureHeight and listItem.getMeasuerWidth into the log, I saw the width values vary a lot, which is not expected here, since all the item in the same ListView should have the same width. And there go the bug :

    Some used measure(0 ,0), which actually made the view unbound, in both direction, and width run wild. Some tried to getWidth of listView, but then it return 0, meaningless.

    When I read further into how android render the View, I realize that all of this attempt can't reach the answer that I searched for, unless these function run after the view is render.

    This time I use the getViewTreeObserver on the ListView that I want to fix height, then addOnGlobalLayoutListener. Inside this method, I declare a new OnGlobalLayoutListener, in which, this time, getWidth return the actual width of the ListView.

    private void getLayoutWidth(final ListView lv, final int pad){
            //final ArrayList<Integer> width = new ArrayList<Integer>();
    
            ViewTreeObserver vto = lv.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    lv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    //width.add(layout.getMeasuredWidth());
                    int width = lv.getMeasuredWidth();
                    ListUtils.setDynamicHeight(lv, width, pad);
                }
            });
        }
    
    public static class ListUtils {
            //private static final int UNBOUNDED = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            public static void setDynamicHeight(ListView mListView, int width, int pad) {
                ListAdapter mListAdapter = mListView.getAdapter();
                mListView.getParent();
                if (mListAdapter == null) {
                    // when adapter is null
                    return;
                }
                int height = 0;
    
    
                int desiredWidth = View.MeasureSpec.makeMeasureSpec(width - 2*pad, View.MeasureSpec.EXACTLY);
                for (int i = 0; i < mListAdapter.getCount(); i++) {
                    View listItem = mListAdapter.getView(i, null, mListView);
    
                    listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                    //listItem.measure(UNBOUNDED, UNBOUNDED);
                    height += listItem.getMeasuredHeight() + 2*pad;
                    Log.v("ViewHeight :", mListAdapter.getClass().toString() + " " + listItem.getMeasuredHeight() + "--" + listItem.getMeasuredWidth());
                }
                ViewGroup.LayoutParams params = mListView.getLayoutParams();
                params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1));
                mListView.setLayoutParams(params);
                mListView.requestLayout();
            }
        }
    

    The value pad, is the padding that I set in ListView layout.

    MVC3 DropDownListFor - a simple example?

         @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")
    

    Here Value is that object of model where you want to save your Selected Value

    How can I switch my signed in user in Visual Studio 2013?

    what worked for me was to go to Team explorer in VS2013 and under 'connect' you'll see a link saying 'select team projects'. click this and a window opens asking you to select the project but in the bottom left corner of this window there is a (switch user) link, just click this and use your new id. simple

    Flatten List in LINQ

    If you have a List<List<int>> k you can do

    List<int> flatList= k.SelectMany( v => v).ToList();
    

    List of installed gems?

    use this code (in console mode):

    Gem::Specification.all_names
    

    Determine the process pid listening on a certain port

    on windows, the netstat option to get the pid's is -o and -p selects a protocol filter, ex.: netstat -a -p tcp -o

    Fast way to discover the row count of a table in PostgreSQL

    Counting rows in big tables is known to be slow in PostgreSQL. To get a precise number it has to do a full count of rows due to the nature of MVCC. There is a way to speed this up dramatically if the count does not have to be exact like it seems to be in your case.

    Instead of getting the exact count (slow with big tables):

    SELECT count(*) AS exact_count FROM myschema.mytable;
    

    You get a close estimate like this (extremely fast):

    SELECT reltuples::bigint AS estimate FROM pg_class where relname='mytable';
    

    How close the estimate is depends on whether you run ANALYZE enough. It is usually very close.
    See the PostgreSQL Wiki FAQ.
    Or the dedicated wiki page for count(*) performance.

    Better yet

    The article in the PostgreSQL Wiki is was a bit sloppy. It ignored the possibility that there can be multiple tables of the same name in one database - in different schemas. To account for that:

    SELECT c.reltuples::bigint AS estimate
    FROM   pg_class c
    JOIN   pg_namespace n ON n.oid = c.relnamespace
    WHERE  c.relname = 'mytable'
    AND    n.nspname = 'myschema'
    

    Or better still

    SELECT reltuples::bigint AS estimate
    FROM   pg_class
    WHERE  oid = 'myschema.mytable'::regclass;
    

    Faster, simpler, safer, more elegant. See the manual on Object Identifier Types.

    Use to_regclass('myschema.mytable') in Postgres 9.4+ to avoid exceptions for invalid table names:


    TABLESAMPLE SYSTEM (n) in Postgres 9.5+

    SELECT 100 * count(*) AS estimate FROM mytable TABLESAMPLE SYSTEM (1);
    

    Like @a_horse commented, the newly added clause for the SELECT command might be useful if statistics in pg_class are not current enough for some reason. For example:

    • No autovacuum running.
    • Immediately after a big INSERT or DELETE.
    • TEMPORARY tables (which are not covered by autovacuum).

    This only looks at a random n % (1 in the example) selection of blocks and counts rows in it. A bigger sample increases the cost and reduces the error, your pick. Accuracy depends on more factors:

    • Distribution of row size. If a given block happens to hold wider than usual rows, the count is lower than usual etc.
    • Dead tuples or a FILLFACTOR occupy space per block. If unevenly distributed across the table, the estimate may be off.
    • General rounding errors.

    In most cases the estimate from pg_class will be faster and more accurate.

    Answer to actual question

    First, I need to know the number of rows in that table, if the total count is greater than some predefined constant,

    And whether it ...

    ... is possible at the moment the count pass my constant value, it will stop the counting (and not wait to finish the counting to inform the row count is greater).

    Yes. You can use a subquery with LIMIT:

    SELECT count(*) FROM (SELECT 1 FROM token LIMIT 500000) t;
    

    Postgres actually stops counting beyond the given limit, you get an exact and current count for up to n rows (500000 in the example), and n otherwise. Not nearly as fast as the estimate in pg_class, though.

    What is web.xml file and what are all things can I do with it?

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
      <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet>
        <description></description>
        <display-name>pdfServlet</display-name>
        <servlet-name>pdfServlet</servlet-name>
        <servlet-class>com.sapta.smartcam.servlet.pdfServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>pdfServlet</servlet-name>
        <url-pattern>/pdfServlet</url-pattern>
      </servlet-mapping>
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
      </context-param>
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
    

    How do I set default terminal to terminator?

    Copy-paste the following into your current terminal:

    gsettings set org.gnome.desktop.default-applications.terminal exec /usr/bin/terminator
    gsettings set org.gnome.desktop.default-applications.terminal exec-arg "-x"
    

    This modifies the dconf to make terminator the default program. You could also use dconf-editor (a GUI-based tool) to make changes to the dconf, as another answer has suggested. If you would like to learn and understand more about this topic, this may help you.

    Maven does not find JUnit tests to run

    In case someone has searched and I do not solve it, I had a library for different tests:

    <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${org.junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
    

    When I installed junit everything worked, I hope and help this:

    <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    

    How to edit one specific row in Microsoft SQL Server Management Studio 2008?

    How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016

    Step 1: Right button mouse > Select "Edit Top 200 Rows"

    Edit top 200 rows

    Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)

    Navigate to Query Designer > Pane > SQL

    Step 3: Modify the query

    Modify the query

    Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)

    enter image description here

    Length of string in bash

    Using your example provided

    #KISS (Keep it simple stupid)
    size=${#myvar}
    echo $size
    

    What's "tools:context" in Android layout files?

    This is best solution : https://developer.android.com/studio/write/tool-attributes

    This is design attributes we can set activty context in xml like

    tools:context=".activity.ActivityName"
    

    Adapter:

    tools:context="com.PackegaName.AdapterName"
    

    enter image description here

    You can navigate to java class when clicking on the marked icon and tools have more features like

    tools:text=""
    tools:visibility:""
    tools:listItems=""//for recycler view 
    

    etx

    How to clear form after submit in Angular 2?

    See also https://angular.io/docs/ts/latest/guide/reactive-forms.html (section "reset the form flags")

    >=RC.6

    In RC.6 it should be supported to update the form model. Creating a new form group and assigning to myForm

    [formGroup]="myForm"
    

    will also be supported (https://github.com/angular/angular/pull/11051#issuecomment-243483654)

    >=RC.5

    form.reset();
    

    In the new forms module (>= RC.5) NgForm has a reset() method and also supports a forms reset event. https://github.com/angular/angular/blob/6fd5bc075d70879c487c0188f6cd5b148e72a4dd/modules/%40angular/forms/src/directives/ng_form.ts#L179

    <=RC.3

    This will work:

    onSubmit(value:any):void {
      //send some data to backend
      for(var name in form.controls) {
        (<Control>form.controls[name]).updateValue('');
        /*(<FormControl>form.controls[name]).updateValue('');*/ this should work in RC4 if `Control` is not working, working same in my case
        form.controls[name].setErrors(null);
      }
    }
    

    See also

    Runtime vs. Compile time

    Run time means something happens when you run the program.

    Compile time means something happens when you compile the program.

    Can you break from a Groovy "each" closure?

    No, you can't break from a closure in Groovy without throwing an exception. Also, you shouldn't use exceptions for control flow.

    If you find yourself wanting to break out of a closure you should probably first think about why you want to do this and not how to do it. The first thing to consider could be the substitution of the closure in question with one of Groovy's (conceptual) higher order functions. The following example:

    for ( i in 1..10) { if (i < 5) println i; else return}
    

    becomes

    (1..10).each{if (it < 5) println it}
    

    becomes

    (1..10).findAll{it < 5}.each{println it} 
    

    which also helps clarity. It states the intent of your code much better.

    The potential drawback in the shown examples is that iteration only stops early in the first example. If you have performance considerations you might want to stop it right then and there.

    However, for most use cases that involve iterations you can usually resort to one of Groovy's find, grep, collect, inject, etc. methods. They usually take some "configuration" and then "know" how to do the iteration for you, so that you can actually avoid imperative looping wherever possible.

    how to install apk application from my pc to my mobile android

    1) Put the apk on your SDKCard and install file browsers like "Estrongs File Explorer", "Easy Installer", etc...

    https://market.android.com/details?id=com.estrongs.android.pop&feature=search_result https://market.android.com/details?id=mobi.infolife.installer&feature=search_result

    2) Go to your mobile settings - applications- debuging - and thick "USB debugging" enter image description here

    The most efficient way to implement an integer based power function pow(int, int)

    If you want to get the value of an integer for 2 raised to the power of something it is always better to use the shift option:

    pow(2,5) can be replaced by 1<<5

    This is much more efficient.

    Understanding the set() function

    As an unordered collection type, set([8, 1, 6]) is equivalent to set([1, 6, 8]).

    While it might be nicer to display the set contents in sorted order, that would make the repr() call more expensive.

    Internally, the set type is implemented using a hash table: a hash function is used to separate items into a number of buckets to reduce the number of equality operations needed to check if an item is part of the set.

    To produce the repr() output it just outputs the items from each bucket in turn, which is unlikely to be the sorted order.

    Getting Django admin url for an object

    You can use the URL resolver directly in a template, there's no need to write your own filter. E.g.

    {% url 'admin:index' %}

    {% url 'admin:polls_choice_add' %}

    {% url 'admin:polls_choice_change' choice.id %}

    {% url 'admin:polls_choice_changelist' %}

    Ref: Documentation

    Getting the textarea value of a ckeditor textarea with javascript

    Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:

    $("#CampaignTitle").bind("keyup", function()
    {
        $("#titleBar").text($(this).val());
    });
    

    If you really wanted a textarea change your input type text to this

    <textarea id="CampaignTitle"></textarea>
    

    Hope it helps.

    Array copy values to keys in PHP

    $final_array = array_combine($a, $a);
    

    Reference: http://php.net/array-combine

    P.S. Be careful with source array containing duplicated keys like the following:

    $a = ['one','two','one'];
    

    Note the duplicated one element.

    Python 2.7.10 error "from urllib.request import urlopen" no module named request

    Instead of using urllib.request.urlopen() remove request for python 2.

    urllib.urlopen() you do not have to request in python 2.x for what you are trying to do. Hope it works for you. This was tested using python 2.7 I was receiving the same error message and this resolved it.

    How do I call a function twice or more times consecutively?

    My two cents:

    from itertools import repeat 
    
    list(repeat(f(), x))  # for pure f
    [f() for f in repeat(f, x)]  # for impure f