Programs & Examples On #User extensions.js

How to make Twitter bootstrap modal full screen

.modal.in .modal-dialog {
 width:100% !important; 
 min-height: 100%;
 margin: 0 0 0 0 !important;
 bottom: 0px !important;
 top: 0px;
}


.modal-content {
    border:0px solid rgba(0,0,0,.2) !important;
    border-radius: 0px !important;
    -webkit-box-shadow: 0 0px 0px rgba(0,0,0,.5) !important;
    box-shadow: 0 3px 9px rgba(0,0,0,.5) !important;
    height: auto;
    min-height: 100%;
}

.modal-dialog {
 position: fixed !important;
 margin:0px !important;
}

.bootstrap-dialog .modal-header {
    border-top-left-radius: 0px !important; 
    border-top-right-radius: 0px !important;
}


@media (min-width: 768px)
.modal-dialog {
    width: 100% !important;
    margin: 0 !important;
}

How do I make an image smaller with CSS?

You can try this:

-ms-transform: scale(width,height); /* IE 9 */
-webkit-transform: scale(width,height); /* Safari */
transform: scale(width, height);

Example: image "grows" 1.3 times

-ms-transform: scale(1.3,1.3); /* IE 9 */
-webkit-transform: scale(1.3,1.3); /* Safari */
transform: scale(1.3,1.3);

text-align: right on <select> or <option>

I was facing the same issue in which I need to align selected placeholder value to the right of the select box & also need to align options to right but when I have used direction: rtl; to select & applied some right padding to select then all options also getting shift to the right by padding as I only want to apply padding to selected placeholder.

I have fixed the issue by the following the style:

select:first-child{
  text-indent: 24%;
  direction: rtl;
  padding-right: 7px;
}

select option{
  direction: rtl;
}

You can change text-indent as per your requirement. Hope it will help you.

How to replace a char in string with an Empty character in C#.NET

I have a latin version of the code of Razvan Dumitru because us use a million indicator even. Offcourse I use a double replace :D

public static string CleanNumb(string numb) 
{
    foreach (char c in ".,'´")
       numb = numb.Replace(c, ' ');

    return numb.Replace(" ", "");
}

Illegal character in path at index 16

I had a similar problem for xml. Just passing the error and solution (edited Jonathon version).

Code:

HttpGet xmlGet = new HttpGet( xmlContent );

Xml format:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <code>CA</code>
    <name>Cath</name>
    <salary>300</salary>
</employee>

Error:

java.lang.IllegalArgumentException: Illegal character in path at index 0: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<contents>
    <portalarea>CA</portalarea>
    <portalsubarea>Cath</portalsubarea>
    <direction>Navigator</direction>
</contents>
    at java.net.URI.create(URI.java:859)
    at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
    at de.vogella.jersey.first.Hello.validate(Hello.java:56)

Not Exactly perfect Solution: ( error vanished for that instance )

String theXml = URLEncoder.encode( xmlContent, "UTF-8" );
HttpGet xmlGet = new HttpGet( theXml );

Any idea What i should be doing ? It just cleared passed but had problem while doing this

HttpResponse response = httpclient.execute( xmlGet );

HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

You may also use element.insertAdjacentHTML('beforeend', data);

Please read the "Security considerations" on MDN.

How do I call Objective-C code from Swift?

One more thing I would like to add here:

I am very thankful for @Logan's answer. It helps a lot to create a bridge file and setups.

But after doing all these steps I'm still not getting an Objective-C class in Swift.

I used the cocoapods library and integrated it into my project. Which is pod "pop".

So if you are using Objective-C pods in Swift then there may be a chance that you can not able to get or import the classes into Swift.

The simple thing you have to do is:

  1. Go to <YOUR-PROJECT>-Bridging-Header file and
  2. Replace the statement #import <ObjC_Framework> to @import ObjC_Framework

For example: (Pop library)

Replace

#import <pop/POP.h>

with

@import pop;

Use clang import when #import is not working.

Order Bars in ggplot2 bar graph

you can simply use this code:

ggplot(yourdatasetname, aes(Position, fill = Name)) + 
     geom_bar(col = "black", size = 2)

enter image description here

What is the main purpose of setTag() getTag() methods of View?

We can use setTag() and getTag() to set and get custom objects as per our requirement. The setTag() method takes an argument of type Object, and getTag() returns an Object.

For example,

Person p = new Person();
p.setName("Ramkailash");
p.setId(2000001);
button1.setTag(p);

mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

Simply put, you need to rewrite all of your database connections and queries.

You are using mysql_* functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.

A basic example of using PDO (without error handling):

<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>

A basic example of using MySQLi (without error handling):

$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");

Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.

Jinja2 template variable if None Object set a default value

As addition to other answers, one can write something else if variable is None like this:

{{ variable or '' }}

Best practices for SQL varchar column length

No DBMS I know of has any "optimization" that will make a VARCHAR with a 2^n length perform better than one with a max length that is not a power of 2.

I think early SQL Server versions actually treated a VARCHAR with length 255 differently than one with a higher maximum length. I don't know if this is still the case.

For almost all DBMS, the actual storage that is required is only determined by the number of characters you put into it, not the max length you define. So from a storage point of view (and most probably a performance one as well), it does not make any difference whether you declare a column as VARCHAR(100) or VARCHAR(500).

You should see the max length provided for a VARCHAR column as a kind of constraint (or business rule) rather than a technical/physical thing.

For PostgreSQL the best setup is to use text without a length restriction and a CHECK CONSTRAINT that limits the number of characters to whatever your business requires.

If that requirement changes, altering the check constraint is much faster than altering the table (because the table does not need to be re-written)

The same can be applied for Oracle and others - in Oracle it would be VARCHAR(4000) instead of text though.

I don't know if there is a physical storage difference between VARCHAR(max) and e.g. VARCHAR(500) in SQL Server. But apparently there is a performance impact when using varchar(max) as compared to varchar(8000).

See this link (posted by Erwin Brandstetter as a comment)

Edit 2013-09-22

Regarding bigown's comment:

In Postgres versions before 9.2 (which was not available when I wrote the initial answer) a change to the column definition did rewrite the whole table, see e.g. here. Since 9.2 this is no longer the case and a quick test confirmed that increasing the column size for a table with 1.2 million rows indeed only took 0.5 seconds.

For Oracle this seems to be true as well, judging by the time it takes to alter a big table's varchar column. But I could not find any reference for that.

For MySQL the manual says "In most cases, ALTER TABLE makes a temporary copy of the original table". And my own tests confirm that: running an ALTER TABLE on a table with 1.2 million rows (the same as in my test with Postgres) to increase the size of a column took 1.5 minutes. In MySQL however you can not use the "workaround" to use a check constraint to limit the number of characters in a column.

For SQL Server I could not find a clear statement on this but the execution time to increase the size of a varchar column (again the 1.2 million rows table from above) indicates that no rewrite takes place.

Edit 2017-01-24

Seems I was (at least partially) wrong about SQL Server. See this answer from Aaron Bertrand that shows that the declared length of a nvarchar or varchar columns makes a huge difference for the performance.

Image library for Python 3

Christoph Gohlke managed to build PIL (for Windows only) for python versions up to 3.3: http://www.lfd.uci.edu/~gohlke/pythonlibs/

I tried his version of PIL with Python 3.2, and image open/create/pixel manipulation/save all work.

How to call codeigniter controller function from view

Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.

A good start for clarifying the best practice is to follow this tutorial:

https://codeigniter.com/user_guide/tutorial/index.html

It's simple, but it really lays out an excellent how-to.

I hope this helps!

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

What is the difference between a schema and a table and a database?

This particular posting has been shown to relate to Oracle only and the definition of Schema changes when in the context of another DB.

Probably the kinda thing to just google up but FYI terms do seem to vary in their definitions which is the most annoying thing :)

In Oracle a database is a database. In your head think of this as the data files and the redo logs and the actual physical presence on the disk of the database itself (i.e. not the instance)

A Schema is effectively a user. More specifically it's a set of tables/procs/indexes etc owned by a user. Another user has a different schema (tables he/she owns) however user can also see any schemas they have select priviliedges on. So a database can consist of hundreds of schemas, and each schema hundreds of tables. You can have tables with the same name in different schemas, which are in the same database.

A Table is a table, a set of rows and columns containing data and is contained in schemas.

Definitions may be different in SQL Server for instance. I'm not aware of this.

C# Remove object from list of objects

Simplest solution without using LINQ:

    Chunk toRemove = null;
    foreach (Chunk i in ChunkList)
    {
        if (i.UniqueID == ChunkID)
        {
            toRemove = i;
            break;
        }
    }
    if (toRemove != null) {
        ChunkList.Remove(toRemove);
    }

(If Chunk is a struct, then you can use Nullable<Chunk> to achieve this.)

Is there a way to view past mysql queries with phpmyadmin?

Here is a trick that some may find useful:

For Select queries (only), you can create Views, especially where you find yourself running the same select queries over and over e.g. in production support scenarios.

The main advantages of creating Views are:

  • they are resident within the database and therefore permanent
  • they can be shared across sessions and users
  • they provide all the usual benefits of working with tables
  • they can be queried further, just like tables e.g. to filter down the results further
  • as they are stored as queries under the hood, they do not add any overheads.

You can create a view easily by simply clicking the "Create view" link at the bottom of the results table display.

SQL Logic Operator Precedence: And and Or

I'll add 2 points:

  • "IN" is effectively serial ORs with parentheses around them
  • AND has precedence over OR in every language I know

So, the 2 expressions are simply not equal.

WHERE some_col in (1,2,3,4,5) AND some_other_expr
--to the optimiser is this
WHERE
     (
     some_col = 1 OR
     some_col = 2 OR 
     some_col = 3 OR 
     some_col = 4 OR 
     some_col = 5
     )
     AND
     some_other_expr

So, when you break the IN clause up, you split the serial ORs up, and changed precedence.

How to modify STYLE attribute of element with known ID using JQuery

Not sure I completely understand the question but:

$(":button.brown").click(function() {
  $(":button.brown.selected").removeClass("selected");
  $(this).addClass("selected");
});

seems to be along the lines of what you want.

I would certainly recommend using classes instead of directly setting CSS, which is problematic for several reasons (eg removing styles is non-trivial, removing classes is easy) but if you do want to go that way:

$("...").css("background", "brown");

But when you want to reverse that change, what do you set it to?

MySQL SELECT WHERE datetime matches day (and not necessarily time)

NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24' - it is a performance killer:

  • it will calculate DATE() for all rows, including those, that don't match
  • it will make it impossible to use an index for the query

It is much faster to use

SELECT * FROM tablename 
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'

as this will allow index use without calculation.

EDIT

As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read

SELECT * FROM tablename 
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'

The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.

Dynamic button click event handler

Some code for a variation on this problem. Using the above code got me my click events as needed, but I was then stuck trying to work out which button had been clicked. My scenario is I have a dynamic amount of tab pages. On each tab page are (all dynamically created) 2 charts, 2 DGVs and a pair of radio buttons. Each control has a unique name relative to the tab, but there could be 20 radio buttons with the same name if I had 20 tab pages. The radio buttons switch between which of the 2 graphs and DGVs you get to see. Here is the code for when one of the radio buttons gets checked (There's a nearly identical block that swaps the charts and DGVs back):

   Private Sub radioFit_Components_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    If sender.name = "radioFit_Components" And sender.visible Then
        If sender.checked Then
            For Each ctrl As Control In TabControl1.SelectedTab.Controls
                Select Case ctrl.Name
                    Case "embChartSSE_Components"
                        ctrl.BringToFront()
                    Case "embChartSSE_Fit_Curve"
                        ctrl.SendToBack()
                    Case "dgvFit_Components"
                        ctrl.BringToFront()
                End Select
            Next

        End If
    End If

End Sub

This code will fire for any of the tab pages and swap the charts and DGVs over on any of the tab pages. The sender.visible check is to stop the code firing when the form is being created.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Please check the permissions on the the ca certificates installed on server.

Git - How to close commit editor?

Had troubles as well. On Linux I used Ctrl+X (and Y to confirm) and then I was back on the shell ready to pull/push.

On Windows GIT Bash Ctrl+X would do nothing and found out it works quite like vi/vim. Press i to enter inline insert mode. Type the description at the very top, press esc to exit insert mode, then type :x! (now the cursor is at the bottom) and hit enter to save and exit.

If typing :q! instead, will exit the editor without saving (and commit will be aborted)

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

Remove NaN from pandas series

A small usage of np.nan ! = np.nan

s[s==s]
Out[953]: 
0    1.0
1    2.0
2    3.0
3    4.0
5    5.0
dtype: float64

More Info

np.nan == np.nan
Out[954]: False

SQL: Select columns with NULL values only

Or did you want to just see if a column only has NULL values (and, thus, is probably unused)?

Further clarification of the question might help.

EDIT: Ok.. here's some really rough code to get you going...

SET NOCOUNT ON
DECLARE @TableName Varchar(100)
SET @TableName='YourTableName'
CREATE TABLE #NullColumns (ColumnName Varchar(100), OnlyNulls BIT)
INSERT INTO #NullColumns (ColumnName, OnlyNulls) SELECT c.name, 0 FROM syscolumns c INNER JOIN sysobjects o ON c.id = o.id AND o.name = @TableName AND o.xtype = 'U'
DECLARE @DynamicSQL AS Nvarchar(2000)
DECLARE @ColumnName Varchar(100)
DECLARE @RC INT
    SELECT TOP 1 @ColumnName = ColumnName FROM #NullColumns WHERE OnlyNulls=0
    WHILE @@ROWCOUNT > 0
    BEGIN
        SET @RC=0
        SET @DynamicSQL = 'SELECT TOP 1 1 As HasNonNulls FROM ' + @TableName + ' (nolock) WHERE ''' + @ColumnName + ''' IS NOT NULL'
        EXEC sp_executesql @DynamicSQL
        set @RC=@@rowcount
        IF @RC=1
        BEGIN
            SET @DynamicSQL = 'UPDATE #NullColumns SET OnlyNulls=1 WHERE ColumnName=''' + @ColumnName + ''''
            EXEC sp_executesql @DynamicSQL
        END
        ELSE
        BEGIN
            SET @DynamicSQL = 'DELETE FROM #NullColumns WHERE ColumnName=''' + @ColumnName+ ''''
            EXEC sp_executesql @DynamicSQL
        END
    SELECT TOP 1 @ColumnName = ColumnName FROM #NullColumns WHERE OnlyNulls=0
    END

SELECT * FROM #NullColumns

DROP TABLE #NullColumns
SET NOCOUNT OFF

Yes, there are easier ways, but I have a meeting to go to right now. Good luck!

How to open child forms positioned within MDI parent in VB.NET?

   Private Sub FileMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) handles FileMenu.Click

    Form1.MdiParent = Me
    Form1.Dock = DockStyle.Fill
    Form1.Show()
End Sub

How to create EditText with cross(x) button at end of it?

If you don't want to use custom views or special layouts, you can use 9-patch to make the (X) button .

Example: http://postimg.org/image/tssjmt97p/ (I don't have enough points to post images on StackOverflow)

The intersection of the right and bottom black pixels represent the content area. Anything outside of that area is padding. So to detect that the user clicked on the x you can set a OnTouchListener like so:

editText.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_UP){
            if (motionEvent.getX()>(view.getWidth()-view.getPaddingRight())){
                ((EditText)view).setText("");
            }
        }
        return false;
    }
});

According to your needs this solution can work better in some cases. I prefer to keep my xml less complicated. This also helps if you want to have an icon on the left, as you can simply include it in the 9 patch.

Does "display:none" prevent an image from loading?

Yes it will render faster, slightly, only because it doesn't have to render the image and is one less element to sort on the screen.

If you don't want it loaded, leave a DIV empty where you can load html into it later containing an <img> tag.

Try using firebug or wireshark as I've mentioned before and you'll see that the files DO get transferred even if display:none is present.

Opera is the only browser which will not load the image if the display is set to none. Opera has now moved to webkit and will render all images even if their display is set to none.

Here is a testing page that will prove it:

http://www.quirksmode.org/css/displayimg.html

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

It doesn't look like DD-MMM-YYYY is supported by default (at least, with dash as separator). However, using the AS clause, you should be able to do something like:

SELECT CONVERT(VARCHAR(11), SYSDATETIME(), 106) AS [DD-MON-YYYY]

See here: http://www.sql-server-helper.com/sql-server-2008/sql-server-2008-date-format.aspx

css divide width 100% to 3 column

A perfect 1/3 cannot exist in CSS with full cross browser support (anything below IE9). I personally would do: (It's not the perfect solution, but it's about as good as you'll get for all browsers)

#c1, #c2 {
    width: 33%;
}

#c3 {
    width: auto;
}

Template not provided using create-react-app

I got the same problem in last week. I tried many things that is provided in this answer section. But now this thing is different. Latest version of this create-react-app provided 2 templates.

1. cra-template

2. cra-template-typescript

If you use javascript, choose cra-template. And if you use typescript, use cra-template-typescript.

First you have to uninstall the create-react-app. (If you have the latest version, ignore this step.)

 npm uninstall -g create-react-app

Again install the latest version of the create-react-app

npm install create-react-app@latest

Now you have to import the template like this. (If you use typescript, use "cra-template-typescript" instead of "cra-template". my-app is used as a name. you can give it any name).

npx create-react-app my-app --template cra-template

Now the template will be downloaded. But remind in your mind, this is not equal to the past versions. (something different)

Happy Coding.

PHP PDO: charset, set names?

For completeness, there're actually three ways to set the encoding when connecting to MySQL from PDO and which ones are available depend on your PHP version. The order of preference would be:

  1. charset parameter in the DSN string
  2. Run SET NAMES utf8 with PDO::MYSQL_ATTR_INIT_COMMAND connection option
  3. Run SET NAMES utf8 manually

This sample code implements all three:

<?php

define('DB_HOST', 'localhost');
define('DB_SCHEMA', 'test');
define('DB_USER', 'test');
define('DB_PASSWORD', 'test');
define('DB_ENCODING', 'utf8');


$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_SCHEMA;
$options = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);

if( version_compare(PHP_VERSION, '5.3.6', '<') ){
    if( defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
        $options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . DB_ENCODING;
    }
}else{
    $dsn .= ';charset=' . DB_ENCODING;
}

$conn = @new PDO($dsn, DB_USER, DB_PASSWORD, $options);

if( version_compare(PHP_VERSION, '5.3.6', '<') && !defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
    $sql = 'SET NAMES ' . DB_ENCODING;
    $conn->exec($sql);
}

Doing all three is probably overkill (unless you're writing a class you plan to distribute or reuse).

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;}

  }

Email address validation in C# MVC 4 application: with or without using Regex

It is surprising the question of validating an email address continually comes up on SO!

You can find one often-mentioned practical solution here: How to Find or Validate an Email Address.

Excerpt:

The virtue of my regular expression above is that it matches 99% of the email addresses in use today. All the email address it matches can be handled by 99% of all email software out there. If you're looking for a quick solution, you only need to read the next paragraph. If you want to know all the trade-offs and get plenty of alternatives to choose from, read on.

See this answer on SO for a discussion of the merits of the article at the above link. In particular, the comment dated 2012-04-17 reads:

To all the complainers: after 3 hours experimenting all the solutions offered in this gigantic discussion, this is THE ONLY good java regex solution I can find. None of the rfc5322 stuff works on java regex.

Error in Process.Start() -- The system cannot find the file specified

I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified can be misleading in some special cases.

In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.

So in fact the message The system cannot find the file specified was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.

Laravel - display a PDF file in storage without forcing download?

Retrieving Files
$contents = Storage::get('file.jpg');

Downloading Files
return Storage::download('file.jpg');

File URLs
$url = Storage::url('file.jpg');

Hide the browse button on a input type=file

You may just without making the element hidden, simply make it transparent by making its opacity to 0.

Making the input file hidden will make it STOP working. So DON'T DO THAT..

Here you can find an example for a transparent Browse operation;

How to make custom dialog with rounded corners in android

You can simply use MaterialAlertDialogBuilder to create custom dialog with rounded corners.

First create a style for the material dialog like this :

<style name="MyRounded.MaterialComponents.MaterialAlertDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.App.CustomDialog.Rounded
    </item>
    <item name="colorSurface">@color/YOUR_COLOR</item>
</style>

<style name="ShapeAppearanceOverlay.App.CustomDialog.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">10dp</item>
</style>

then create a Alert Dialog object in Java class like this :

AlertDialog alertDialog =  new MaterialAlertDialogBuilder(this,R.style.MyRounded_MaterialComponents_MaterialAlertDialog)  // for fragment you can use getActivity() instead of this 
                    .setView(R.layout.custom_layout) // custom layout is here 
                    .show();

            final EditText editText = alertDialog.findViewById(R.id.custom_layout_text);   // access to text view of custom layout         
            Button btn = alertDialog.findViewById(R.id.custom_layout_btn);

            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Log.d(TAG, "onClick: " + editText.getText().toString());
                }
            });

That's all you need to do.

Simulate limited bandwidth from within Chrome?

I don't think what you ask can be done by chrome alone. The closest I could find was this, which isn't what you want. I getting a chrome plugin to do it would be Hard.

A web proxy running on your local machine could achieve the effect you want. A search for "throttling proxy" came up with this, for example.

Confused by python file mode "w+"

All file modes in Python

  • r for reading
  • r+ opens for reading and writing (cannot truncate a file)
  • w for writing
  • w+ for writing and reading (can truncate a file)
  • rb for reading a binary file. The file pointer is placed at the beginning of the file.
  • rb+ reading or writing a binary file
  • wb+ writing a binary file
  • a+ opens for appending
  • ab+ Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.
  • x open for exclusive creation, failing if the file already exists (Python 3)

List comprehension vs map

Here is one possible case:

map(lambda op1,op2: op1*op2, list1, list2)

versus:

[op1*op2 for op1,op2 in zip(list1,list2)]

I am guessing the zip() is an unfortunate and unnecessary overhead you need to indulge in if you insist on using list comprehensions instead of the map. Would be great if someone clarifies this whether affirmatively or negatively.

How to track down access violation "at address 00000000"

When I've stumbled upon this problem I usually start looking at the places where I FreeAndNil() or just xxx := NIL; variables and the code after that.

When nothing else has helped I've added a Log() function to output messages from various suspect places during execution, and then later looked at that log to trace where in the code the access violation comes.

There are ofcourse many more elegant solutions available for tracing these violations, but if you do not have them at your disposal the old-fashioned trial & error method works fine.

How do I convert Long to byte[] and back in java

I tested the ByteBuffer method against plain bitwise operations but the latter is significantly faster.

public static byte[] longToBytes(long l) {
    byte[] result = new byte[8];
    for (int i = 7; i >= 0; i--) {
        result[i] = (byte)(l & 0xFF);
        l >>= 8;
    }
    return result;
}

public static long bytesToLong(final byte[] b) {
    long result = 0;
    for (int i = 0; i < 8; i++) {
        result <<= 8;
        result |= (b[i] & 0xFF);
    }
    return result;
}

For Java 8+ we can use the static variables that were added:

public static byte[] longToBytes(long l) {
    byte[] result = new byte[Long.BYTES];
    for (int i = Long.BYTES - 1; i >= 0; i--) {
        result[i] = (byte)(l & 0xFF);
        l >>= Byte.SIZE;
    }
    return result;
}

public static long bytesToLong(final byte[] b) {
    long result = 0;
    for (int i = 0; i < Long.BYTES; i++) {
        result <<= Byte.SIZE;
        result |= (b[i] & 0xFF);
    }
    return result;
}

Better way to convert file sizes in Python

Here are some easy-to-copy one liners to use if you already know what unit size you want. If you're looking for in a more generic function with a few nice options, see my FEB 2021 update further on...

Bytes

print ('{:,.0f}'.format(os.path.getsize(filepath))+" B")

Kilobits

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<7))+" kb")

Kilobytes

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<10))+" KB")

Megabits

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<17))+" mb")

Megabytes

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<20))+" MB")

Gigabits

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<27))+" gb")

Gigabytes

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<30))+" GB")

Terabytes

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<40))+" TB")

UPDATE FEB 2021 Here are my updated and fleshed-out functions to a) get file/folder size, b) convert into desired units:

from pathlib import Path

def get_path_size(path = Path('.'), recursive=False):
    """
    Gets file size, or total directory size

    Parameters
    ----------
    path: str | pathlib.Path
        File path or directory/folder path

    recursive: bool
        True -> use .rglob i.e. include nested files and directories
        False -> use .glob i.e. only process current directory/folder

    Returns
    -------
    int:
        File size or recursive directory size in bytes
        Use cleverutils.format_bytes to convert to other units e.g. MB
    """
    path = Path(path)
    if path.is_file():
        size = path.stat().st_size
    elif path.is_dir():
        path_glob = path.rglob('*.*') if recursive else path.glob('*.*')
        size = sum(file.stat().st_size for file in path_glob)
    return size


def format_bytes(bytes, unit, SI=False):
    """
    Converts bytes to common units such as kb, kib, KB, mb, mib, MB

    Parameters
    ---------
    bytes: int
        Number of bytes to be converted

    unit: str
        Desired unit of measure for output


    SI: bool
        True -> Use SI standard e.g. KB = 1000 bytes
        False -> Use JEDEC standard e.g. KB = 1024 bytes

    Returns
    -------
    str:
        E.g. "7 MiB" where MiB is the original unit abbreviation supplied
    """
    if unit.lower() in "b bit bits".split():
        return f"{bytes*8} {unit}"
    unitN = unit[0].upper()+unit[1:].replace("s","")  # Normalised
    reference = {"Kb Kib Kibibit Kilobit": (7, 1),
                 "KB KiB Kibibyte Kilobyte": (10, 1),
                 "Mb Mib Mebibit Megabit": (17, 2),
                 "MB MiB Mebibyte Megabyte": (20, 2),
                 "Gb Gib Gibibit Gigabit": (27, 3),
                 "GB GiB Gibibyte Gigabyte": (30, 3),
                 "Tb Tib Tebibit Terabit": (37, 4),
                 "TB TiB Tebibyte Terabyte": (40, 4),
                 "Pb Pib Pebibit Petabit": (47, 5),
                 "PB PiB Pebibyte Petabyte": (50, 5),
                 "Eb Eib Exbibit Exabit": (57, 6),
                 "EB EiB Exbibyte Exabyte": (60, 6),
                 "Zb Zib Zebibit Zettabit": (67, 7),
                 "ZB ZiB Zebibyte Zettabyte": (70, 7),
                 "Yb Yib Yobibit Yottabit": (77, 8),
                 "YB YiB Yobibyte Yottabyte": (80, 8),
                 }
    key_list = '\n'.join(["     b Bit"] + [x for x in reference.keys()]) +"\n"
    if unitN not in key_list:
        raise IndexError(f"\n\nConversion unit must be one of:\n\n{key_list}")
    units, divisors = [(k,v) for k,v in reference.items() if unitN in k][0]
    if SI:
        divisor = 1000**divisors[1]/8 if "bit" in units else 1000**divisors[1]
    else:
        divisor = float(1 << divisors[0])
    value = bytes / divisor
    if value != 1 and len(unitN) > 3:
            unitN += "s" # Create plural unit of measure
    return "{:,.0f}".format(value) + " " + unitN


# Tests 
>>> assert format_bytes(1,"b") == '8 b'
>>> assert format_bytes(1,"bits") == '8 bits'
>>> assert format_bytes(1024, "kilobyte") == "1 Kilobyte"
>>> assert format_bytes(1024, "kB") == "1 KB"
>>> assert format_bytes(7141000, "mb") == '54 Mb'
>>> assert format_bytes(7141000, "mib") == '54 Mib'
>>> assert format_bytes(7141000, "Mb") == '54 Mb'
>>> assert format_bytes(7141000, "MB") == '7 MB'
>>> assert format_bytes(7141000, "mebibytes") == '7 Mebibytes'
>>> assert format_bytes(7141000, "gb") == '0 Gb'
>>> assert format_bytes(1000000, "kB") == '977 KB'
>>> assert format_bytes(1000000, "kB", SI=True) == '1,000 KB'
>>> assert format_bytes(1000000, "kb") == '7,812 Kb'
>>> assert format_bytes(1000000, "kb", SI=True) == '8,000 Kb'
>>> assert format_bytes(125000, "kb") == '977 Kb'
>>> assert format_bytes(125000, "kb", SI=True) == '1,000 Kb'
>>> assert format_bytes(125*1024, "kb") == '1,000 Kb'
>>> assert format_bytes(125*1024, "kb", SI=True) == '1,024 Kb'

How to recursively download a folder via FTP on Linux

wget -r ftp://url

Work perfectly for Redhat and Ubuntu

What is your most productive shortcut with Vim?

In addition to the great reply about grokking vi, it should be noted that vim does add some very vi-like features that make using vi commands nicer. The one that comes to mind first are text objects: instead of {!}fmt to reformat the current paragraph, !apfmt does the same. It works by first specifying that we want to select a text object, which is the current paragraph. Similar, to change the current string literal (foo to bar for an example), instead of T"ct"bar (move to just after the previous ", change until just before the next ", insert bar), you can say ci"bar: change inside (innermost) quotes, inserting bar.

Thinking in terms of text objects instead of movement commands is quite nice.

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

ALTER TABLE is right:

ALTER TABLE MyCustomers ALTER COLUMN CompanyName VARCHAR(20) NULL

How to install Openpyxl with pip

For me it worked as Kumar Jaggal but: steps 1, 2, 3, the same 4. py -m setup.py install

How to get the value of an input field using ReactJS?

Give the <input> a unique id

<input id='title' ...>

and then use the standard Web API to reference it in the DOM

const title = document.getElementById('title').value

No need to continually update the React state with every keypress. Simply get the value when it's required.

Get resultset from oracle stored procedure

In SQL Plus:

SQL> var r refcursor
SQL> set autoprint on
SQL> exec :r := function_returning_refcursor();

Replace the last line with a call to your procedure / function and the contents of the refcursor will be displayed

IIS7 folder permissions for web application

If it's any help to anyone, give permission to "IIS_IUSRS" group.

Note that if you can't find "IIS_IUSRS", try prepending it with your server's name, like "MySexyServer\IIS_IUSRS".

Eclipse - Unable to install breakpoint due to missing line number attributes

I got the same issue, I spent a lot of time to look for solution but these solutions are unuseful, So I self study all of cases, finally I found out problem it is confliction among JDK versions. Below is steps to resolve problem: 1. Remove all of JDK and JRE version, keep only one version. 2. Set JAVA_HOME system and java compiler in Eclipse is the same. In some cases, the error above will not disappear, but we be able to run at debug model.

What exactly is a Context in Java?

A Context represents your environment. It represents the state surrounding where you are in your system.

For example, in web programming in Java, you have a Request, and a Response. These are passed to the service method of a Servlet.

A property of the Servlet is the ServletConfig, and within that is a ServletContext.

The ServletContext is used to tell the servlet about the Container that the Servlet is within.

So, the ServletContext represents the servlets environment within its container.

Similarly, in Java EE, you have EBJContexts that elements (like session beans) can access to work with their containers.

Those are two examples of contexts used in Java today.

Edit --

You mention Android.

Look here: http://developer.android.com/reference/android/content/Context.html

You can see how this Context gives you all sorts of information about where the Android app is deployed and what's available to it.

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

T_PAAMAYIM_NEKUDOTAYIM is the double colon scope resolution thingy PHP uses - ::

Quick glance at your code, I think this line:

return $cnf::getConfig($key);

should be

return $cnf->getConfig($key);

The first is the way to call a method statically - this code would be valid if $cnf contained a string that was also a valid class. The -> syntax is for calling a method on an instance of a class/object.

Java 8: merge lists with stream API

Alternative: Stream.concat()

Stream.concat(map.values().stream(), listContainer.lst.stream())
                             .collect(Collectors.toList()

Color picker utility (color pipette) in Ubuntu

I recommend GPick:

sudo apt-get install gpick

Applications -> Graphics -> GPick

It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.

If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.

It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.

Why do I always get the same sequence of random numbers with rand()?

To quote from man rand :

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

So, with no seed value, rand() assumes the seed as 1 (every time in your case) and with the same seed value, rand() will produce the same sequence of numbers.

OpenCV - Saving images to a particular folder of choice

Thank you everyone. Your ways are perfect. I would like to share another way I used to fix the problem. I used the function os.chdir(path) to change local directory to path. After which I saved image normally.

Using "Object.create" instead of "new"

Object.create is not yet standard on several browsers, for example IE8, Opera v11.5, Konq 4.3 do not have it. You can use Douglas Crockford's version of Object.create for those browsers but this doesn't include the second 'initialisation object' parameter used in CMS's answer.

For cross browser code one way to get object initialisation in the meantime is to customise Crockford's Object.create. Here is one method:-

Object.build = function(o) {
   var initArgs = Array.prototype.slice.call(arguments,1)
   function F() {
      if((typeof o.init === 'function') && initArgs.length) {
         o.init.apply(this,initArgs)
      }
   }
   F.prototype = o
   return new F()
}

This maintains Crockford prototypal inheritance, and also checks for any init method in the object, then runs it with your parameter(s), like say new man('John','Smith'). Your code then becomes:-

MY_GLOBAL = {i: 1, nextId: function(){return this.i++}}  // For example

var userB = {
    init: function(nameParam) {
        this.id = MY_GLOBAL.nextId();
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};
var bob = Object.build(userB, 'Bob');  // Different from your code
bob.sayHello();

So bob inherits the sayHello method and now has own properties id=1 and name='Bob'. These properties are both writable and enumerable of course. This is also a much simpler way to initialise than for ECMA Object.create especially if you aren't concerned about the writable, enumerable and configurable attributes.

For initialisation without an init method the following Crockford mod could be used:-

Object.gen = function(o) {
   var makeArgs = arguments 
   function F() {
      var prop, i=1, arg, val
      for(prop in o) {
         if(!o.hasOwnProperty(prop)) continue
         val = o[prop]
         arg = makeArgs[i++]
         if(typeof arg === 'undefined') break
         this[prop] = arg
      }
   }
   F.prototype = o
   return new F()
}

This fills the userB own properties, in the order they are defined, using the Object.gen parameters from left to right after the userB parameter. It uses the for(prop in o) loop so, by ECMA standards, the order of property enumeration cannot be guaranteed the same as the order of property definition. However, several code examples tested on (4) major browsers show they are the same, provided the hasOwnProperty filter is used, and sometimes even if not.

MY_GLOBAL = {i: 1, nextId: function(){return this.i++}};  // For example

var userB = {
   name: null,
   id: null,
   sayHello: function() {
      console.log('Hello '+ this.name);
   }
}

var bob = Object.gen(userB, 'Bob', MY_GLOBAL.nextId());

Somewhat simpler I would say than Object.build since userB does not need an init method. Also userB is not specifically a constructor but looks like a normal singleton object. So with this method you can construct and initialise from normal plain objects.

stale element reference: element is not attached to the page document

To handle it, I use the following click method. This will attempt to find and click the element. If the DOM changes between the find and click, it will try again. The idea is that if it failed and I try again immediately the second attempt will succeed. If the DOM changes are very rapid then this will not work.

public boolean retryingFindClick(By by) {
    boolean result = false;
    int attempts = 0;
    while(attempts < 2) {
        try {
            driver.findElement(by).click();
            result = true;
            break;
        } catch(StaleElementException e) {
        }
        attempts++;
    }
    return result;
}

Deprecated: mysql_connect()

Deprecated features in PHP 5.5.x

The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the **MYSQLi or PDO_MySQL extensions.**

Syntax:

<?php
  $connect = mysqli_connect('localhost', 'user', 'password', 'dbname');

Also, replace all mysql_* functions into mysqli_* functions

instead of

<?php
 $connect = mysql_connect('localhost','root','');
  mysql_select_db('dbname');
?> 

How do I check if a string is unicode or ascii?

use:

import six
if isinstance(obj, six.text_type)

inside the six library it is represented as:

if PY3:
    string_types = str,
else:
    string_types = basestring,

Vector erase iterator

The it++ instruction is done at the end of the block. So if your are erasing the last element, then you try to increment the iterator that is pointing to an empty collection.

Error: Generic Array Creation

Besides the way suggested in the "possible duplicate", the other main way of getting around this problem is for the array itself (or at least a template of one) to be supplied by the caller, who will hopefully know the concrete type and can thus safely create the array.

This is the way methods like ArrayList.toArray(T[]) are implemented. I'd suggest you take a look at that method for inspiration. Better yet, you should probably be using that method anyway as others have noted.

How to check Network port access and display useful message?

You can check if the Connected property is set to $true and display a friendly message:

    $t = New-Object Net.Sockets.TcpClient "10.45.23.109", 443 

    if($t.Connected)
    {
        "Port 443 is operational"
    }
    else
    {
        "..."
    }

Is #pragma once a safe include guard?

I don't know about any performance benefits but it certainly works. I use it in all my C++ projects (granted I am using the MS compiler). I find it to be more effective than using

#ifndef HEADERNAME_H
#define HEADERNAME_H
...
#endif

It does the same job and doesn't populate the preprocessor with additional macros.

GCC supports #pragma once officially as of version 3.4.

C# guid and SQL uniqueidentifier

Store it in the database in a field with a data type of uniqueidentifier.

Mongodb: failed to connect to server on first connect

if it is cluster MongoDB then you need to add your current IP to the cluster, to add your current IP address you need to complete few steps below-

step 1- go to login page of Mongodb and login with valid credential - https://cloud.mongodb.com/user#/atlas/login
step 2- CLick Network Access from left sidebar under Security Section
Step 3 - Click Add IP Address
Step 4 - Click Add Current IP Address or Allow Connection From Any Where
now try to connect - npm start

enter image description here

and for Local MongoDB use mongo String like "mongodb+srv://username:pass%[email protected]/test?retryWrites=true&w=majority"

password must be encoded like example string

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

In your storyboard you should set the 'Identifier' of your prototype cell to be the same as your CellReuseIdentifier "Cell". Then you won't get that message or need to call that registerClass: function.

How to start Apache and MySQL automatically when Windows 8 comes up

Ok, so I've tried using the Xampp Control Panel and choosing from the Config menu to start MySQL did not work. Instead go to C:\xampp\mysql and run a file entitled mysql_installservice and MySQL will automatically run as a Windows service.

What is the difference between Tomcat, JBoss and Glassfish?

Both JBoss and Tomcat are Java servlet application servers, but JBoss is a whole lot more. The substantial difference between the two is that JBoss provides a full Java Enterprise Edition (Java EE) stack, including Enterprise JavaBeans and many other technologies that are useful for developers working on enterprise Java applications.

Tomcat is much more limited. One way to think of it is that JBoss is a Java EE stack that includes a servlet container and web server, whereas Tomcat, for the most part, is a servlet container and web server.

Skip first couple of lines while reading lines in Python file

Here are the timeit results for the top 2 answers. Note that "file.txt" is a text file containing 100,000+ lines of random string with a file size of 1MB+.

Using itertools:

import itertools
from timeit import timeit

timeit("""with open("file.txt", "r") as fo:
    for line in itertools.islice(fo, 90000, None):
        line.strip()""", number=100)

>>> 1.604976346003241

Using two for loops:

from timeit import timeit

timeit("""with open("file.txt", "r") as fo:
    for i in range(90000):
        next(fo)
    for j in fo:
        j.strip()""", number=100)

>>> 2.427317383000627

clearly the itertools method is more efficient when dealing with large files.

Is it possible to sort a ES6 map object?

Slight variation - I didn't have spread syntax and I wanted to work on an object instead of a Map.

Object.fromEntries(Object.entries(apis).sort())

How to break line in JavaScript?

I was facing the same problem. For my solution, I added br enclosed between 2 brackets < > enclosed in double quotation marks, and preceded and followed by the + sign:

+"<br>"+

Try this in your browser and see, it certainly works in my Internet Explorer.

Why use armeabi-v7a code over armeabi code?

EABI = Embedded Application Binary Interface. It is such specifications to which an executable must conform in order to execute in a specific execution environment. It also specifies various aspects of compilation and linkage required for interoperation between toolchains used for the ARM Architecture. In this context when we speak about armeabi we speak about ARM architecture and GNU/Linux OS. Android follows the little-endian ARM GNU/Linux ABI.

armeabi application will run on ARMv5 (e.g. ARM9) and ARMv6 (e.g. ARM11). You may use Floating Point hardware if you build your application using proper GCC options like -mfpu=vfpv3 -mfloat-abi=softfp which tells compiler to generate floating point instructions for VFP hardware and enables the soft-float calling conventions. armeabi doesn't support hard-float calling conventions (it means FP registers are not used to contain arguments for a function), but FP operations in HW are still supported.

armeabi-v7a application will run on Cortex A# devices like Cortex A8, A9, and A15. It supports multi-core processors and it supports -mfloat-abi=hard. So, if you build your application using -mfloat-abi=hard, many of your function calls will be faster.

Calculating Page Table Size

Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***

403 Forbidden vs 401 Unauthorized HTTP responses

These are the meanings:

401: User not (correctly) authenticated, the resource/page require authentication

403: User authenticated, but his role or permissions does not allow to access requested resource, for instance user is not an administrator and requested page is for administrators

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

How to give ASP.NET access to a private key in a certificate in the certificate store?

If you are trying to load a cert from a .pfx file in IIS the solution may be as simple as enabling this option for the Application Pool.

Right click on the App Pool and select Advanced Settings.

Then enable Load User Profile


enter image description here

Force update of an Android app when a new version is available

It is better to define our own process to for upgrade.

  1. Create a web service which gives latest version for app (ios,android) from our server.
  2. Or Any web service that you used in app (e.g Login) will return latest app version from server.
  3. Once app will get version from #1 or 2. App will cross check it with local/cuurent appversion. if there is difference then we can show alert as follows,

Android & iOS : If latest app version available then it will show alert as “Latest version available with more features, To upgrade click on upgrade button” (Alert with “Upgarde” and “No. Thanks” button.) Then app will redirect to playstore/Appstore and it will open latest version.

 --- we can do upgrade compulsory or optionally.

Before Upgrade process please make sure that you handled proper db migration process if there is any db schema change.

source of historical stock data

I'd crawl finance.google.com (for the quotes) - or finance.yahoo.com.

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

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

For more, see Quote History

How to initialize all members of an array to the same value?

If the array happens to be int or anything with the size of int or your mem-pattern's size fits exact times into an int (i.e. all zeroes or 0xA5A5A5A5), the best way is to use memset().

Otherwise call memcpy() in a loop moving the index.

Excel function to get first word from sentence in other cell

How about something like

=LEFT(A1,SEARCH(" ",A1)-1)

or

=LEFT(A1,SEARCH("<b>",A1)-1)

Have a look at MS Excel: Search Function and Excel 2007 LEFT Function

Web.Config Debug/Release

It is possible using ConfigTransform build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/

All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.

The same applies to "app.*.config" transform files in non-web projects.

and then adding the following target to your *.csproj.

<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
    <TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>

Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.

Make a link open a new window (not tab)

That will open a new window, not tab (with JavaScript, but quite laconically):

<a href="print.html"  
    onclick="window.open('print.html', 
                         'newwindow', 
                         'width=300,height=250'); 
              return false;"
 >Print</a>

Style disabled button with CSS

For the disabled buttons you can use the :disabled pseudo-element. It works for all the elements.

For browsers/devices supporting CSS2 only, you can use the [disabled] selector.

As with the image, don't put an image in the button. Use CSS background-image with background-position and background-repeat. That way, the image dragging will not occur.

Selection problem: here is a link to the specific question:

Example for the disabled selector:

_x000D_
_x000D_
button {_x000D_
  border: 1px solid #0066cc;_x000D_
  background-color: #0099cc;_x000D_
  color: #ffffff;_x000D_
  padding: 5px 10px;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
  border: 1px solid #0099cc;_x000D_
  background-color: #00aacc;_x000D_
  color: #ffffff;_x000D_
  padding: 5px 10px;_x000D_
}_x000D_
_x000D_
button:disabled,_x000D_
button[disabled]{_x000D_
  border: 1px solid #999999;_x000D_
  background-color: #cccccc;_x000D_
  color: #666666;_x000D_
}_x000D_
_x000D_
div {_x000D_
  padding: 5px 10px;_x000D_
}
_x000D_
<div>_x000D_
  <button> This is a working button </button>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <button disabled> This is a disabled button </button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I increment a char?

For me i made the fallowing as a test.

string_1="abcd"

def test(string_1):
   i = 0
   p = ""
   x = len(string_1)
   while i < x:
    y = (string_1)[i]
    i=i+1
    s = chr(ord(y) + 1)
    p=p+s

   print(p)

test(string_1)

How do you detect the clearing of a "search" HTML5 input?

I want to add a "late" answer, because I struggled with change, keyup and search today, and maybe what I found in the end may be useful for others too. Basically, I have a search-as-type panel, and I just wanted to react properly to the press of the little X (under Chrome and Opera, FF does not implement it), and clear a content pane as a result.

I had this code:

 $(some-input).keyup(function() { 
    // update panel
 }
 $(some-input).change(function() { 
    // update panel
 }
 $(some-input).on("search", function() { 
    // update panel
 }

(They are separate because I wanted to check when and under which circumstances each was called).

It turns out that Chrome and Firefox react differently. In particular, Firefox treats change as "every change to the input", while Chrome treats it as "when focus is lost AND the content is changed". So, on Chrome the "update panel" function was called once, on FF twice for every keystroke (one in keyup, one in change)

Additionally, clearing the field with the small X (which is not present under FF) fired the search event under Chrome: no keyup, no change.

The conclusion? Use input instead:

 $(some-input).on("input", function() { 
    // update panel
 }

It works with the same behaviour under all the browsers I tested, reacting at every change in the input content (copy-paste with the mouse, autocompletion and "X" included).

npm - EPERM: operation not permitted on Windows

Just run cmd as admin. delete old node_modules folder and run npm install again.

How can I use Bash syntax in Makefile targets?

You can call bash directly, use the -c flag:

bash -c "diff <(sort file1) <(sort file2) > $@"

Of course, you may not be able to redirect to the variable $@, but when I tried to do this, I got -bash: $@: ambiguous redirect as an error message, so you may want to look into that before you get too into this (though I'm using bash 3.2.something, so maybe yours works differently).

Android: Tabs at the BOTTOM

There are two ways to display tabs at the bottom of a tab activity.

  1. Using relative layout
  2. Using Layout_weight attribute

Please check the link for more details.

Compile/run assembler in Linux?

If you are using NASM, the command-line is just

nasm -felf32 -g -Fdwarf file.asm -o file.o

where 'file.asm' is your assembly file (code) and 'file.o' is an object file you can link with gcc -m32 or ld -melf_i386. (Assembling with nasm -felf64 will make a 64-bit object file, but the hello world example below uses 32-bit system calls, and won't work in a PIE executable.)

Here is some more info:

http://www.nasm.us/doc/nasmdoc2.html#section-2.1

You can install NASM in Ubuntu with the following command:

apt-get install nasm

Here is a basic Hello World in Linux assembly to whet your appetite:

http://web.archive.org/web/20120822144129/http://www.cin.ufpe.br/~if817/arquivos/asmtut/index.html

I hope this is what you were asking...

Using a dictionary to count the items in a list

How about this:

src = [ 'one', 'two', 'three', 'two', 'three', 'three' ]
result_dict = dict( [ (i, src.count(i)) for i in set(src) ] )

This results in

{'one': 1, 'three': 3, 'two': 2}

Entity Framework 6 Code first Default value

It's been a while, but leaving a note for others. I achieved what is needed with an attribute and I decorated my model class fields with that attribute as I want.

[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDateUtc { get; set; }

Got the help of these 2 articles:

What I did:

Define Attribute

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
    public string DefaultValue { get; set; }
}

In the "OnModelCreating" of the context

modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));

In the custom SqlGenerator

private void SetAnnotatedColumn(ColumnModel col)
{
    AnnotationValues values;
    if (col.Annotations.TryGetValue("SqlDefaultValue", out values))
    {
         col.DefaultValueSql = (string)values.NewValue;
    }
}

Then in the Migration Configuration constructor, register the custom SQL generator.

SetSqlGenerator("System.Data.SqlClient", new CustomMigrationSqlGenerator());

delete all record from table in mysql

truncate tableName

That is what you are looking for.

Truncate will delete all records in the table, emptying it.

Invalid length for a Base-64 char array

My guess is that you simply need to URL-encode your Base64 string when you include it in the querystring.

Base64 encoding uses some characters which must be encoded if they're part of a querystring (namely + and /, and maybe = too). If the string isn't correctly encoded then you won't be able to decode it successfully at the other end, hence the errors.

You can use the HttpUtility.UrlEncode method to encode your Base64 string:

string msg = "Please click on the link below or paste it into a browser "
             + "to verify your email account.<br /><br /><a href=\""
             + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
             + HttpUtility.UrlEncode(userName.Encrypt("verify")) + "\">"
             + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
             + HttpUtility.UrlEncode(userName.Encrypt("verify")) + "</a>";

How to programmatically send SMS on the iPhone?

You need to use the MFMessageComposeViewController if you want to show creating and sending the message in your own app.

Otherwise, you can use the sharedApplication method.

In MS DOS copying several files to one file

filenames must sort correctly to combine correctly!

file1.bin file2.bin ... file10.bin wont work properly

file01.bin file02.bin ... file10.bin will work properly

c:>for %i in (file*.bin) do type %i >> onebinary.bin

Works for ascii or binary files.

What exactly is LLVM?

A good summary of LLVM is this:

enter image description here

At the frontend you have Perl, and many other high level languages. At the backend, you have the natives code that run directly on the machine.

At the centre is your intermediate code representation. If every high level language can be represented in this LLVM IR format, then analysis tools based on this IR can be easily reused - that is the basic rationale.

How do you read a file into a list in Python?

If you have multiple numbers per line and you have multiple lines, you can read them in like this:

    #!/usr/bin/env python

    from os.path import dirname

    with open(dirname(__file__) + '/data/path/filename.txt') as input_data:
        input_list= [map(int,num.split()) for num in input_data.readlines()]

Can Twitter Bootstrap alerts fade in as well as out?

I don't agree with the way that Bootstrap uses fade in (as seen in their documentation - http://v4-alpha.getbootstrap.com/components/alerts/), and my suggestion is to avoid the class names fade and in, and to avoid that pattern in general (which is currently seen in the top-rated answer to this question).

(1) The semantics are wrong - transitions are temporary, but the class names live on. So why should we name our classes fade and fade in? It should be faded and faded-in, so that when developers read the markup, it's clear that those elements were faded or faded-in. The Bootstrap team has already done away with hide for hidden, why is fade any different?

(2) Using 2 classes fade and in for a single transition pollutes the class space. And, it's not clear that fade and in are associated with one another. The in class looks like a completely independent class, like alert and alert-success.

The best solution is to use faded when the element has been faded out, and to replace that class with faded-in when the element has been faded in.

Alert Faded

So to answer the question. I think the alert markup, style, and logic should be written in the following manner. Note: Feel free to replace the jQuery logic, if you're using vanilla javascript.

HTML

<div id="saveAlert" class="alert alert-success">
  <a class="close" href="#">×</a>
  <p><strong>Well done!</strong> You successfully read this alert message.</p>
</div>

CSS

.faded {
  opacity: 0;
  transition: opacity 1s;
}

JQuery

$('#saveAlert .close').on('click', function () {

  $("#saveAlert")
    .addClass('faded');

});

Cloning an array in Javascript/Typescript

The following line in your code creates a new array, copies all object references from genericItems into that new array, and assigns it to backupData:

this.backupData = this.genericItems.slice();

So while backupData and genericItems are different arrays, they contain the same exact object references.

You could bring in a library to do deep copying for you (as @LatinWarrior mentioned).

But if Item is not too complex, maybe you can add a clone method to it to deep clone the object yourself:

class Item {
  somePrimitiveType: string;
  someRefType: any = { someProperty: 0 };

  clone(): Item {
    let clone = new Item();

    // Assignment will copy primitive types

    clone.somePrimitiveType = this.somePrimitiveType;

    // Explicitly deep copy the reference types

    clone.someRefType = {
      someProperty: this.someRefType.someProperty
    };

    return clone;
  }
}

Then call clone() on each item:

this.backupData = this.genericItems.map(item => item.clone());

Java 8 LocalDate Jackson format

If your request contains an object like this:

{
    "year": 1900,
    "month": 1,
    "day": 20
}

Then you can use:

data class DateObject(
    val day: Int,
    val month: Int,
    val year: Int
)
class LocalDateConverter : StdConverter<DateObject, LocalDate>() {
    override fun convert(value: DateObject): LocalDate {
        return value.run { LocalDate.of(year, month, day) }
    }
}

Above the field:

@JsonDeserialize(converter = LocalDateConverter::class)
val dateOfBirth: LocalDate

The code is in Kotlin but this would work for Java too of course.

How to set image to fit width of the page using jsPDF?

A better solution is to set the doc width/height using the aspect ratio of your image.

_x000D_
_x000D_
var ExportModule = {_x000D_
  // Member method to convert pixels to mm._x000D_
  pxTomm: function(px) {_x000D_
    return Math.floor(px / $('#my_mm').height());_x000D_
  },_x000D_
  ExportToPDF: function() {_x000D_
    var myCanvas = document.getElementById("exportToPDF");_x000D_
_x000D_
    html2canvas(myCanvas, {_x000D_
      onrendered: function(canvas) {_x000D_
        var imgData = canvas.toDataURL(_x000D_
          'image/jpeg', 1.0);_x000D_
        //Get the original size of canvas/image_x000D_
        var img_w = canvas.width;_x000D_
        var img_h = canvas.height;_x000D_
_x000D_
        //Convert to mm_x000D_
        var doc_w = ExportModule.pxTomm(img_w);_x000D_
        var doc_h = ExportModule.pxTomm(img_h);_x000D_
        //Set doc size_x000D_
        var doc = new jsPDF('l', 'mm', [doc_w, doc_h]);_x000D_
_x000D_
        //set image height similar to doc size_x000D_
        doc.addImage(imgData, 'JPG', 0, 0, doc_w, doc_h);_x000D_
        var currentTime = new Date();_x000D_
        doc.save('Dashboard_' + currentTime + '.pdf');_x000D_
_x000D_
      }_x000D_
    });_x000D_
  },_x000D_
}
_x000D_
<script src="Scripts/html2canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/jsPDF.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/addimage.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/fileSaver.js"></script>_x000D_
<div id="my_mm" style="height: 1mm; display: none"></div>_x000D_
_x000D_
<div id="exportToPDF">_x000D_
  Your html here._x000D_
</div>_x000D_
_x000D_
<button id="export_btn" onclick="ExportModule.ExportToPDF();">Export</button>
_x000D_
_x000D_
_x000D_

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

If you're having this issue, and try to run bundle exec jekyll serve per this Jekyll documentation, it'll ask you to run bundle install, which should prompt you to install any missing gems, which in this case will be rake. This should resolve your issue.

You may also need to run bundle update to ensure Gemfile.lock is referencing the most up-to-date gems.

The transaction log for the database is full

Do you have Enable Autogrowth and Unrestricted File Growth both enabled for the log file? You can edit these via SSMS in "Database Properties > Files"

Difference between a User and a Login in SQL Server

I think there is a really good MSDN blog post about this topic by Laurentiu Cristofor:

The first important thing that needs to be understood about SQL Server security is that there are two security realms involved - the server and the database. The server realm encompasses multiple database realms. All work is done in the context of some database, but to get to do the work, one needs to first have access to the server and then to have access to the database.

Access to the server is granted via logins. There are two main categories of logins: SQL Server authenticated logins and Windows authenticated logins. I will usually refer to these using the shorter names of SQL logins and Windows logins. Windows authenticated logins can either be logins mapped to Windows users or logins mapped to Windows groups. So, to be able to connect to the server, one must have access via one of these types or logins - logins provide access to the server realm.

But logins are not enough, because work is usually done in a database and databases are separate realms. Access to databases is granted via users.

Users are mapped to logins and the mapping is expressed by the SID property of logins and users. A login maps to a user in a database if their SID values are identical. Depending on the type of login, we can therefore have a categorization of users that mimics the above categorization for logins; so, we have SQL users and Windows users and the latter category consists of users mapped to Windows user logins and of users mapped to Windows group logins.

Let's take a step back for a quick overview: a login provides access to the server and to further get access to a database, a user mapped to the login must exist in the database.

that's the link to the full post.

how to create a login page when username and password is equal in html

Doing password checks on client side is unsafe especially when the password is hard coded.

The safest way is password checking on server side, but even then the password should not be transmitted plain text.

Checking the password client side is possible in a "secure way":

  • The password needs to be hashed
  • The hashed password is used as part of a new url

Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).

How can I login to a website with Python?

Maybe you want to use twill. It's quite easy to use and should be able to do what you want.

It will look like the following:

from twill.commands import *
go('http://example.org')

fv("1", "email-email", "blabla.com")
fv("1", "password-clear", "testpass")

submit('0')

You can use showforms() to list all forms once you used go… to browse to the site you want to login. Just try it from the python interpreter.

Type or namespace name does not exist

I got a very similar error message that was caused by inadvertently having made a duplicate of a class in another project of my solution. Deleting the duplicate fixed the issue

Register .NET Framework 4.5 in IIS 7.5

use .NET3.5 it worked for me for similar issue.

How to get numeric value from a prompt box?

var xInt = parseInt(x)

This will return either the integer value, or NaN.

Read more about parseInt here.

How to show full height background image?

 html, body {
    height:100%;
}

body { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Xcode 8 shows error that provisioning profile doesn't include signing certificate

This happens because the provisioning profile can't find the file for the certificate it is linked to.

To fix:

  1. Check which certificate is linked to your provisioning profile by clicking edit on your provisioning profile in the Certificates, Identifiers & Profiles section of the Apple Developer dashboard
  2. Download the certificate from the dashboard
  3. Double click the file to install it in your keychain
  4. Drag the file into Xcode to be extra sure it is linked

The error should be gone now.

Converting ArrayList to Array in java

Here is the solution for you given scenario -

List<String>ls = new ArrayList<String>();
    ls.add("dfsa#FSDfsd");
    ls.add("dfsdaor#ooiui");
    String[] firstArray = new String[ls.size()];    
 firstArray =ls.toArray(firstArray);
String[] secondArray = new String[ls.size()];
for(int i=0;i<ls.size();i++){
secondArray[i]=firstArray[i].split("#")[0];
firstArray[i]=firstArray[i].split("#")[1];
} 

How do I check if PHP is connected to a database already?

Baron Schwartz blogs that due to race conditions, this 'check before write' is a bad practice. He advocates a try/catch pattern with a reconnect in the catch. Here is the pseudo code he recommends:

function query_database(connection, sql, retries=1)
   while true
      try
         result=connection.execute(sql)
         return result
      catch InactiveConnectionException e
         if retries > 0 then
            retries = retries - 1
            connection.reconnect()
         else
            throw e
         end
      end
   end
end

Here is his full blog: https://www.percona.com/blog/2010/05/05/checking-for-a-live-database-connection-considered-harmful/

How do I close an Android alertdialog

Use setNegative button, no Positive button required! I promise you'll win x

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Inspired by [@JulieLerman 's DDD MSDN Mag Article 2013][1]

    public class ShippingContext : BaseContext<ShippingContext>
{
  public DbSet<Shipment> Shipments { get; set; }
  public DbSet<Shipper> Shippers { get; set; }
  public DbSet<OrderShippingDetail> Order { get; set; } //Orders table
  public DbSet<ItemToBeShipped> ItemsToBeShipped { get; set; }
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Ignore<LineItem>();
    modelBuilder.Ignore<Order>();
    modelBuilder.Configurations.Add(new ShippingAddressMap());
  }
}

public class BaseContext<TContext>
  DbContext where TContext : DbContext
{
  static BaseContext()
  {
    Database.SetInitializer<TContext>(null);
  }
  protected BaseContext() : base("DPSalesDatabase")
  {}
}   

"If you’re doing new development and you want to let Code First create or migrate your database based on your classes, you’ll need to create an “uber-model” using a DbContext that includes all of the classes and relationships needed to build a complete model that represents the database. However, this context must not inherit from BaseContext." JL

Android widget: How to change the text of a button

I was able to change the button's text like this:

import android.widget.RemoteViews;

//grab the layout, then set the text of the Button called R.id.Counter:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");

Create table with jQuery - append

It is important to note that you could use Emmet to achieve the same result. First, check what Emmet can do for you at https://emmet.io/

In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below:

Example #1

ul>li*5

... will produce

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

Example #2

div#header+div.page+div#footer.class1.class2.class3

... will produce

<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>

And list goes on. There are more examples at https://docs.emmet.io/abbreviations/syntax/

And there is a library for doing that using jQuery. It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js

How to write a comment in a Razor view?

This comment syntax should work for you:

@* enter comments here *@

How can I display a tooltip on an HTML "option" tag?

I don't think this would be possible to do across all browsers.

W3Schools reports that the option events exist in all browsers, but after setting up this test demo. I can only get it to work for Firefox (not Chrome or IE), I haven't tested it on other browsers.

Firefox also allows mouseenter and mouseleave but this is not reported on the w3schools page.


Update: Honestly, from looking at the example code you provided, I wouldn't even use a select box. I think it would look nicer with a slider. I've updated your demo. I had to make a few minor changes to your ratings object (adding a level number) and the safesurf tab. But I left pretty much everything else intact.

Can anyone recommend a simple Java web-app framework?

try Vaadin! Very simple and you'll be able to work the UI with ease as well! www.vaadin.com

How to automatically update an application without ClickOnce?

I think you should check the following project at codeplex.com http://autoupdater.codeplex.com/

This sample application is developed in C# as a library with the project name “AutoUpdater”. The DLL “AutoUpdater” can be used in a C# Windows application(WinForm and WPF).

There are certain features about the AutoUpdater:

  1. Easy to implement and use.
  2. Application automatic re-run after checking update.
  3. Update process transparent to the user.
  4. To avoid blocking the main thread using multi-threaded download.
  5. Ability to upgrade the system and also the auto update program.
  6. A code that doesn't need change when used by different systems and could be compiled in a library.
  7. Easy for user to download the update files.

How to use?

In the program that you want to be auto updateable, you just need to call the AutoUpdate function in the Main procedure. The AutoUpdate function will check the version with the one read from a file located in a Web Site/FTP. If the program version is lower than the one read the program downloads the auto update program and launches it and the function returns True, which means that an auto update will run and the current program should be closed. The auto update program receives several parameters from the program to be updated and performs the auto update necessary and after that launches the updated system.

  #region check and download new version program
  bool bSuccess = false;
  IAutoUpdater autoUpdater = new AutoUpdater();
  try
  {
      autoUpdater.Update();
      bSuccess = true;
  }
  catch (WebException exp)
  {
      MessageBox.Show("Can not find the specified resource");
  }
  catch (XmlException exp)
  {
      MessageBox.Show("Download the upgrade file error");
  }
  catch (NotSupportedException exp)
  {
      MessageBox.Show("Upgrade address configuration error");
  }
  catch (ArgumentException exp)
  {
      MessageBox.Show("Download the upgrade file error");
  }
  catch (Exception exp)
  {
      MessageBox.Show("An error occurred during the upgrade process");
  }
  finally
  {
      if (bSuccess == false)
      {
          try
          {
              autoUpdater.RollBack();
          }
          catch (Exception)
          {
             //Log the message to your file or database
          }
      }
  }
  #endregion

How to add image to canvas

You have to use .onload

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); 

const drawImage = (url) => {
    const image = new Image();
    image.src = url;
    image.onload = () => {
       ctx.drawImage(image, 0, 0)
    }
}

Here's Why

If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()

Java Try Catch Finally blocks without Catch

The inner finally is executed prior to throwing the exception to the outer block.

public class TryCatchFinally {

  public static void main(String[] args) throws Exception {

    try{
        System.out.println('A');
        try{
            System.out.println('B');
            throw new Exception("threw exception in B");
        }
        finally
        {
            System.out.println('X');
        }
        //any code here in the first try block 
        //is unreachable if an exception occurs in the second try block
    }
    catch(Exception e)
    {
        System.out.println('Y');
    }
    finally
    {
        System.out.println('Z');
    }
  }
}

Results in

A
B
X
Y
Z

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

string.split - by multiple character delimiter

More fast way using directly a no-string array but a string:

string[] StringSplit(string StringToSplit, string Delimitator)
{
    return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}

StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/

Setting a spinner onClickListener() in Android

Whenever you have to perform some action on the click of the Spinner in Android, use the following method.

mspUserState.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            doWhatIsRequired();
        }
        return false;
    }
});

One thing to keep in mind is always to return False while using the above method. If you will return True then the dropdown items of the spinner will not be displayed on clicking the Spinner.

Convert Linq Query Result to Dictionary

Looking at your example, I think this is what you want:

var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);

How to filter multiple values (OR operation) in angularJS

I believe this is what you're looking for:

<div>{{ (collection | fitler1:args) + (collection | filter2:args) }}</div>

How to edit incorrect commit message in Mercurial?

I did it this way. Firstly, don't push your changes or you are out of luck. Grab and install the collapse extension. Commit another dummy changeset. Then use collapse to combine the previous two changesets into one. It will prompt you for a new commit message, giving you the messages that you already have as a starting point. You have effectively changed your original commit message.

Run .jar from batch-file

inside .bat file format

SET CLASSPATH=%Path%;

-------set java classpath and give jar location-------- set classpath=%CLASSPATH%;../lib/MoveFiles.jar;

---------mention your fully classified name of java class to run, which was given in jar------ Java com.mits.MoveFiles pause

How to Reload ReCaptcha using JavaScript?

Or you could just simulate a click on the refresh button

// If recaptcha object exists, refresh it
    if (typeof Recaptcha != "undefined") {
      jQuery('#recaptcha_reload').click();
    }

Lightweight workflow engine for Java

I recently open sourced Piper (https://github.com/creactiviti/piper) a distributed and very light weight, Spring-based, workflow engine.

How do I add comments to package.json for npm install?

I have a funny hack idea.

Create an npm package name suitably as a comment divider for dependencies and devDependencies block in file package.json, for example x----x----x

{
    "name": "app-name",
    "dependencies": {
        "x----x----x": "this is the first line of a comment",
        "babel-cli": "6.x.x",
        "babel-core": "6.x.x",
        "x----x----x": "this is the second line of a comment",
        "knex": "^0.11.1",
        "mocha": "1.20.1",
        "x----x----x": "*"
    }
}

NOTE: You must add the last comment divider line with a valid version, like * in the block.

JavaScript backslash (\) in variables is causing an error

If you want to use special character in javascript variable value, Escape Character (\) is required.

Backslash in your example is special character, too.

So you should do something like this,

var ttt = "aa ///\\\\\\"; // --> ///\\\

or

var ttt = "aa ///\\"; // --> ///\

But Escape Character not require for user input.

When you press / in prompt box or input field then submit, that means single /.

How to overwrite styling in Twitter Bootstrap

Came across this late, but I think it could use another answer.

If you're using sass, you can actually change the variables before you import bootstrap. http://twitter.github.com/bootstrap/customize.html#variables

Change any of them, such as:

$bodyBackground: red;
@import "bootstrap";

Alternatively if there isn't a variable available for what you want to change, you can override the styles or add your own.

Sass:

@import "bootstrap";

/* override anything manually, like rounded buttons */
.btn {
  border-radius: 0;
}

Also see this: Proper SCSS Asset Structure in Rails

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

What causes "Unable to access jarfile" error?

[Possibly Windows only]

Beware of spaces in the path, even when your jar is in the current working directory. For example, for me this was failing:

java -jar myjar.jar

I was able to fix this by givng the full, quoted path to the jar:

java -jar "%~dp0\myjar.jar" 

Credit goes to this answer for setting me on the right path....

Currently running queries in SQL Server

There's this, from SQL Server DMV's In Action book:

The output shows the spid (process identifier), the ecid (this is similar to a thread within the same spid and is useful for identifying queries running in parallel), the user running the SQL, the status (whether the SQL is running or waiting), the wait status (why it’s waiting), the hostname, the domain name, and the start time (useful for determining how long the batch has been running).

The nice part is the query and parent query. That shows, for example, a stored proc as the parent and the query within the stored proc that is running. It has been very handy for me. I hope this helps someone else.

USE master
GO
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
er.session_Id AS [Spid]
, sp.ecid
, er.start_time
, DATEDIFF(SS,er.start_time,GETDATE()) as [Age Seconds]
, sp.nt_username
, er.status
, er.wait_type
, SUBSTRING (qt.text, (er.statement_start_offset/2) + 1,
((CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE er.statement_end_offset
END - er.statement_start_offset)/2) + 1) AS [Individual Query]
, qt.text AS [Parent Query]
, sp.program_name
, sp.Hostname
, sp.nt_domain


FROM sys.dm_exec_requests er
INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
WHERE session_Id > 50
AND session_Id NOT IN (@@SPID)
ORDER BY session_Id, ecid

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to list all dates between two dates

I made a calendar using:

http://social.technet.microsoft.com/wiki/contents/articles/22776.t-sql-calendar-table.aspx

then a Store procedure passing two dates and thats all:

USE DB_NAME;
GO

CREATE PROCEDURE [dbo].[USP_LISTAR_RANGO_FECHAS]
@FEC_INICIO date,
@FEC_FIN date
AS
Select Date from CALENDARIO where Date BETWEEN @FEC_INICIO AND @FEC_FIN;

hash function for string

There are a number of existing hashtable implementations for C, from the C standard library hcreate/hdestroy/hsearch, to those in the APR and glib, which also provide prebuilt hash functions. I'd highly recommend using those rather than inventing your own hashtable or hash function; they've been optimized heavily for common use-cases.

If your dataset is static, however, your best solution is probably to use a perfect hash. gperf will generate a perfect hash for you for a given dataset.

Mongoimport of json file

A bit late for probable answer, might help new people. In case you have multiple instances of database:

mongoimport --host <host_name>:<host_port> --db <database_name> --collection <collection_name>  --file <path_to_dump_file> -u <my_user> -p <my_pass>

Assuming credentials needed, otherwise remove this option.

Tomcat Server Error - Port 8080 already in use

The Way I solved this problem is , Install TCPview go to TCP view and check what ports is Tomcat utilizing there will be few other ports other than 8005,8009,8080 now go to Servers tab in eclipse double click on Tomcatv9.0 server and change port numbers there. This will solve the problem.

Create a directory if it does not exist and then create the files in that directory as well

If you create a web based application, the better solution is to check the directory exists or not then create the file if not exist. If exists, recreate again.

    private File createFile(String path, String fileName) throws IOException {
       ClassLoader classLoader = getClass().getClassLoader();
       File file = new File(classLoader.getResource(".").getFile() + path + fileName);

       // Lets create the directory
       try {
          file.getParentFile().mkdir();
       } catch (Exception err){
           System.out.println("ERROR (Directory Create)" + err.getMessage());
       }

       // Lets create the file if we have credential
       try {
           file.createNewFile();
       } catch (Exception err){
           System.out.println("ERROR (File Create)" + err.getMessage());
       }
       return  file;
   }

Show MySQL host via SQL Command

I think you try to get the remote host of the conneting user...

You can get a String like 'myuser@localhost' from the command:

SELECT USER()

You can split this result on the '@' sign, to get the parts:

-- delivers the "remote_host" e.g. "localhost" 
SELECT SUBSTRING_INDEX(USER(), '@', -1) 

-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)

if you are conneting via ip address you will get the ipadress instead of the hostname.

adb uninstall failed

Just run ADB and use the following command:

adb shell pm uninstall -k --user 0 <package name>

And you should get this return:

successful

How to know if two arrays have the same values

Why your code didn't work

JavaScript has primitive data types and non-primitive data types.

For primitive data types, == and === check whether the things on either side of the bars have the same value. That's why 1 === 1 is true.

For non-primitive data types like arrays, == and === check for reference equality. That is, they check whether arr1 and arr2 are the same object. In your example, the two arrays have the same objects in the same order, but are not equivalent.

Solutions

Two arrays, arr1 and arr2, have the same members if and only if:

  • Everything in arr2 is in arr1

AND

  • Everything in arr1 is in arr2

So this will do the trick (ES2016):

const containsAll = (arr1, arr2) => 
                arr2.every(arr2Item => arr1.includes(arr2Item))

const sameMembers = (arr1, arr2) => 
                        containsAll(arr1, arr2) && containsAll(arr2, arr1);

sameMembers(arr1, arr2); // `true`

This second solution using Underscore is closer to what you were trying to do:

arr1.sort();
arr2.sort();

_.isEqual(arr1, arr2); // `true`

It works because isEqual checks for "deep equality," meaning it looks at more than just reference equality and compares values.

A solution to your third question

You also asked how to find out which things in arr1 are not contained in arr2.

This will do it (ES2015):

const arr1 = [1, 2, 3, 4];
const arr2 = [3, 2, 1];

arr1.filter(arr1Item => !arr2.includes(arr1Item)); // `[4]`

You could also use Underscore's difference: method:

_.difference(arr1, arr2); // `[4]`

UPDATE

See @Redu's comment—my solution is for sameMembers, but what you may have in mind is sameMembersInOrder also-known-as deepEquals.

UPDATE 2

If you don't care about the order of the members of the arrays, ES2015+'s Set may be a better data structure than Array. See the MDN notes on how to implement isSuperset and difference using dangerous monkey-patching.

How to pass data between fragments

Fragment class A

public class CountryListFragment extends ListFragment{

    /** List of countries to be displayed in the ListFragment */

    ListFragmentItemClickListener ifaceItemClickListener;   

    /** An interface for defining the callback method */
    public interface ListFragmentItemClickListener {
    /** This method will be invoked when an item in the ListFragment is clicked */
    void onListFragmentItemClick(int position);
}   

/** A callback function, executed when this fragment is attached to an activity */  
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try{
        /** This statement ensures that the hosting activity implements ListFragmentItemClickListener */
        ifaceItemClickListener = (ListFragmentItemClickListener) activity;          
    }catch(Exception e){
        Toast.makeText(activity.getBaseContext(), "Exception",Toast.LENGTH_SHORT).show();
    }
}

Fragment Class B

public class CountryDetailsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    /** Inflating the layout country_details_fragment_layout to the view object v */
    View v = inflater.inflate(R.layout.country_details_fragment_layout, null);

    /** Getting the textview object of the layout to set the details */ 
    TextView tv = (TextView) v.findViewById(R.id.country_details);      

    /** Getting the bundle object passed from MainActivity ( in Landscape   mode )  or from 
     *  CountryDetailsActivity ( in Portrait Mode )  
     * */
    Bundle b = getArguments();

    /** Getting the clicked item's position and setting corresponding  details in the textview of the detailed fragment */
    tv.setText("Details of " + Country.name[b.getInt("position")]);     

    return v;
    }

}

Main Activity class for passing data between fragments

public class MainActivity extends Activity implements ListFragmentItemClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}


/** This method will be executed when the user clicks on an item in the listview */
@Override
public void onListFragmentItemClick(int position) {

    /** Getting the orientation ( Landscape or Portrait ) of the screen */
    int orientation = getResources().getConfiguration().orientation;


    /** Landscape Mode */
    if(orientation == Configuration.ORIENTATION_LANDSCAPE ){
        /** Getting the fragment manager for fragment related operations */
        FragmentManager fragmentManager = getFragmentManager();

        /** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        /** Getting the existing detailed fragment object, if it already exists. 
         *  The fragment object is retrieved by its tag name  *
         */
Fragment prevFrag = fragmentManager.findFragmentByTag("in.wptrafficanalyzer.country.details");

        /** Remove the existing detailed fragment object if it exists */
        if(prevFrag!=null)
    fragmentTransaction.remove(prevFrag);           

        /** Instantiating the fragment CountryDetailsFragment */
  CountryDetailsFragment fragment = new CountryDetailsFragment();

        /** Creating a bundle object to pass the data(the clicked item's   position) from the activity to the fragment */ 
        Bundle b = new Bundle();

        /** Setting the data to the bundle object */
        b.putInt("position", position);

        /** Setting the bundle object to the fragment */
        fragment.setArguments(b);           

        /** Adding the fragment to the fragment transaction */
        fragmentTransaction.add(R.id.detail_fragment_container,   fragment,"in.wptrafficanalyzer.country.details");

        /** Adding this transaction to backstack */
        fragmentTransaction.addToBackStack(null);

        /** Making this transaction in effect */
        fragmentTransaction.commit();

    }else{          /** Portrait Mode or Square mode */
        /** Creating an intent object to start the CountryDetailsActivity */
        Intent intent = new Intent("in.wptrafficanalyzer.CountryDetailsActivity");

        /** Setting data ( the clicked item's position ) to this intent */
        intent.putExtra("position", position);

        /** Starting the activity by passing the implicit intent */
        startActivity(intent);          
      }
    }
 }

Detailde acitivity class

public class CountryDetailsActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /** Setting the layout for this activity */
    setContentView(R.layout.country_details_activity_layout);

    /** Getting the fragment manager for fragment related operations */
    FragmentManager fragmentManager = getFragmentManager();

    /** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
    FragmentTransaction fragmentTransacton = fragmentManager.beginTransaction();

    /** Instantiating the fragment CountryDetailsFragment */
    CountryDetailsFragment detailsFragment = new CountryDetailsFragment();

    /** Creating a bundle object to pass the data(the clicked item's position) from the activity to the fragment */
    Bundle b = new Bundle();

    /** Setting the data to the bundle object from the Intent*/
    b.putInt("position", getIntent().getIntExtra("position", 0));

    /** Setting the bundle object to the fragment */
    detailsFragment.setArguments(b);

    /** Adding the fragment to the fragment transaction */
    fragmentTransacton.add(R.id.country_details_fragment_container, detailsFragment);       

    /** Making this transaction in effect */
    fragmentTransacton.commit();

    }
}

Array Of Contries

public class Country {

/** Array of countries used to display in CountryListFragment */
static String name[] = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan",
        "Bhutan"
};
}

For More Details visit this link [http://wptrafficanalyzer.in/blog/itemclick-handler-for-listfragment-in-android/]. There are full example ..

Detect when an image fails to load in Javascript

just like below:

var img = new Image(); 
img.src = imgUrl; 

if (!img.complete) {

//has picture
}
else //not{ 

}

AngularJS ng-if with multiple conditions

you can also try with && for mandatory constion if both condtion are true than work

//div ng-repeat="(k,v) in items"

<div ng-if="(k == 'a' &&  k == 'b')">
    <!-- SOME CONTENT -->
</div>

Adobe Reader Command Line Reference

To open a PDF at page 100 the follow works

<path to Adobe Reader> /A "page=100" "<Path To PDF file>"

If you require more than one argument separate them with &

I use the following in a batch file to open the book I'm reading to the page I was up to.

C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe /A "page=149&pagemode=none" "D:\books\MCTS(70-562) ASP.Net 3.5 Development.pdf"

The best list of command line args for Adobe Reader I have found is here.
http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf

It's for version 7 but all the arguments I tried worked.

As for closing the file, I think you will need to use the SDK, or if you are opening the file from code you could close the file from code once you have finished with it.

Remove duplicated rows

Here's a very simple, fast dplyr/tidy solution:

Remove rows that are entirely the same:

library(dplyr)
iris %>% 
  distinct(.keep_all = TRUE)

Remove rows that are the same only in certain columns:

iris %>% 
  distinct(Sepal.Length, Sepal.Width, .keep_all = TRUE)

How to remove a TFS Workspace Mapping?

I managed to remove the mapping using the /newowner command as suggested here:

How can I regain access to my Team Foundation Server Workspace?

The command opened an Edit Workspace windows where I removed the mapping. Afterwards I deleted the workspace I didn't need.

Array definition in XML?

As its name is "numbers" it is clear it is a list of number... So an array of number... no need of the attribute type... Although I like the principle of specifying the type of field in a type attribute...

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

command `< file`

will pass file contents to the command on stdin, but will strip newlines, meaning you couldn't iterate over each line individually. For that you could write a script with a 'for' loop:

for line in `cat input_file`; do some_command "$line"; done

Or (the multi-line variant):

for line in `cat input_file`
do
    some_command "$line"
done

Or (multi-line variant with $() instead of ``):

for line in $(cat input_file)
do
    some_command "$line"
done

References:

  1. For loop syntax: https://www.cyberciti.biz/faq/bash-for-loop/

I want to multiply two columns in a pandas DataFrame and add the result into a new column

If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:

In [22]: orders_df['C'] = orders_df.Action.apply(
               lambda x: (1 if x == 'Sell' else -1))

In [23]: orders_df   # New column C represents the sign of the transaction
Out[23]:
   Prices  Amount Action  C
0       3      57   Sell  1
1      89      42   Sell  1
2      45      70    Buy -1
3       6      43   Sell  1
4      60      47   Sell  1
5      19      16    Buy -1
6      56      89   Sell  1
7       3      28    Buy -1
8      56      69   Sell  1
9      90      49    Buy -1

Now we have eliminated the need for the if statement. Using DataFrame.apply(), we also do away with the for loop. As Hayden noted, vectorized operations are always faster.

In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C

In [25]: orders_df   # The resulting dataframe
Out[25]:
   Prices  Amount Action  C  Value
0       3      57   Sell  1    171
1      89      42   Sell  1   3738
2      45      70    Buy -1  -3150
3       6      43   Sell  1    258
4      60      47   Sell  1   2820
5      19      16    Buy -1   -304
6      56      89   Sell  1   4984
7       3      28    Buy -1    -84
8      56      69   Sell  1   3864
9      90      49    Buy -1  -4410

This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.

Can't find SDK folder inside Android studio path, and SDK manager not opening

If you have downloaded the AS + SDK bundle:

Assuming the defaults were left unchanged, you will find the SDK in C:\Users\%USERNAME%\AppData\Local\Android

If it is missing at this location, one of the following reasons apply: you have chosen a custom location, you missed to install the SDK at all, or (unlikely) they have changed the default install location.

Note #1: the AppData directory is hidden by default. If you have a standard Windows configuration, the C:\ path above should work "as is" (hit Win + R -> paste the path -> Enter).

Note #2: you will never find the SDK in the Android Studio directory unless you have explicitly put it in there. The reason is that those directories might be deleted after installing a newer version of Android Studio and you would have to re-install the SDK as well.

If you have retrieved the standalone SDK by some other means:

The SDK location may vary (from my experience), however (assuming the default configuration) you will most likely find it in C:\Program Files\Android or C:\Users\%USERNAME%

Automating running command on Linux from Windows using PuTTY

You can create a putty session, and auto load the script on the server, when starting the session:

putty -load "sessionName" 

At remote command, point to the remote script.

"End of script output before headers" error in Apache

So for everyone starting out with XAMPP cgi

change the extension from pl to cgi
change the permissions to 755

mv test.pl test.cgi
chmod 755 test.cgi

It fixed mine as well.

Unsupported major.minor version 52.0 when rendering in Android Studio

I also got the same error message of 'Unsupported major.minor version 52.0' when running ./gradlew makeJar to create a jar library by Android Studio 2.2.3.

After moving down the version of gradle plugin in build.gradle from 2.2.2 to 2.1.3, the error message disappeared and all worked well. classpath 'com.android.tools.build:gradle:2.1.3'

I don't know how the higer version of gradle plugin caused the error, but this did the trick for me. please let me know how this worked if you know the answer, thanks

Android: Access child views from a ListView

See: Android ListView: get data index of visible item and combine with part of Feet's answer above, can give you something like:

int wantedPosition = 10; // Whatever position you're looking for
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
  Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
  return;
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
View wantedView = listView.getChildAt(wantedChild);

The benefit is that you aren't iterating over the ListView's children, which could take a performance hit.

Eliminate extra separators below UITableView

You may find lots of answers to this question. Most of them around manipulation with UITableView's tableFooterView attribute and this is proper way to hide empty rows. For the conveniency I've created simple extension which allows to turn on/off empty rows from Interface Builder. You can check it out from this gist file. I hope it could save a little of your time.

extension UITableView {

  @IBInspectable
  var isEmptyRowsHidden: Bool {
        get {
          return tableFooterView != nil
        }
        set {
          if newValue {
              tableFooterView = UIView(frame: .zero)
          } else {
              tableFooterView = nil
          }
       }
    }
}

Usage:

tableView.isEmptyRowsHidden = true

enter image description here

How can I use ":" as an AWK field separator?

You have multiple ways to set : as the separator:

awk -F: '{print $1}'

awk -v FS=: '{print $1}'

awk '{print $1}' FS=:

awk 'BEGIN{FS=":"} {print $1}'

All of them are equivalent and will return 1 given a sample input "1:2:3":

$ awk -F: '{print $1}' <<< "1:2:3"
1
$ awk -v FS=: '{print $1}' <<< "1:2:3"
1
$ awk '{print $1}' FS=: <<< "1:2:3"
1
$ awk 'BEGIN{FS=":"} {print $1}' <<< "1:2:3"
1

Inner join with count() on three tables

One needs to understand what a JOIN or a series of JOINs does to a set of data. With strae's post, a pe_id of 1 joined with corresponding order and items on pe_id = 1 will give you the following data to "select" from:

[ table people portion ] [ table orders portion ] [ table items portion ]

| people.pe_id | people.pe_name | orders.ord_id | orders.pe_id | orders.ord_title | item.item_id | item.ord_id | item.pe_id | item.title |

| 1 | Foo | 1 | 1 | First order | 1 | 1 | 1 | Apple |
| 1 | Foo | 1 | 1 | First order | 2 | 1 | 1 | Pear |

The joins essentially come up with a cartesian product of all the tables. You basically have that data set to select from and that's why you need a distinct count on orders.ord_id and items.item_id. Otherwise both counts will result in 2 - because you effectively have 2 rows to select from.

How to convert an Instant to a date format?

If you want to convert an Instant to a Date:

Date myDate = Date.from(instant);

And then you can use SimpleDateFormat for the formatting part of your question:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);

Service Reference Error: Failed to generate code for the service reference

I have encountered this problem when upgrading a VS2010 WCF+Silverlight solution in VS2015 Professional. Besides automatically upgrading from Silverlight 4 to Silverlight 5, the service reference reuse checkbox value was changed and generation failed.

How do I filter an array with TypeScript in Angular 2?

You can check an example in Plunker over here plunker example filters

filter() {

    let storeId = 1;
    this.bookFilteredList = this.bookList
                                .filter((book: Book) => book.storeId === storeId);
    this.bookList = this.bookFilteredList; 
}

Generate random int value from 3 to 6

You can do this:

DECLARE @maxval TINYINT, @minval TINYINT
select @maxval=24,@minval=5

SELECT CAST(((@maxval + 1) - @minval) *
    RAND(CHECKSUM(NEWID())) + @minval AS TINYINT)

And that was taken directly from this link, I don't really know how to give proper credit for this answer.

Gson library in Android Studio

There is no need of adding JAR to your project by yourself, just add dependency in build.gradle (Module lavel). ALSO always try to use the upgraded version, as of now is

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

As every incremental version has some bugs fixes or up-gradations as mentioned here

Node.js Web Application examples/tutorials

I would suggest you check out the various tutorials that are coming out lately. My current fav is:

http://nodetuts.com/

Hope this helps.

How to round a number to n decimal places in Java

A succinct solution:

   public static double round(double value, int precision) {
      int scale = (int) Math.pow(10, precision);
      return (double) Math.round(value * scale) / scale;
  }

See also, https://stackoverflow.com/a/22186845/212950 Thanks to jpdymond for offering this.

How can my iphone app detect its own version number?

Read the info.plist file of your app and get the value for key CFBundleShortVersionString. Reading info.plist will give you an NSDictionary object

Convert milliseconds to date (in Excel)

Converting your value in milliseconds to days is simply (MsValue / 86,400,000)

We can get 1/1/1970 as numeric value by DATE(1970,1,1)

= (MsValueCellReference / 86400000) + DATE(1970,1,1)

Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss gives me a date and time of 19/04/2010 08:16:11

Remove quotes from a character vector in R

Here is one combining noquote and paste:

noquote(paste("Argument is of length zero",sQuote("!"),"and",dQuote("double")))


#[1] Argument is of length zero ‘!’ and “double”

How do I convert a numpy array to (and display) an image?

Supplement for doing so with matplotlib. I found it handy doing computer vision tasks. Let's say you got data with dtype = int32

from matplotlib import pyplot as plot
import numpy as np

fig = plot.figure()
ax = fig.add_subplot(1, 1, 1)
# make sure your data is in H W C, otherwise you can change it by
# data = data.transpose((_, _, _))
data = np.zeros((512,512,3), dtype=np.int32)
data[256,256] = [255,0,0]
ax.imshow(data.astype(np.uint8))

How can I install a local gem?

If you want to work on a locally modified fork of a gem, the best way to do so is

gem 'pry', path: './pry'

in a Gemfile.

... where ./pry would be the clone of your repository. Simply run bundle install once, and any changes in the gem sources you make are immediately reflected. With gem install pry/pry.gem, the sources are still moved into GEM_PATH and you'll always have to run both bundle gem pry and gem update to test.

How do I change the font size and color in an Excel Drop Down List?

I work on 60-70% zoom vue and my dropdown are unreadable so I made this simple code to overcome the issue

Note that I selected first all my dropdown lsts (CTRL+mouse click), went on formula tab, clicked "define name" and called them "ProduktSelection"

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim KeyCells As Range
Set KeyCells = Range("ProduktSelection")
    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

ActiveWindow.Zoom = 100

End If

End Sub

I then have another sub

Private Sub Worksheet_Change(ByVal Target As Range) 

where I come back to 65% when value is changed.

Print JSON parsed object?

The following code will display complete json data in alert box

var data= '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

json = JSON.parse(data);
window.alert(JSON.stringify(json));

Embedding a media player in a website using HTML

Definitely the HTML5 element is the way to go. There's at least basic support for it in the most recent versions of almost all browsers:

http://caniuse.com/#feat=audio

And it allows to specify what to do when the element is not supported by the browser. For example you could add a link to a file by doing:

<audio controls src="intro.mp3">
   <a href="intro.mp3">Introduction to HTML5 (10:12) - MP3 - 3.2MB</a>
</audio>

You can find this examples and more information about the audio element in the following link:

http://hacks.mozilla.org/2012/04/enhanceyourhtml5appwithaudio/

Finally, the good news are that mozilla's April's dev Derby is about this element so that's probably going to provide loads of great examples of how to make the most out of this element:

http://hacks.mozilla.org/2012/04/april-dev-derby-show-us-what-you-can-do-with-html5-audio/

database vs. flat files

What about a non-relational (NoSQL) database such as Amazon's SimpleDB, Tokio Cabinet, etc? I've heard that Google, Facebook, LinkedIn are using these to store their huge datasets.

Can you tell us if your data is structured, if your schema is fixed, if you need easy replicability, if access times are important, etc?

PHP how to get the base domain/url?

If you're using wordpress, use get_site_url:

get_site_url()

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

Using variables inside a bash heredoc

Don't use quotes with <<EOF:

var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF

Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).

CSS: Position loading indicator in the center of the screen

Here is a solution using an overlay that inhibits along with material design spinner that you configure one time in your app and you can call it from anywhere.

app.component.html

(put this somewhere at the root level of your html)

<div class="overlay" [style.height.px]="height" [style.width.px]="width" *ngIf="message.plzWait$ | async">
        <mat-spinner class="plzWait"  mode="indeterminate"></mat-spinner>
</div>

app.component.css

.plzWait{
  position: relative;
  left: calc(50% - 50px);
  top:50%;

}
.overlay{
  position: absolute;
  top:0px;
  left:0px;
  width: 100%;
  height: 100%;
  background: black;
  opacity: .5;
  z-index: 999999;
}

app.component.ts

height = 0;
width = 0;
constructor(
    private message: MessagingService
  }
ngOnInit() {
    this.height = document.body.clientHeight;
    this.width = document.body.clientWidth;
  }

messaging.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
    providedIn: 'root',
  })
export class MessagingService {
    // Observable string sources
  private plzWaitObservable = new Subject<boolean>();


  // Public Observables you subscribe to
  public plzWait$ = this.plzWaitObservable.asObservable();

  public plzWait = (wait: boolean) => this.plzWaitObservable.next(wait);
}

Some other component

constructor(private message: MessagingService) { }
somefunction() {
    this.message.plzWait(true);
    setTimeout(() => {
            this.message.plzWait(false);
    }, 5000);
}

how to set cursor style to pointer for links without hrefs

Give them all a common class (for instance link). Then add in css-file:

.link { cursor: pointer; }

Or as @mxmissile suggested, do it inline with style="cursor: pointer;"

DateTime to javascript date

I know this is a little late, but here's the solution I had to come up with for handling dates when you want to be timezone independent. Essentially it involves converting everything to UTC.

From Javascript to Server:

Send out dates as epoch values with the timezone offset removed.

var d = new Date(2015,0,1) // Jan 1, 2015
// Ajax Request to server ...
$.ajax({
  url: '/target',
  params: { date: d.getTime() - (d.getTimezoneOffset() * 60 * 1000) }
});

The server then recieves 1420070400000 as the date epoch.

On the Server side, convert that epoch value to a datetime object:

DateTime d = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(epoch);

At this point the date is just the date/time provided by the user as they provided it. Effectively it is UTC.

Going the other way:

When the server pulls data from the database, presumably in UTC, get the difference as an epoch (making sure that both date objects are either local or UTC):

long ms = (long)utcDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;

or

long ms = (long)localDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)).TotalMilliseconds;

When javascript receives this value, create a new date object. However, this date object is going to be assumed local time, so you need to offset it by the current timezone:

var epochValue = 1420070400000 // value pulled from server.
var utcDateVal = new Date(epochValue);
var actualDate = new Date(utcDateVal.getTime() + (utcDateVal.getTimezoneOffset() * 60 * 1000))

console.log(utcDateVal); // Wed Dec 31 2014 19:00:00 GMT-0500 (Eastern Standard Time)
console.log(actualDate); // Thu Jan 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)

As far as I know, this should work for any time zone where you need to display dates that are timezone independent.

Can I set text box to readonly when using Html.TextBoxFor?

Use the following:

 @Html.TextBoxFor(m => m.Whatever, new {@readonly = "readonly"})

If you want to assign a class to it you could do it the same way , by adding the @class = "" property. Hope this helps :)

How to give a time delay of less than one second in excel vba?

I have try this and it works for me:

Private Sub DelayMs(ms As Long)
    Debug.Print TimeValue(Now)
    Application.Wait (Now + (ms * 0.00000001))
    Debug.Print TimeValue(Now)
End Sub

Private Sub test()
    Call DelayMs (2000)  'test code with delay of 2 seconds, see debug window
End Sub

How to install JQ on Mac by command-line?

You can install any application/packages with brew on mac. If you want to know the exact command just search your package on https://brewinstall.org and you will get the set of commands needed to install that package.

First open terminal and install brew

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null

Now Install jq

brew install jq

How to set UICollectionViewCell Width and Height programmatically

If one is using storyboard and overriding UICollectionViewDelegateFlowLayout then in swift 5 and Xcode 11 also set Estimate size to None enter image description here