Programs & Examples On #Xom

XOM™ is a new XML object model. It is an open source (LGPL), tree-based API for processing XML with Java that strives for correctness, simplicity, and performance.

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

Best XML parser for Java

Here is a nice comparision on DOM, SAX, StAX & TrAX (Source: http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/SJSXP2.html )

Feature                  StAX                  SAX                      DOM                  TrAX

API Type                Pull,streaming     Push,streaming    In memory tree    XSLT Rule

Ease of Use          High                    Medium                 High                    Medium

XPath Capability   No                       No                        Yes                      Yes

CPU & Memory     Good                  Good                    Varies                  Varies

Forward Only        Yes                    Yes                        No                       No

Read XML              Yes                    Yes                        Yes                     Yes

Write XML              Yes                    No                          Yes                     Yes

CRUD                      No                      No                         Yes                     No

event.preventDefault() vs. return false

The main difference between return false and event.preventDefault() is that your code below return false will not be executed and in event.preventDefault() case your code will execute after this statement.

When you write return false it do the following things for you behind the scenes.

* Stops callback execution and returns immediately when called.
* event.stopPropagation();
* event.preventDefault();

How to dynamically create a class?

You want to look at CodeDOM. It allows defining code elements and compiling them. Quoting MSDN:

...This object graph can be rendered as source code using a CodeDOM code generator for a supported programming language. The CodeDOM can also be used to compile source code into a binary assembly.

How to scale down a range of numbers with a known min and max value

Based on Charles Clayton's response, I included some JSDoc, ES6 tweaks, and incorporated suggestions from the comments in the original response.

_x000D_
_x000D_
/**_x000D_
 * Returns a scaled number within its source bounds to the desired target bounds._x000D_
 * @param {number} n - Unscaled number_x000D_
 * @param {number} tMin - Minimum (target) bound to scale to_x000D_
 * @param {number} tMax - Maximum (target) bound to scale to_x000D_
 * @param {number} sMin - Minimum (source) bound to scale from_x000D_
 * @param {number} sMax - Maximum (source) bound to scale from_x000D_
 * @returns {number} The scaled number within the target bounds._x000D_
 */_x000D_
const scaleBetween = (n, tMin, tMax, sMin, sMax) => {_x000D_
  return (tMax - tMin) * (n - sMin) / (sMax - sMin) + tMin;_x000D_
}_x000D_
_x000D_
if (Array.prototype.scaleBetween === undefined) {_x000D_
  /**_x000D_
   * Returns a scaled array of numbers fit to the desired target bounds._x000D_
   * @param {number} tMin - Minimum (target) bound to scale to_x000D_
   * @param {number} tMax - Maximum (target) bound to scale to_x000D_
   * @returns {number} The scaled array._x000D_
   */_x000D_
  Array.prototype.scaleBetween = function(tMin, tMax) {_x000D_
    if (arguments.length === 1 || tMax === undefined) {_x000D_
      tMax = tMin; tMin = 0;_x000D_
    }_x000D_
    let sMax = Math.max(...this), sMin = Math.min(...this);_x000D_
    if (sMax - sMin == 0) return this.map(num => (tMin + tMax) / 2);_x000D_
    return this.map(num => (tMax - tMin) * (num - sMin) / (sMax - sMin) + tMin);_x000D_
  }_x000D_
}_x000D_
_x000D_
// ================================================================_x000D_
// Usage_x000D_
// ================================================================_x000D_
_x000D_
let nums = [10, 13, 25, 28, 43, 50], tMin = 0, tMax = 100,_x000D_
    sMin = Math.min(...nums), sMax = Math.max(...nums);_x000D_
_x000D_
// Result: [ 0.0, 7.50, 37.50, 45.00, 82.50, 100.00 ]_x000D_
console.log(nums.map(n => scaleBetween(n, tMin, tMax, sMin, sMax).toFixed(2)).join(', '));_x000D_
_x000D_
// Result: [ 0, 30.769, 69.231, 76.923, 100 ]_x000D_
console.log([-4, 0, 5, 6, 9].scaleBetween(0, 100).join(', '));_x000D_
_x000D_
// Result: [ 50, 50, 50 ]_x000D_
console.log([1, 1, 1].scaleBetween(0, 100).join(', '));
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
_x000D_
_x000D_

How can query string parameters be forwarded through a proxy_pass with nginx?

you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3

S3 Static Website Hosting Route All Paths to Index.html

adopted to your needs would be something like

location /service/ {
    rewrite ^\/service\/(.*) /$1 break;
    proxy_pass http://apache;
}

if you want to end up in http://127.0.0.1:8080/query/params/

if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like

location /service/ {
    rewrite ^\/(.*) /$1 break;
    proxy_pass http://apache;
}

How to clear the interpreter console?

The easiest way is to use os module

>>> import os
>>> clear = lambda: os.system('clear')
>>> clear()

Java JTable setting Column Width

No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.

table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);

Parse rfc3339 date strings in Python?

You should have a look at moment which is a python port of the excellent js lib momentjs.

One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

import moment
time_string='2012-10-09T19:00:55Z'

m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday

Result:

2012-10-09 19:10
2

How to make an array of arrays in Java

try

String[][] arrays = new String[5][];

std::string to float or double

You can use boost lexical cast:

#include <boost/lexical_cast.hpp>

string v("0.6");
double dd = boost::lexical_cast<double>(v);
cout << dd << endl;

Note: boost::lexical_cast throws exception so you should be prepared to deal with it when you pass invalid value, try passing string("xxx")

How to use a FolderBrowserDialog from a WPF application

The advantage of passing an owner handle is that the FolderBrowserDialog will not be modal to that window. This prevents the user from interacting with your main application window while the dialog is active.

How to call servlet through a JSP page

You can submit your jsp page to servlet. For this use <form> tag.

And to redirect use:

response.sendRedirect("servleturl")

Import python package from local directory into interpreter

A bit late to the party, but this is what worked for me:

>>> import sys
>>> sys.path.insert(0, '')

Apparently, if there is an empty string, Python knows that it should look in the current directory. I did not have the empty string in sys.path, which caused this error.

Passing parameters in rails redirect_to

If you are looking for a way to pass additional URL parameters (not controller, action, id, etc), here's a robust method for doing so:

object_path(@object, params: request.query_parameters)

That will pass along utm parameters or any other additional params you don't want to lose.

How to make <label> and <input> appear on the same line on an HTML form?

_x000D_
_x000D_
#form {_x000D_
    background-color: #FFF;_x000D_
    height: 600px;_x000D_
    width: 600px;_x000D_
    margin-right: auto;_x000D_
    margin-left: auto;_x000D_
    margin-top: 0px;_x000D_
    border-top-left-radius: 10px;_x000D_
    border-top-right-radius: 10px;_x000D_
    padding: 0px;_x000D_
    text-align:center;_x000D_
}_x000D_
label {_x000D_
    font-family: Georgia, "Times New Roman", Times, serif;_x000D_
    font-size: 18px;_x000D_
    color: #333;_x000D_
    height: 20px;_x000D_
    width: 200px;_x000D_
    margin-top: 10px;_x000D_
    margin-left: 10px;_x000D_
    text-align: right;_x000D_
    margin-right:15px;_x000D_
    float:left;_x000D_
}_x000D_
input {_x000D_
    height: 20px;_x000D_
    width: 300px;_x000D_
    border: 1px solid #000;_x000D_
    margin-top: 10px;_x000D_
}
_x000D_
<div id="form">_x000D_
    <form action="" method="post" name="registration" class="register">_x000D_
        <fieldset>_x000D_
            <div class="form-group">_x000D_
                <label for="Student">Name:</label>_x000D_
                <input name="Student" />_x000D_
            </div>_x000D_
            <div class="form-group">_x000D_
                <label for="Matric_no">Matric number:</label>_x000D_
                <input name="Matric_no" />_x000D_
            </div>_x000D_
            <div class="form-group">_x000D_
                <label for="Email">Email:</label>_x000D_
                <input name="Email" />_x000D_
            </div>_x000D_
            <div class="form-group">_x000D_
                <label for="Username">Username:</label>_x000D_
                <input name="Username" />_x000D_
            </div>_x000D_
            <div class="form-group">_x000D_
                <label for="Password">Password:</label>_x000D_
                <input name="Password" type="password" />_x000D_
            </div>_x000D_
            <input name="regbutton" type="button" class="button" value="Register" />_x000D_
        </fieldset>_x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Format Date/Time in XAML in Silverlight

You can use StringFormat in Silverlight 4 to provide a custom formatting of the value you bind to.

Dates

The date formatting has a huge range of options.

For the DateTime of “April 17, 2004, 1:52:45 PM”

You can either use a set of standard formats (standard formats)…

StringFormat=f : “Saturday, April 17, 2004 1:52 PM”
StringFormat=g : “4/17/2004 1:52 PM”
StringFormat=m : “April 17”
StringFormat=y : “April, 2004”
StringFormat=t : “1:52 PM”
StringFormat=u : “2004-04-17 13:52:45Z”
StringFormat=o : “2004-04-17T13:52:45.0000000”

… or you can create your own date formatting using letters (custom formats)

StringFormat=’MM/dd/yy’ : “04/17/04”
StringFormat=’MMMM dd, yyyy g’ : “April 17, 2004 A.D.”
StringFormat=’hh:mm:ss.fff tt’ : “01:52:45.000 PM”

Can a Byte[] Array be written to a file in C#?

Yep, why not?

fs.Write(myByteArray, 0, myByteArray.Length);

jQuery issue - #<an Object> has no method

This problem can also arise if you include jQuery more than once.

Break when a value changes using the Visual Studio debugger

Really old post but in case someone is unaware...

In Visual Studio 2015, you can place a breakpoint on the set accessor of an Auto-Implemented Property and the debugger will break when the property is updated

public bool IsUpdated
{
    get;
    set;    //set breakpoint on this line
}

Update

Alternatively; @AbdulRaufMujahid has pointed out in the comments that if the auto implemented property is on a single line, you can position your cursor at the get; or set; and hit F9 and a breakpoint will be placed accordingly. Nice!

public bool IsUpdated { get; set; }

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

os:Ubuntu18.04

mysql:5.7

  1. add the skip-grant-tables to the file end of mysqld.cnf

  2. cp the my.cnf

sudo cp /etc/mysql/mysql.conf.d/mysqld.cnf /etc/mysql/my.cnf
  1. reset the password
(base) ?  ~ sudo service mysql stop 
(base) ?  ~ sudo service mysql start
(base) ?  ~ mysql -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed, 3 warnings
mysql> update mysql.user set authentication_string=password('newpass') where user='root' and Host ='localhost';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> update user set plugin="mysql_native_password"; 
Query OK, 0 rows affected (0.00 sec)
Rows matched: 4  Changed: 0  Warnings: 0

mysql>  flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye
  1. remove theskip-grant-tables from my.cnf
(base) ?  ~ sudo emacs /etc/mysql/mysql.conf.d/mysqld.cnf 
(base) ?  ~ sudo emacs /etc/mysql/my.cnf                 
(base) ?  ~ sudo service mysql restart

  1. open the mysql
(base) ?  ~ mysql -uroot -ppassword 
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 
  1. check the password policy
mysql> select @@validate_password_policy;
+----------------------------+
| @@validate_password_policy |
+----------------------------+
| MEDIUM                     |
+----------------------------+
1 row in set (0.00 sec)


mysql> SHOW VARIABLES LIKE 'validate_password%';
+--------------------------------------+--------+
| Variable_name                        | Value  |
+--------------------------------------+--------+
| validate_password_dictionary_file    |        |
| validate_password_length             | 8      |
| validate_password_mixed_case_count   | 1      |
| validate_password_number_count       | 1      |
| validate_password_policy             | MEDIUM |
| validate_password_special_char_count | 1      |
+--------------------------------------+--------+
6 rows in set (0.08 sec)!
  1. change the config of the validate_password
mysql> set global validate_password_policy=0;
Query OK, 0 rows affected (0.05 sec)

mysql> set global validate_password_mixed_case_count=0;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_number_count=3;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_special_char_count=0;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_length=3;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE 'validate_password%';
+--------------------------------------+-------+
| Variable_name                        | Value |
+--------------------------------------+-------+
| validate_password_dictionary_file    |       |
| validate_password_length             | 3     |
| validate_password_mixed_case_count   | 0     |
| validate_password_number_count       | 3     |
| validate_password_policy             | LOW   |
| validate_password_special_char_count | 0     |
+--------------------------------------+-------+
6 rows in set (0.00 sec)

note you should know that you error caused by what? validate_password_policy?

you should decided to reset the your password to fill the policy or change the policy.

Classes vs. Functions

It depends on the scenario. If you only want to compute the age of a person, then use a function since you want to implement a single specific behaviour.

But if you want to create an object, that contains the date of birth of a person (and possibly other data), allows to modify it, then computing the age could be one of many operations related to the person and it would be sensible to use a class instead.

Classes provide a way to merge together some data and related operations. If you have only one operation on the data then using a function and passing the data as argument you will obtain an equivalent behaviour, with less complex code.

Note that a class of the kind:

class A(object):
    def __init__(self, ...):
        #initialize
    def a_single_method(self, ...):
        #do stuff

isn't really a class, it is only a (complicated)function. A legitimate class should always have at least two methods(without counting __init__).

MySQL, create a simple function

this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)

DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
  DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
  */
  DECLARE NAME_FOUND VARCHAR DEFAULT "";

    SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
  RETURN NAME_FOUND;
END;//

Android Location Providers - GPS or Network Provider?

GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.

A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.

http://developer.android.com/guide/topics/location/obtaining-user-location.html

Creating a dictionary from a CSV file

I'd suggest adding if rows in case there is an empty line at the end of the file

import csv
with open('coors.csv', mode='r') as infile:
    reader = csv.reader(infile)
    with open('coors_new.csv', mode='w') as outfile:
        writer = csv.writer(outfile)
        mydict = dict(row[:2] for row in reader if row)

How to assert greater than using JUnit Assert?

When using JUnit asserts, I always make the message nice and clear. It saves huge amounts of time debugging. Doing it this way avoids having to add a added dependency on hamcrest Matchers.

previousTokenValues[1] = "1378994409108";
currentTokenValues[1] = "1378994416509";

Long prev = Long.parseLong(previousTokenValues[1]);
Long curr = Long.parseLong(currentTokenValues[1]);
assertTrue("Previous (" + prev + ") should be greater than current (" + curr + ")", prev > curr);

Loading cross-domain endpoint with AJAX

To get the data form external site by passing using a local proxy as suggested by jherax you can create a php page that fetches the content for you from respective external url and than send a get request to that php page.

var req = new XMLHttpRequest();
req.open('GET', 'http://localhost/get_url_content.php',false);
if(req.status == 200) {
   alert(req.responseText);
}

as a php proxy you can use https://github.com/cowboy/php-simple-proxy

How to Set a Custom Font in the ActionBar Title?

I agree that this isn't completely supported, but here's what I did. You can use a custom view for your action bar (it will display between your icon and your action items). I'm using a custom view and I have the native title disabled. All of my activities inherit from a single activity, which has this code in onCreate:

this.getActionBar().setDisplayShowCustomEnabled(true);
this.getActionBar().setDisplayShowTitleEnabled(false);

LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.titleview, null);

//if you need to customize anything else about the text, do it here.
//I'm using a custom TextView with a custom font in my layout xml so all I need to do is set title
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());

//assign the view to the actionbar
this.getActionBar().setCustomView(v);

And my layout xml (R.layout.titleview in the code above) looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

<com.your.package.CustomTextView
        android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:textSize="20dp"
            android:maxLines="1"
            android:ellipsize="end"
            android:text="" />
</RelativeLayout>

How do I get logs from all pods of a Kubernetes replication controller?

I use this command.

kubectl -n <namespace> logs -f deployment/<app-name> --all-containers=true --since=10m

CocoaPods Errors on Project Build

So it seems that CocoaPods didn't set the Configurations for my Project. They need to be based on the Pods.xcconfig which is found in the Pods/Target Support Files/Pods. To get this to work I had to do the following:

  1. Drag this file into my Xcode Project in Xcode, choosing not to copy.
  2. Now there is a reference in our project, we can set the configurations: enter image description here

I then had another build error which may or may not have been related. The path to the shell script defined in the Copy Pods Resources was incorrect.

"${SRCROOT}/Pods/Pods-resources.sh"

Resolved incorrectly. It seemed that SRCROOT was adding an extra dir that didn't exist into the path. So I hard coded the path to the Project folder.

This allowed me to build.

Why is it that so many things that are supposed to save you time end up eating it up?

Note: Please see @abood's answer for explanation.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

How to save to local storage using Flutter?

You can use Localstorage

1- Add dependency to pubspec.yaml (Change the version based on the last)

dependencies:
  ...
  localstorage: ^3.0.0

2- Then run the following command

flutter packages get

3- import the localstorage :

import 'package:localstorage/localstorage.dart';

4- create an instance

class MainApp extends StatelessWidget {
  final LocalStorage storage = new LocalStorage('localstorage_app');
  ...
}

Add item to lcoalstorage :

void addItemsToLocalStorage() {
  storage.setItem('name', 'Abolfazl');
  storage.setItem('family', 'Roshanzamir');

  final info = json.encode({'name': 'Darush', 'family': 'Roshanzami'});
  storage.setItem('info', info);
}

Get an item from lcoalstorage:

void getitemFromLocalStorage() {
  final name = storage.getItem('name'); // Abolfazl
  final family = storage.getItem('family'); // Roshanzamir
  
  Map<String, dynamic> info = json.decode(storage.getItem('info'));
  final info_name=info['name'];
  final info_family=info['family'];
}

Delete an item from localstorage :

void removeItemFromLocalStorage() {
  storage.deleteItem('name');
  storage.deleteItem('family');
  storage.deleteItem('info');
}

Sending email with gmail smtp with codeigniter email library

According to the CI docs (CodeIgniter Email Library)...

If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create a new file called the email.php, add the $config array in that file. Then save the file at config/email.php and it will be used automatically. You will NOT need to use the $this->email->initialize() function if you save your preferences in a config file.

I was able to get this to work by putting all the settings into application/config/email.php.

$config['useragent'] = 'CodeIgniter';
$config['protocol'] = 'smtp';
//$config['mailpath'] = '/usr/sbin/sendmail';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_user'] = '[email protected]';
$config['smtp_pass'] = 'YOURPASSWORDHERE';
$config['smtp_port'] = 465; 
$config['smtp_timeout'] = 5;
$config['wordwrap'] = TRUE;
$config['wrapchars'] = 76;
$config['mailtype'] = 'html';
$config['charset'] = 'utf-8';
$config['validate'] = FALSE;
$config['priority'] = 3;
$config['crlf'] = "\r\n";
$config['newline'] = "\r\n";
$config['bcc_batch_mode'] = FALSE;
$config['bcc_batch_size'] = 200;

Then, in one of the controller methods I have something like:

$this->load->library('email'); // Note: no $config param needed
$this->email->from('[email protected]', '[email protected]');
$this->email->to('[email protected]');
$this->email->subject('Test email from CI and Gmail');
$this->email->message('This is a test.');
$this->email->send();

Also, as Cerebro wrote, I had to uncomment out this line in my php.ini file and restart PHP:

extension=php_openssl.dll

TypeError: $ is not a function when calling jQuery function

Use

jQuery(document).

instead of

$(document).

or

Within the function, $ points to jQuery as you would expect

(function ($) {
   $(document).
}(jQuery));

Unable to load script from assets index.android.bundle on windows

In my case, I'd forgotten the Android Emulator wifi as disabled. To solve the issue, I just swiped down the notification bar to expand menu and to enable Wifi connection.

After activating Wifi connection, the problem has been resolved in my case.

How to create virtual column using MySQL SELECT?

You could use a CASE statement, like

SELECT name
       ,address
       ,CASE WHEN a < b THEN '1' 
             ELSE '2' END AS one_or_two
FROM ...

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

I must add :

I had the same problem, it was coming from the fact that my teammate had a different version of cordova, and commited plugins on the repo with his version.

For all cordova plugins, I had to :

cordova plugin rm <plugin-name> 
cordova plugin add <plugin-name>

And ask my teammate to update his cordova to match my version

php is null or empty?

No it's not a bug. Have a look at the Loose comparisons with == table (second table), which shows the result of comparing each value in the first column with the values in the other columns:

    TRUE    FALSE   1       0       -1      "1"     "0"     "-1"    NULL    array() "php"   ""

    [...]    

""  FALSE   TRUE    FALSE   TRUE    FALSE   FALSE   FALSE   FALSE   TRUE    FALSE   FALSE   TRUE

There you can see that an empty string "" compared with false, 0, NULL or "" will yield true.

You might want to use is_null [docs] instead, or strict comparison (third table).

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

For my case, it was my code calling System.exit(0).

Here is the extract about it from te documentation:

Surefire does not support tests or any referenced libraries calling System.exit() at any time. If they do so, they are incompatible with Surefire and you should probably file an issue with the library/vendor.

Predefined type 'System.ValueTuple´2´ is not defined or imported

It's part of the .NET Framework 4.7.

As long as you don't target the above framework or higher (or .NET Core 2.0 / .NET Standard 2.0), you'll need to reference ValueTuple. Do this by adding the System.ValueTuple NuGet Package

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

Ended up writing something of my own based on UUID.java implementation. Note that I'm not generating a UUID, instead just a random 32 bytes hex string in the most efficient way I could think of.

Implementation

import java.security.SecureRandom;
import java.util.UUID;

public class RandomUtil {
    // Maxim: Copied from UUID implementation :)
    private static volatile SecureRandom numberGenerator = null;
    private static final long MSB = 0x8000000000000000L;

    public static String unique() {
        SecureRandom ng = numberGenerator;
        if (ng == null) {
            numberGenerator = ng = new SecureRandom();
        }

        return Long.toHexString(MSB | ng.nextLong()) + Long.toHexString(MSB | ng.nextLong());
    }       
}

Usage

RandomUtil.unique()

Tests

Some of the inputs I've tested to make sure it's working:

public static void main(String[] args) {
    System.out.println(UUID.randomUUID().toString());
    System.out.println(RandomUtil.unique());

    System.out.println();
    System.out.println(Long.toHexString(0x8000000000000000L |21));
    System.out.println(Long.toBinaryString(0x8000000000000000L |21));
    System.out.println(Long.toHexString(Long.MAX_VALUE + 1));
}

How do I create a random alpha-numeric string in C++?

I just tested this, it works sweet and doesn't require a lookup table. rand_alnum() sort of forces out alphanumerics but because it selects 62 out of a possible 256 chars it isn't a big deal.

#include <cstdlib>   // for rand()
#include <cctype>    // for isalnum()   
#include <algorithm> // for back_inserter
#include <string>

char 
rand_alnum()
{
    char c;
    while (!std::isalnum(c = static_cast<char>(std::rand())))
        ;
    return c;
}


std::string 
rand_alnum_str (std::string::size_type sz)
{
    std::string s;
    s.reserve  (sz);
    generate_n (std::back_inserter(s), sz, rand_alnum);
    return s;
}

How do I show running processes in Oracle DB?

After looking at sp_who, Oracle does not have that ability per se. Oracle has at least 8 processes running which run the db. Like RMON etc.

You can ask the DB which queries are running as that just a table query. Look at the V$ tables.

Quick Example:

SELECT sid,
       opname,
       sofar,
       totalwork,
       units,
       elapsed_seconds,
       time_remaining
FROM v$session_longops
WHERE sofar != totalwork;

How do I set the selected item in a drop down box

Check this:

<select class="form-control" id="department" name="department" type="text">
    <option value="medical-furniture" @if($list->department == "medical-furniture") selected @endif>Medical furniture</option>
    <option value="medical-table" @if($list->department == "medical-table") selected @endif>Medical table</option>
    <option value="service" @if($list->department == "service") selected @endif>Service</option>
</select>

C++ compiling on Windows and Linux: ifdef switch

No, these defines are compiler dependent. What you can do, use your own set of defines, and set them on the Makefile. See this thread for more info.

how to sort an ArrayList in ascending order using Collections and Comparator

Just throwing this out there...Can't you just do:

Collections.sort(myarrayList);

It's been awhile though...

Best GUI designer for eclipse?

well check out the eclipse distro easyeclipse at EasyEclipse. it has Visual editor project already added as a plugin, so no hassles of eclipse version compatibility.Plus the eclipse help section has a tutorial on VE.

How to list installed packages from a given repo using yum

On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:

yumdb search from_repo repoid

(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:

http://james.fedorapeople.org/yum/commands/find-repos-of-install.py

As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?

How to create a simple http proxy in node.js?

Your code doesn't work for binary files because they can't be cast to strings in the data event handler. If you need to manipulate binary files you'll need to use a buffer. Sorry, I do not have an example of using a buffer because in my case I needed to manipulate HTML files. I just check the content type and then for text/html files update them as needed:

app.get('/*', function(clientRequest, clientResponse) {
  var options = { 
    hostname: 'google.com',
    port: 80, 
    path: clientRequest.url,
    method: 'GET'
  };  

  var googleRequest = http.request(options, function(googleResponse) { 
    var body = ''; 

    if (String(googleResponse.headers['content-type']).indexOf('text/html') !== -1) {
      googleResponse.on('data', function(chunk) {
        body += chunk;
      }); 

      googleResponse.on('end', function() {
        // Make changes to HTML files when they're done being read.
        body = body.replace(/google.com/gi, host + ':' + port);
        body = body.replace(
          /<\/body>/, 
          '<script src="http://localhost:3000/new-script.js" type="text/javascript"></script></body>'
        );

        clientResponse.writeHead(googleResponse.statusCode, googleResponse.headers);
        clientResponse.end(body);
      }); 
    }   
    else {
      googleResponse.pipe(clientResponse, {
        end: true
      }); 
    }   
  }); 

  googleRequest.end();
});    

Receiving login prompt using integrated windows authentication

I tried the above IIS configuration tricks and loopback registry hack, and I reviewed and recreated app pool permissions and a dozen other things and still wasn't able to get rid of the authentication loop running on my development workstation with IIS Express or IIS 7.5, from a local or remote browsing session. I received four 401.2 status responses and a blank page. The exact same site deployed to my IIS 8.5 staging server works flawlessly.

Finally I noticed markup in the Response Body that was rendered blank by the browser contained the default page for a successful log in. I determined that Custom Error handling for ASP.NET and HTTP for the 401 error was preventing/interfering with Windows Authentication my workstation but not the staging server. I spent several hours fiddling with this, but as soon as I removed custom handling for just the 401 error, the workstation was back to normal. I present this as yet one another way to shoot your own foot.

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

Create PDF from a list of images

Some changes to make a pdf from the dir where the files are

I take the code and made some slight change to make it useable as it is.

from fpdf import FPDF
from PIL import Image
import os # I added this and the code at the end

def makePdf(pdfFileName, listPages, dir=''):
    if (dir):
        dir += "/"

    cover = Image.open(dir + str(listPages[0]))
    width, height = cover.size

    pdf = FPDF(unit="pt", format=[width, height])

    for page in listPages:
        pdf.add_page()
        pdf.image(dir + str(page), 0, 0)

    pdf.output(dir + pdfFileName + ".pdf", "F")


# this is what I added
x = [f for f in os.listdir() if f.endswith(".jpg")]
y = len(x)

makePdf("file", x)

How can I get a side-by-side diff when I do "git diff"?

For unix, combining just git and the built-in diff:

git show HEAD:path/to/file | diff -y - path/to/file

Of course, you can replace HEAD with any other git reference, and you probably want to add something like -W 170 to the diff command.

This assumes that you are just comparing your directory contents with a past commit. Comparing between two commits is more complex. If your shell is bash you can use "process substitution":

diff -y -W 170 <(git show REF1:path/to/file) <(git show REF2:path/to/file)

where REF1 and REF2 are git references – tags, branches or hashes.

AngularJS multiple filter with custom filter function

Hope below answer in this link will help, Multiple Value Filter

And take a look into the fiddle with example

arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}

fiddle

Git Clone from GitHub over https with two-factor authentication

If your repo have 2FA enabled. Highly suggest to use the app provided by github.com Here is the link: https://desktop.github.com/

After you downloaded it and installed it. Follow the withard, the app will ask you to provide the one time password for login. Once you filled in the one time password, you could see your repo/projects now.

How to modify list entries during for loop?

Modifying each element while iterating a list is fine, as long as you do not change add/remove elements to list.

You can use list comprehension:

l = ['a', ' list', 'of ', ' string ']
l = [item.strip() for item in l]

or just do the C-style for loop:

for index, item in enumerate(l):
    l[index] = item.strip()

Floating point exception

It's caused by n % x where x = 0 in the first loop iteration. You can't calculate a modulus with respect to 0.

Highcharts - redraw() vs. new Highcharts.chart

chart.series[0].setData(data,true);

The setData method itself will call the redraw method

'xmlParseEntityRef: no name' warnings while loading xml into a php file

Try to clean the HTML first using this function:

$html = htmlspecialchars($html);

Special chars are usually represented differently in HTML and it might be confusing for the compiler. Like & becomes &amp;.

Explicit vs implicit SQL joins

Basically, the difference between the two is that one is written in the old way, while the other is written in the modern way. Personally, I prefer the modern script using the inner, left, outer, right definitions because they are more explanatory and makes the code more readable.

When dealing with inner joins there is no real difference in readability neither, however, it may get complicated when dealing with left and right joins as in the older method you would get something like this:

SELECT * 
FROM table a, table b
WHERE a.id = b.id (+);

The above is the old way how a left join is written as opposed to the following:

SELECT * 
FROM table a 
LEFT JOIN table b ON a.id = b.id;

As you can visually see, the modern way of how the script is written makes the query more readable. (By the way same goes for right joins and a little more complicated for outer joins).

Going back to the boiler plate, it doesn't make a difference to the SQL compiler how the query is written as it handles them in the same way. I've seen a mix of both in Oracle databases which have had many people writing into it, both elder and younger ones. Again, it boils down to how readable the script is and the team you are developing with.

Regular Expression - 2 letters and 2 numbers in C#

You're missing an ending anchor.

if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}\z")) {
    // ...
}

Here's a demo.


EDIT: If you can have anything between an initial 2 letters and a final 2 numbers:

if(Regex.IsMatch(myString, @"^[A-Za-z]{2}.*\d{2}\z")) {
    // ...
}

Here's a demo.

Granting Rights on Stored Procedure to another user of Oracle

You can't do what I think you're asking to do.

The only privileges you can grant on procedures are EXECUTE and DEBUG.

If you want to allow user B to create a procedure in user A schema, then user B must have the CREATE ANY PROCEDURE privilege. ALTER ANY PROCEDURE and DROP ANY PROCEDURE are the other applicable privileges required to alter or drop user A procedures for user B. All are wide ranging privileges, as it doesn't restrict user B to any particular schema. User B should be highly trusted if granted these privileges.

EDIT:

As Justin mentioned, the way to give execution rights to A for a procedure owned by B:

GRANT EXECUTE ON b.procedure_name TO a;

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

After working on this for several hours what worked for me was go to /etc/mysql/ and edit the my.cnf file. Add the following

[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock

What is the Windows version of cron?

In addition to Windows Task Scheduler you also have 'at' on Windows. I'm not sure how it differs from Task Scheduler besides the fact that it has a command line interface.

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

Is there a developers api for craigslist.org

The closest I have been able to find is called 3taps. 3taps was sued by Craigslist with the result that "access to public data on a public website can be selectively censored by blacklisting certain viewers (i.e. competitors)", and thus states that "3taps will therefore access the very same data exclusively from public sources that retain open and equal access rights to public data".

Spring MVC: Complex object as GET @RequestParam

You can absolutely do that, just remove the @RequestParam annotation, Spring will cleanly bind your request parameters to your class instance:

public @ResponseBody List<MyObject> myAction(
    @RequestParam(value = "page", required = false) int page,
    MyObject myObject)

Including a groovy script in another groovy

How about treat the external script as a Java class? Based on this article: https://www.jmdawson.net/blog/2014/08/18/using-functions-from-one-groovy-script-in-another/

getThing.groovy The external script

def getThingList() {
    return ["thing","thin2","thing3"]
}

printThing.groovy The main script

thing = new getThing()  // new the class which represents the external script
println thing.getThingList()

Result

$ groovy printThing.groovy
[thing, thin2, thing3]

Table 'performance_schema.session_variables' doesn't exist

As sixty4bit question, if your mysql root user looks to be misconfigured, try to install the configurator extension from mysql official source:

https://dev.mysql.com/downloads/repo/apt/

It will help you to set up a new root user password.

Make sure to update your repository (debian/ubuntu) :

apt-get update

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

The iPhone 6+ renders internally using @3x assets at a virtual resolution of 2208×1242 (with 736x414 points), then samples that down for display. The same as using a scaled resolution on a Retina MacBook — it lets them hit an integral multiple for pixel assets while still having e.g. 12 pt text look the same size on the screen.

So, yes, the launch screens need to be that size.

The maths:

The 6, the 5s, the 5, the 4s and the 4 are all 326 pixels per inch, and use @2x assets to stick to the approximately 160 points per inch of all previous devices.

The 6+ is 401 pixels per inch. So it'd hypothetically need roughly @2.46x assets. Instead Apple uses @3x assets and scales the complete output down to about 84% of its natural size.

In practice Apple has decided to go with more like 87%, turning the 1080 into 1242. No doubt that was to find something as close as possible to 84% that still produced integral sizes in both directions — 1242/1080 = 2208/1920 exactly, whereas if you'd turned the 1080 into, say, 1286, you'd somehow need to render 2286.22 pixels vertically to scale well.

Count the frequency that a value occurs in a dataframe column

If your DataFrame has values with the same type, you can also set return_counts=True in numpy.unique().

index, counts = np.unique(df.values,return_counts=True)

np.bincount() could be faster if your values are integers.

How to get response status code from jQuery.ajax?

Came across this old thread searching for a similar solution myself and found the accepted answer to be using .complete() method of jquery ajax. I quote the notice on jquery website here:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

To know the status code of a ajax response, one can use the following code:

$.ajax( url [, settings ] )
.always(function (jqXHR) {
    console.log(jqXHR.status);
});

Works similarily for .done() and .fail()

React.js, wait for setState to finish before triggering a function?

       this.setState(
        {
            originId: input.originId,
            destinationId: input.destinationId,
            radius: input.radius,
            search: input.search
        },
        function() { console.log("setState completed", this.state) }
       )

this might be helpful

How to create a popup windows in javafx

Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.

ASP.NET MVC JsonResult Date Format

Not the most elegant way but this worked for me:

var ms = date.substring(6, date.length - 2);
var newDate = formatDate(ms);


function formatDate(ms) {

    var date = new Date(parseInt(ms));
    var hour = date.getHours();
    var mins = date.getMinutes() + '';
    var time = "AM";

    // find time 
    if (hour >= 12) {
        time = "PM";
    }
    // fix hours format
    if (hour > 12) {
        hour -= 12;
    }
    else if (hour == 0) {
        hour = 12;
    }
    // fix minutes format
    if (mins.length == 1) {
        mins = "0" + mins;
    }
    // return formatted date time string
    return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + hour + ":" + mins + " " + time;
}

How to put spacing between floating divs?

A litte late answer.

If you want to use a grid like this, you should have a look at Bootstrap, It's relatively easy to install, and it gives you exactly what you are looking for, all wrapped in nice and simple html/css + it works easily for making websites responsive.

What is the difference between Step Into and Step Over in a debugger

When debugging lines of code, here are the usual scenarios:

  • (Step Into) A method is about to be invoked, and you want to debug into the code of that method, so the next step is to go into that method and continue debugging step-by-step.
  • (Step Over) A method is about to be invoked, but you're not interested in debugging this particular invocation, so you want the debugger to execute that method completely as one entire step.
  • (Step Return) You're done debugging this method step-by-step, and you just want the debugger to run the entire method until it returns as one entire step.
  • (Resume) You want the debugger to resume "normal" execution instead of step-by-step
  • (Line Breakpoint) You don't care how it got there, but if execution reaches a particular line of code, you want the debugger to temporarily pause execution there so you can decide what to do.

Eclipse has other advanced debugging features, but these are the basic fundamentals.

See also

DateTime and CultureInfo

Use CultureInfo class to change your culture info.

var dutchCultureInfo = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCultureInfo);

cannot open shared object file: No such file or directory

When working on a supercomputer, I received this error when I ran:

module load python/3.4.0
screen
python

To resolve the error, I simply needed to reload the module in the screen terminal:

module load python/3.4.0
python

How to uninstall with msiexec using product id guid without .msi file present

There's no reason for the {} command not to work. The semi-obvious questions are:

  1. You are sure that the product is actually installed! There's something in ARP/Programs&Features.

  2. The original install is in fact visible in the current context. It looks as if it might have been a per-user install, and if you are logged in as somebody else now then it won't know about it - you'd need to log in under the same account as the original install.

  3. If the \windows\installer directory was damaged the cached file would be missing, and that's used to do the uninstall.

Check whether a value exists in JSON object

iterate through the array and check its name value.

Vertical Align Center in Bootstrap 4

<div class="col-lg-5 col-sm-5 offset-1 d-flex">
            <div class="offer-txt justify-content-center align-self-center">
                <span class="inner-title">Our Offer</span>
                <h2 class="section-title">Today’s Special </h2>
                <p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly.</p>
            </div>
        </div>

enter image description here

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

Making an array of integers in iOS

If you want to use a NSArray, you need an Objective-C class to put in it - hence the NSNumber requirement.

That said, Obj-C is still C, so you can use regular C arrays and hold regular ints instead of NSNumbers if you need to.

not-null property references a null or transient value

Check the unsaved values for your primary key/Object ID in your hbm files. If you have automated ID creation by hibernate framework and you are setting the ID somewhere it will throw this error.By default the unsaved value is 0, so if you set the ID to 0 you will see this error.

find vs find_by vs where

Suppose I have a model User

  1. User.find(id)

Returns a row where primary key = id. The return type will be User object.

  1. User.find_by(email:"[email protected]")

Returns first row with matching attribute or email in this case. Return type will be User object again.

Note :- User.find_by(email: "[email protected]") is similar to User.find_by_email("[email protected]")

  1. User.where(project_id:1)

Returns all users in users table where attribute matches.

Here return type will be ActiveRecord::Relation object. ActiveRecord::Relation class includes Ruby's Enumerable module so you can use it's object like an array and traverse on it.

SSH library for Java

I took miku's answer and jsch example code. I then had to download multiple files during the session and preserve original timestamps. This is my example code how to do it, probably many people find it usefull. Please ignore filenameHack() function its my own usecase.

package examples;

import com.jcraft.jsch.*;
import java.io.*;
import java.util.*;

public class ScpFrom2 {

    public static void main(String[] args) throws Exception {
        Map<String,String> params = parseParams(args);
        if (params.isEmpty()) {
            System.err.println("usage: java ScpFrom2 "
                    + " user=myid password=mypwd"
                    + " host=myhost.com port=22"
                    + " encoding=<ISO-8859-1,UTF-8,...>"
                    + " \"remotefile1=/some/file.png\""
                    + " \"localfile1=file.png\""
                    + " \"remotefile2=/other/file.txt\""
                    + " \"localfile2=file.txt\""

            );
            return;
        }

        // default values
        if (params.get("port") == null)
            params.put("port", "22");
        if (params.get("encoding") == null)
            params.put("encoding", "ISO-8859-1"); //"UTF-8"

        Session session = null;
        try {
            JSch jsch=new JSch();
            session=jsch.getSession(
                    params.get("user"),  // myuserid
                    params.get("host"),  // my.server.com
                    Integer.parseInt(params.get("port")) // 22
            );
            session.setPassword( params.get("password") );
            session.setConfig("StrictHostKeyChecking", "no"); // do not prompt for server signature

            session.connect();

            // this is exec command and string reply encoding
            String encoding = params.get("encoding");

            int fileIdx=0;
            while(true) {
                fileIdx++;

                String remoteFile = params.get("remotefile"+fileIdx);
                String localFile = params.get("localfile"+fileIdx);
                if (remoteFile == null || remoteFile.equals("")
                        || localFile == null || localFile.equals("") )
                    break;

                remoteFile = filenameHack(remoteFile);
                localFile  = filenameHack(localFile);

                try {
                    downloadFile(session, remoteFile, localFile, encoding);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        } catch(Exception ex) {
            ex.printStackTrace();
        } finally {
            try{ session.disconnect(); } catch(Exception ex){}
        }
    }

    private static void downloadFile(Session session, 
            String remoteFile, String localFile, String encoding) throws Exception {
        // send exec command: scp -p -f "/some/file.png"
        // -p = read file timestamps
        // -f = From remote to local
        String command = String.format("scp -p -f \"%s\"", remoteFile); 
        System.console().printf("send command: %s%n", command);
        Channel channel=session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command.getBytes(encoding));

        // get I/O streams for remote scp
        byte[] buf=new byte[32*1024];
        OutputStream out=channel.getOutputStream();
        InputStream in=channel.getInputStream();

        channel.connect();

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'

        // reply: T<mtime> 0 <atime> 0\n
        // times are in seconds, since 1970-01-01 00:00:00 UTC 
        int c=checkAck(in);
        if(c!='T')
            throw new IOException("Invalid timestamp reply from server");

        long tsModified = -1; // millis
        for(int idx=0; ; idx++){
            in.read(buf, idx, 1);
            if(tsModified < 0 && buf[idx]==' ') {
                tsModified = Long.parseLong(new String(buf, 0, idx))*1000;
            } else if(buf[idx]=='\n') {
                break;
            }
        }

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'

        // reply: C0644 <binary length> <filename>\n
        // length is given as a text "621873" bytes
        c=checkAck(in);
        if(c!='C')
            throw new IOException("Invalid filename reply from server");

        in.read(buf, 0, 5); // read '0644 ' bytes

        long filesize=-1;
        for(int idx=0; ; idx++){
            in.read(buf, idx, 1);
            if(buf[idx]==' ') {
                filesize = Long.parseLong(new String(buf, 0, idx));
                break;
            }
        }

        // read remote filename
        String origFilename=null;
        for(int idx=0; ; idx++){
            in.read(buf, idx, 1);
            if(buf[idx]=='\n') {
                origFilename=new String(buf, 0, idx, encoding); // UTF-8, ISO-8859-1
                break;
            }
        }

        System.console().printf("size=%d, modified=%d, filename=%s%n"
                , filesize, tsModified, origFilename);

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'

        // read binary data, write to local file
        FileOutputStream fos = null;
        try {
            File file = new File(localFile);
            fos = new FileOutputStream(file);
            while(filesize > 0) {
                int read = Math.min(buf.length, (int)filesize);
                read=in.read(buf, 0, read);
                if(read < 0)
                    throw new IOException("Reading data failed");

                fos.write(buf, 0, read);
                filesize -= read;
            }
            fos.close(); // we must close file before updating timestamp
            fos = null;
            if (tsModified > 0)
                file.setLastModified(tsModified);               
        } finally {
            try{ if (fos!=null) fos.close(); } catch(Exception ex){}
        }

        if(checkAck(in) != 0)
            return;

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'
        System.out.println("Binary data read");     
    }

    private static int checkAck(InputStream in) throws IOException {
        // b may be 0 for success
        //          1 for error,
        //          2 for fatal error,
        //          -1
        int b=in.read();
        if(b==0) return b;
        else if(b==-1) return b;
        if(b==1 || b==2) {
            StringBuilder sb=new StringBuilder();
            int c;
            do {
                c=in.read();
                sb.append((char)c);
            } while(c!='\n');
            throw new IOException(sb.toString());
        }
        return b;
    }


    /**
     * Parse key=value pairs to hashmap.
     * @param args
     * @return
     */
    private static Map<String,String> parseParams(String[] args) throws Exception {
        Map<String,String> params = new HashMap<String,String>();
        for(String keyval : args) {
            int idx = keyval.indexOf('=');
            params.put(
                    keyval.substring(0, idx),
                    keyval.substring(idx+1)
            );
        }
        return params;
    }

    private static String filenameHack(String filename) {
        // It's difficult reliably pass unicode input parameters 
        // from Java dos command line.
        // This dirty hack is my very own test use case. 
        if (filename.contains("${filename1}"))
            filename = filename.replace("${filename1}", "Korilla ABC ÅÄÖ.txt");
        else if (filename.contains("${filename2}"))
            filename = filename.replace("${filename2}", "test2 ABC ÅÄÖ.txt");           
        return filename;
    }

}

Deleting a file in VBA

An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be

With New FileSystemObject
    If .FileExists(yourFilePath) Then
        .DeleteFile yourFilepath
    End If
End With

Same effect but fewer (well, none at all) variable declarations.

The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).

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

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

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

How about Processing for JavaScript? I don't know Processing, but the code always seems rather small for what it can do, it's very visual, and you can run it in a browser.
http://processingjs.org/exhibition

Select elements by attribute

I have created npm package with intended behaviour as described above in question.

Link to [npm] and [github]

Usage is very simple. For example:

<p id="test" class="test">something</p>
$("#test").hasAttr("class")

returns true.

Works with camelcase too.

creating charts with angularjs

Did you try D3.js? Here is a good example.

jQuery text() and newlines

Alternatively, try using .html and then wrap with <pre> tags:

$(someElem).html('this\n has\n newlines').wrap('<pre />');

Get time in milliseconds using C#

Use System.DateTime.Now.ToUniversalTime(). That puts your reading in a known reference-based millisecond format that totally eliminates day change, etc.

Adding external library in Android studio

Try one of these approaches:

Approach 1)

1- Choose project view

enter image description here

2- Copy your JAR file in app -> lib folder

enter image description here

3- Right click on your JAR file and choose add as library

enter image description here enter image description here

4- Check it in build.gradle

enter image description here


Approach 2)

1- File -> New -> New Module

enter image description here

2- Import .JAR/.AAR Package

enter image description here

3- Browse your JAR File

enter image description here

4- Finish

5- File -> Project Structure -> Dependencies

enter image description here

6- You should click on + button and then click on Module Dependency

enter image description here

7- You will see your library here

enter image description here

8- choose your library and click ok

enter image description here

9- Then, you will see that your library is added.

enter image description here


For first two approaches, you need a JAR file. You can search http://search.maven.org/ to find JAR files that are related to Android. For example, this is the search result for jdom in this link

Search result for jdom


Approach 3) Android is using http://jcenter.bintray.com/ as remote library. For example, this is the search result for jdom in the link.

jcenter jdom

To add a library in this approach, please follow these steps:

1- File -> Project Structure -> Dependencies

enter image description here

2- Click on + button and choose library dependency

enter image description here enter image description here

3- find your library and select it, then click OK.


I hope it helps.

Need to perform Wildcard (*,?, etc) search on a string using Regex

You need to convert your wildcard expression to a regular expression. For example:

    private bool WildcardMatch(String s, String wildcard, bool case_sensitive)
    {
        // Replace the * with an .* and the ? with a dot. Put ^ at the
        // beginning and a $ at the end
        String pattern = "^" + Regex.Escape(wildcard).Replace(@"\*", ".*").Replace(@"\?", ".") + "$";

        // Now, run the Regex as you already know
        Regex regex;
        if(case_sensitive)
            regex = new Regex(pattern);
        else
            regex = new Regex(pattern, RegexOptions.IgnoreCase);

        return(regex.IsMatch(s));
    } 

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

How to move columns in a MySQL table?

I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.

SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';

SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"` 
`",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT 
NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ,"  AFTER 
`",@NeighboringColumn,"`;")
FROM information_schema.COLUMNS c, information_schema.TABLES t
WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
AND @NeighboringColumn IN (SELECT COLUMN_NAME 
    FROM information_schema.COLUMNS c2 
    WHERE c2.TABLE_NAME = t.TABLE_NAME);

How to create a file with a given size in Linux?

There are lots of answers, but none explained nicely what else can be done. Looking into man pages for dd, it is possible to better specify the size of a file.

This is going to create /tmp/zero_big_data_file.bin filled with zeros, that has size of 20 megabytes :

    dd if=/dev/zero of=/tmp/zero_big_data_file.bin  bs=1M count=20

This is going to create /tmp/zero_1000bytes_data_file.bin filled with zeros, that has size of 1000 bytes :

    dd if=/dev/zero of=/tmp/zero_1000bytes_data_file.bin  bs=1kB count=1

or

    dd if=/dev/zero of=/tmp/zero_1000bytes_data_file.bin  bs=1000 count=1

  • In all examples, bs is block size, and count is number of blocks
  • BLOCKS and BYTES may be followed by the following multiplicative suffixes: c =1, w =2, b =512, kB =1000, K =1024, MB =1000*1000, M =1024*1024, xM =M GB =1000*1000*1000, G =1024*1024*1024, and so on for T, P, E, Z, Y.

<hr> tag in Twitter Bootstrap not functioning correctly?

I think it would look better if we add border-color : transparent as per below:

<hr style="width: 100%; background-color: black; height: 1px; border-color : transparent;" />

If you don't put the border transparent it will be white and i don't think that is good all time.

How to count the NaN values in a column in pandas DataFrame

based to the answer that was given and some improvements this is my approach

def PercentageMissin(Dataset):
    """this function will return the percentage of missing values in a dataset """
    if isinstance(Dataset,pd.DataFrame):
        adict={} #a dictionary conatin keys columns names and values percentage of missin value in the columns
        for col in Dataset.columns:
            adict[col]=(np.count_nonzero(Dataset[col].isnull())*100)/len(Dataset[col])
        return pd.DataFrame(adict,index=['% of missing'],columns=adict.keys())
    else:
        raise TypeError("can only be used with panda dataframe")

Use multiple @font-face rules in CSS

Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.

/* Regular Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Regular.ttf");
}

/* SemiBold (600) Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-SemiBold.ttf");
    font-weight: 600;
}

/* Bold Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Bold.ttf");
    font-weight: bold;
}

Declared rules can be used by following

/* Regular */
font-family: Montserrat;


/* Semi Bold */
font-family: Montserrat;
font-weght: 600;

/* Bold */
font-family: Montserrat;
font-weight: bold;

HTML/CSS font color vs span style

<span style="color:#ffffff; font-size:18px; line-height:35px; font-family: Calibri;">Our Activities </span>

This works for me well:) As it has been already mentioned above "The font tag has been deprecated, at least in XHTML. It always safe to use span tag. font may not give you desire results, at least in my case it didn't.

Include CSS,javascript file in Yii Framework

Something like this:

<?php  
  $baseUrl = Yii::app()->baseUrl; 
  $cs = Yii::app()->getClientScript();
  $cs->registerScriptFile($baseUrl.'/js/yourscript.js');
  $cs->registerCssFile($baseUrl.'/css/yourcss.css');
?>

How do I set the figure title and axes labels font size in Matplotlib?

Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:

from matplotlib import pyplot as plt    

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')

For globally setting title and label sizes, mpl.rcParams contains axes.titlesize and axes.labelsize. (From the page):

axes.titlesize      : large   # fontsize of the axes title
axes.labelsize      : medium  # fontsize of the x any y labels

(As far as I can see, there is no way to set x and y label sizes separately.)

And I see that axes.titlesize does not affect suptitle. I guess, you need to set that manually.

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

Subtract days from a DateTime

The dateTime.AddDays(-1) does not subtract that one day from the dateTime reference. It will return a new instance, with that one day subtracted from the original reference.

DateTime dateTime = DateTime.Now;
DateTime otherDateTime = dateTime.AddDays(-1);

CMake does not find Visual C++ compiler

I got this problem with CMake 3.12.1, after an update of Visual Studio 2017. I simply re-ran CMake and it worked.

What is the maximum number of edges in a directed graph with n nodes?

If you have N nodes, there are N - 1 directed edges than can lead from it (going to every other node). Therefore, the maximum number of edges is N * (N - 1).

Github: Can I see the number of downloads for a repo?

GitHub has deprecated the download support and now supports 'Releases' - https://github.com/blog/1547-release-your-software. To create a release either use the GitHub UI or create an annotated tag (http:// git-scm.com/book/ch2-6.html) and add release notes to it in GitHub. You can then upload binaries, or 'assets', to each release.

Once you have some releases, the GitHub API supports getting information about them, and their assets.

curl -i \
https://api.github.com/repos/:owner/:repo/releases \
-H "Accept: application/vnd.github.manifold-preview+json"

Look for the 'download_count' entry. Theres more info at http://developer.github.com/v3/repos/releases/. This part of the API is still in the preview period ATM so it may change.

Update Nov 2013:

GitHub's releases API is now out of the preview period so the 'Accept' header is no longer needed - http://developer.github.com/changes/2013-11-04-releases-api-is-official/

It won't do any harm to continue to add the 'Accept' header though.

How to automatically insert a blank row after a group of data

Figured it out.

Step 1

Put a new column to the left of column1 and copy+paste the following formula

=B2=B3

=B3=B4

=B4=B5

... all the way to the bottom (assume column B here is column1 in the original question).

This formula evaluates whether or not the next row is a new value in column1. Deopending on the result, you will have TRUE or FALSE. Copy and Paste these results as values and then swap "FALSE" for nil and "TRUE" for 0.5

Step 2

Then add that column full of only 0.5's to the column1 which will yield the following table:

  newcolumn0  |   column1 ("B") |   column2   |  column3
-----------------------------------------------------
              |     1           |     small   |  blue
              |     1           |     small   |  orange
      1.5     |     1           |     small   |  yellow
              |     2           |     med     |  yellow
      2.5     |     2           |     med     |  blue
      3.5     |     3           |     large   |  green
              |     4           |     large   |  green
      4.5     |     4           |     small   |  pink

Step 3

Lastly, copy and paste the values from newcolumn0 right below the values in column1 and then sort the table by column1 and you should have a blank row in between each distinct whole number in column1, with the table something like this:

    newcolumn0   |  column1 ("B")  |   column2       |  column3
---------------------------------------------------------------
                 |     1           |     small   |  blue
                 |     1           |     small   |  orange
        1.5      |     1.5         |             |
                 |     1           |     small   |  yellow
                 |     2           |     med     |  yellow
                 |     2           |     med     |  blue
        2.5      |     2.5         |             |
                 |     3           |     large   |  green
        3.5      |     3.5         |             |
                 |     4           |     large   |  green
                 |     4           |     small   |  pink
        4.5      |     4.5         |             |

Alternative Solutions (still no VBA)

  1. Put a value of 1 Column 1, Row 2 (assume this is A2)
  2. Put this formula in A3 =IF(B3=B2,A2,A2+1) and copy+paste this formula for the rest of column 2
  3. Then copy and paste all the values from column 1 into a new temp excel sheet, remove duplicates, then add 0.5 to all numbers, then paste these values below the values in original spreadsheet below the data in column 1, paste all data in column as values and then sort by that column, delete the temp excel sheet

Simple DateTime sql query

You missed single quote sign:

SELECT * 
FROM TABLENAME 
WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM'

Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.

SELECT *
FROM TABLENAME 
WHERE 
    DateTime >= '2011-04-12T00:00:00.000' AND 
    DateTime <= '2011-05-25T03:53:04.000'

Running script upon login mac

Follow this:

  • start Automator.app
  • select Application
  • click Show library in the toolbar (if hidden)
  • add Run shell script (from the Actions/Utilities)
  • copy & paste your script into the window
  • test it
  • save somewhere (for example you can make an Applications folder in your HOME, you will get an your_name.app)

  • go to System Preferences -> Accounts -> Login items

  • add this app
  • test & done ;)

EDIT:

I've recently earned a "Good answer" badge for this answer. While my solution is simple and working, the cleanest way to run any program or shell script at login time is described in @trisweb's answer, unless, you want interactivity.

With automator solution you can do things like next: automator screenshot login application

so, asking to run a script or quit the app, asking passwords, running other automator workflows at login time, conditionally run applications at login time and so on...

Checking from shell script if a directory contains files

Works well for me this (when dir exist):

some_dir="/some/dir with whitespace & other characters/"
if find "`echo "$some_dir"`" -maxdepth 0 -empty | read v; then echo "Empty dir"; fi

With full check:

if [ -d "$some_dir" ]; then
  if find "`echo "$some_dir"`" -maxdepth 0 -empty | read v; then echo "Empty dir"; else "Dir is NOT empty" fi
fi

How to print strings with line breaks in java

Do this way:-

String newline = System.getProperty("line.separator");

private static final String mText = "SHOP MA" + newline +
        + "----------------------------" + newline +
        + "Pannampitiya" + newline +
        + "09-10-2012 harsha  no: 001" + newline +
        + "No  Item  Qty  Price  Amount" + newline +
        + "1 Bread 1 50.00  50.00" + newline +
        + "____________________________" + newline;

No suitable records were found verify your bundle identifier is correct

I have to manually sign the app. Created new certificate and new profile. Set code signing to Manual. Only then i was able to upload. Moreover select Manual sign in from organizer while uploading build.

enter image description here

Get Selected value of a Combobox

Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)

sub myhandler(eventsource)
  process(eventsource.value)
end sub

for each cell
  cell.setEventHandler(myHandler)

But i dont know the syntax for achieving this in VB/VBA, or if is even possible.

How can I find the length of a number?

I've been using this functionality in node.js, this is my fastest implementation so far:

var nLength = function(n) { 
    return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1; 
}

It should handle positive and negative integers (also in exponential form) and should return the length of integer part in floats.

The following reference should provide some insight into the method: Weisstein, Eric W. "Number Length." From MathWorld--A Wolfram Web Resource.

I believe that some bitwise operation can replace the Math.abs, but jsperf shows that Math.abs works just fine in the majority of js engines.

Update: As noted in the comments, this solution has some issues :(

Update2 (workaround) : I believe that at some point precision issues kick in and the Math.log(...)*0.434... just behaves unexpectedly. However, if Internet Explorer or Mobile devices are not your cup of tea, you can replace this operation with the Math.log10 function. In Node.js I wrote a quick basic test with the function nLength = (n) => 1 + Math.log10(Math.abs(n) + 1) | 0; and with Math.log10 it worked as expected. Please note that Math.log10 is not universally supported.

Right pad a string with variable number of spaces

Based on KMier's answer, addresses the comment that this method poses a problem when the field to be padded is not a field, but the outcome of a (possibly complicated) function; the entire function has to be repeated.

Also, this allows for padding a field to the maximum length of its contents.

WITH
cte AS (
  SELECT 'foo' AS value_to_be_padded
  UNION SELECT 'foobar'
),
cte_max AS (
  SELECT MAX(LEN(value_to_be_padded)) AS max_len
)
SELECT
  CONCAT(SPACE(max_len - LEN(value_to_be_padded)), value_to_be_padded AS left_padded,
  CONCAT(value_to_be_padded, SPACE(max_len - LEN(value_to_be_padded)) AS right_padded;

Using an authorization header with Fetch in React Native

It turns out, I was using the fetch method incorrectly.

fetch expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.

I was wrapping the intended object within a second object, which did not get me any desired result.

Here's how it looks on a high level:

fetch('API_ENDPOINT', OBJECT)  
  .then(function(res) {
    return res.json();
   })
  .then(function(resJson) {
    return resJson;
   })

I structured my object as such:

var obj = {  
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Origin': '',
    'Host': 'api.producthunt.com'
  },
  body: JSON.stringify({
    'client_id': '(API KEY)',
    'client_secret': '(API SECRET)',
    'grant_type': 'client_credentials'
  })

Match line break with regular expression

By default . (any character) does not match newline characters.

This means you can simply match zero or more of any character then append the end tag.

Find: <li><a href="#">.* Replace: $0</a>

Iterate over each line in a string in PHP

foreach(preg_split('~[\r\n]+~', $text) as $line){
    if(empty($line) or ctype_space($line)) continue; // skip only spaces
    // if(!strlen($line = trim($line))) continue; // or trim by force and skip empty
    // $line is trimmed and nice here so use it
}

^ this is how you break lines properly, cross-platform compatible with Regexp :)

Val and Var in Kotlin

var is a variable like any other language. eg.

var price: Double

On the other side, val provides you feature of referencing. eg.

val CONTINENTS = 7
// You refer this to get constant value 7. In this case, val acts as access
// specifier final in Java

and,

val Int.absolute: Int
    get() {
        return Math.abs(this)
    }
// You refer to the newly create 'method' which provides absolute value 
// of your integer

println(-5.absolute) // O.P: 5

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

Simple way to find if two different lists contain exactly the same elements?

list1.equals(list2);

If your list contains a custom Class MyClass, this class must override the equals function.

 class MyClass
  {
  int field=0;
  @0verride
  public boolean equals(Object other)
        {
        if(this==other) return true;
        if(other==null || !(other instanceof MyClass)) return false;
        return this.field== MyClass.class.cast(other).field;
        }
  }

Note :if you want to test equals on a java.util.Set rather than a java.util.List, then your object must override the hashCode function.

How to build minified and uncompressed bundle with webpack?

You can define two entry points in your webpack configuration, one for your normal js and the other one for minified js. Then you should output your bundle with its name, and configure UglifyJS plugin to include min.js files. See the example webpack configuration for more details:

module.exports = {
 entry: {
   'bundle': './src/index.js',
   'bundle.min': './src/index.js',
 },

 output: {
   path: path.resolve(__dirname, 'dist'),
   filename: "[name].js"
 },

 plugins: [
   new webpack.optimize.UglifyJsPlugin({
      include: /\.min\.js$/,
      minimize: true
   })
 ]
};

After running webpack, you will get bundle.js and bundle.min.js in your dist folder, no need for extra plugin.

How do I put an already-running process under nohup?

Unfortunately disown is specific to bash and not available in all shells.

Certain flavours of Unix (e.g. AIX and Solaris) have an option on the nohup command itself which can be applied to a running process:

nohup -p pid

See http://en.wikipedia.org/wiki/Nohup

Can't append <script> element

I wrote an npm package that lets you take an HTML string, including script tags and append it to a container while executing the scripts

Example:

import appendHtml from 'appendhtml';

const html = '<p>Hello</p><script src="some_js_file.js"></script>'; 
const container = document.getElementById('some-div');

await appendHtml(html, container);

// appendHtml returns a Promise, some_js_file.js is now loaded and executed (note the await)

Find it here: https://www.npmjs.com/package/appendhtml

How to set button click effect in Android?

just wanna add another easy way to do this: If your ImageButton remains its background and you don't set it to null, it will work like a normal button and will show the click animation while clicking exactly like other buttons.The way to hide the background while it is still there:

<ImageButton
    android:id="@+id/imageButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="1dp"
    android:paddingLeft="1dp"
    android:paddingRight="1dp"
    android:paddingTop="1dp"
    android:src="@drawable/squareicon" />

The paddings won't let the background be visible and make the button act like other buttons.

How does facebook, gmail send the real time notification?

Facebook uses MQTT instead of HTTP. Push is better than polling. Through HTTP we need to poll the server continuously but via MQTT server pushes the message to clients.

Comparision between MQTT and HTTP: http://www.youtube.com/watch?v=-KNPXPmx88E

Note: my answers best fits for mobile devices.

php form action php self

Leaving the action value blank will cause the form to post back to itself.

Android Studio installation on Windows 7 fails, no JDK found

The path for the latest JDK. It worked very well.

enter image description here

display Java.util.Date in a specific format

Use the SimpleDateFormat.format

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);

How do I run a Python program?

Navigate your file location just press Shift button and click file name. Click tab Open command window here and write in your command prompt python file_name.py

HttpUtility does not exist in the current context

Agrega System.web a las referencias del proyecto.

[Edit]

According to Google Translate, this translates to:

Add System.Web to the project references.

How to write a comment in a Razor view?

Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.

Server side Comments:

Razor .cshtml

Like so:

@* Comment goes here *@

.aspx
For those looking for the older .aspx view (and Asp.Net WebForms) server side comment syntax:

<%-- Comment goes here --%>

Client Side Comments

HTML Comment

<!-- Comment goes here -->

Javascript Comment

// One line Comment goes Here
/* Multiline comment
   goes here */

As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).

How to get phpmyadmin username and password

I had a problem with this. I didn't even create any passwords so I was confused. I googled it and I found out that I should just write root as username and than click GO. I hope it helps.

escaping question mark in regex javascript

Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:

var re = /I like your Apartment\. Could we schedule a viewing\?/g;
                               ^^                            ^^

Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes for them to denote a literal backslash:

var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");

And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):

_x000D_
_x000D_
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
_x000D_
_x000D_
_x000D_

A must-read: RegExp: Description at MDN.

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:

First, you need to link against QuickLook.framework and #import <QuickLook/QuickLook.h>;

Afterwards, in either viewDidLoad or any of the lazy initialization methods:

QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];

In Python, how to display current time in readable format

You could do something like:

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
'Thu, 28 Jun 2001 14:17:15 +0000'

The full doc on the % codes are at http://docs.python.org/library/time.html

How do I reload a page without a POSTDATA warning in Javascript?

using meta refresh in html

<meta http-equiv='refresh' content='1'>

using meta refresh in php

echo "<meta http-equiv='refresh' content='1'>"

Using Node.JS, how do I read a JSON file into (server) memory?

using node-fs-extra (async await)

const readJsonFile = async () => {
  try {
    const myJsonObject = await fs.readJson('./my_json_file.json');
    console.log(myJsonObject);
  } catch (err) {
    console.error(err)
  }
}

readJsonFile() // prints your json object

How to compile for Windows on Linux with gcc/g++?

From: https://fedoraproject.org/wiki/MinGW/Tutorial

As of Fedora 17 it is possible to easily build (cross-compile) binaries for the win32 and win64 targets. This is realized using the mingw-w64 toolchain: http://mingw-w64.sf.net/. Using this toolchain allows you to build binaries for the following programming languages: C, C++, Objective-C, Objective-C++ and Fortran.

"Tips and tricks for using the Windows cross-compiler": https://fedoraproject.org/wiki/MinGW/Tips

How to count TRUE values in a logical vector

Another way is

> length(z[z==TRUE])
[1] 498

While sum(z) is nice and short, for me length(z[z==TRUE]) is more self explaining. Though, I think with a simple task like this it does not really make a difference...

If it is a large vector, you probably should go with the fastest solution, which is sum(z). length(z[z==TRUE]) is about 10x slower and table(z)[TRUE] is about 200x slower than sum(z).

Summing up, sum(z) is the fastest to type and to execute.

Sniffing/logging your own Android Bluetooth traffic

On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa

With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '

I was used Total Commander for taking file from Internal storage

How to display my location on Google Maps for Android API v2

From android 6.0 you need to check for user permission, if you want to use GoogleMap.setMyLocationEnabled(true) you will get Call requires permission which may be rejected by user error

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
   mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}

if you want to read more, check google map docs

How to keep a git branch in sync with master

Whenever you want to get the changes from master into your work branch, do a git rebase <remote>/master. If there are any conflicts. resolve them.

When your work branch is ready, rebase again and then do git push <remote> HEAD:master. This will update the master branch on remote (central repo).

add an onclick event to a div

Is it possible to add onclick to a div and have it occur if any area of the div is clicked.

Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work

If yes then why is the onclick method not going through to my div.

You are assigning a string where a function is expected.

divTag.onclick = printWorking;

There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.

That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener

How to Execute stored procedure from SQL Plus?

You have two options, a PL/SQL block or SQL*Plus bind variables:

var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

How to check sbt version?

sbt about then enter to get SBT version

enter image description here

How to do a recursive find/replace of a string with awk or sed?

A simpler way is to use the below on the command line

find /home/www/ -type f|xargs perl -pi -e 's/subdomainA\.example\.com/subdomainB.example.com/g' 

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

Change:

<select name="select2" ...

To:

<select name="select2[]" ...

Tree view of a directory/folder in Windows?

If it is just viewing in tree view,One workaround is to use the Explorer in Notepad++ or any other tools.

How can I apply a border only inside a table?

this works for me:

table {
    border-collapse: collapse;
    border-style: hidden;
}

table td, table th {
    border: 1px solid black;
}

view example ...

tested in FF 3.6 and Chromium 5.0, IE lacks support; from W3C:

Borders with the 'border-style' of 'hidden' take precedence over all other conflicting borders. Any border with this value suppresses all borders at this location.

UNION with WHERE clause

You need to look at the explain plans, but unless there is an INDEX or PARTITION on COL_A, you are looking at a FULL TABLE SCAN on both tables.

With that in mind, your first example is throwing out some of the data as it does the FULL TABLE SCAN. That result is being sorted by the UNION, then duplicate data is dropped. This gives you your result set.

In the second example, you are pulling the full contents of both tables. That result is likely to be larger. So the UNION is sorting more data, then dropping the duplicate stuff. Then the filter is being applied to give you the result set you are after.

As a general rule, the earlier you filter away data, the smaller the data set, and the faster you will get your results. As always, your milage may vary.

How to send emails from my Android application?

I use the below code in my apps. This shows exactly email client apps, such as Gmail.

    Intent contactIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.email_to), null));
    contactIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject));
    startActivity(Intent.createChooser(contactIntent, getString(R.string.email_chooser)));

Javascript: how to validate dates in format MM-DD-YYYY?

<script language = "Javascript">
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
        if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strDay=dtStr.substring(0,pos1)
    var strMonth=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
        alert("The date format should be : dd/mm/yyyy")
        return false
    }
    if (strMonth.length<1 || month<1 || month>12){
        alert("Please enter a valid month")
        return false
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        alert("Please enter a valid day")
        return false
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
        return false
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        alert("Please enter a valid date")
        return false
    }
return true
}

function ValidateForm(){
    var dt=document.frmSample.txtDateenter code here
    if (isDate(dt.value)==false){
        dt.focus()
        return false
    }
    return true
 }

</script>

Git:nothing added to commit but untracked files present

Please Follow this process

First of all install git bash and create a repository on git

1) Go to working directory where the file exist which you want to push on remote and create .git folder by

$ git init

2) Add the files in your new local repository.

$ git add .

Note: while you are in same folder make sure you have placed dot after command if you putting path or not putting dot that will create ambiguity

3) Commit the files that you've staged in your local repository.

$ git commit -m "First commit"**

4) after this go to git repository and copy remote URL

$ git remote add origin *remote repository URL

5)

$ git remote -v

Note: this will ask for user.email and user.name just put it as per config

6)

$ git push origin master

this will push whole committed code to FILE.git on repository

And I think we done

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

Here is the result. enter image description here

LISTAGG in Oracle to return distinct values

Use listagg_clob function created like this:

create or replace package list_const_p
is
list_sep varchar2(10) := ',';
end list_const_p;
/
sho err

create type listagg_clob_t as object(
v_liststring varchar2(32767),
v_clob clob,
v_templob number,

static function ODCIAggregateInitialize(
sctx IN OUT listagg_clob_t
) return number,
member function ODCIAggregateIterate(
self IN OUT listagg_clob_t, value IN varchar2
) return number,
member function ODCIAggregateTerminate(
self IN OUT listagg_clob_t, returnValue OUT clob, flags IN number
) return number,
member function ODCIAggregateMerge(
self IN OUT listagg_clob_t, ctx2 IN OUT listagg_clob_t
) return number
);
/
sho err

create or replace type body listagg_clob_t is

static function ODCIAggregateInitialize(sctx IN OUT listagg_clob_t)
return number is
begin
sctx := listagg_clob_t('', '', 0);
return ODCIConst.Success;
end;

member function ODCIAggregateIterate(
self IN OUT listagg_clob_t,
value IN varchar2
) return number is
begin
if nvl(lengthb(v_liststring),0) + nvl(lengthb(value),0) <= 4000 then
self.v_liststring:=self.v_liststring || value || list_const_p.list_sep;
else
if self.v_templob = 0 then
dbms_lob.createtemporary(self.v_clob, true, dbms_lob.call);
self.v_templob := 1;
end if;
dbms_lob.writeappend(self.v_clob, length(self.v_liststring), v_liststring);
self.v_liststring := value || list_const_p.list_sep;
end if;
return ODCIConst.Success;
end;

member function ODCIAggregateTerminate(
self IN OUT listagg_clob_t,
returnValue OUT clob,
flags IN number
) return number is
begin
if self.v_templob != 0 then
dbms_lob.writeappend(self.v_clob, length(self.v_liststring), self.v_liststring);
dbms_lob.trim(self.v_clob, dbms_lob.getlength(self.v_clob) - 1);
else
self.v_clob := substr(self.v_liststring, 1, length(self.v_liststring) - 1);
end if;
returnValue := self.v_clob;
return ODCIConst.Success;
end;

member function ODCIAggregateMerge(self IN OUT listagg_clob_t, ctx2 IN OUT listagg_clob_t) return number is
begin
if ctx2.v_templob != 0 then
if self.v_templob != 0 then
dbms_lob.append(self.v_clob, ctx2.v_clob);
dbms_lob.freetemporary(ctx2.v_clob);
ctx2.v_templob := 0;
else
self.v_clob := ctx2.v_clob;
self.v_templob := 1;
ctx2.v_clob := '';
ctx2.v_templob := 0;
end if;
end if;
if nvl(lengthb(self.v_liststring),0) + nvl(lengthb(ctx2.v_liststring),0) <= 4000 then
self.v_liststring := self.v_liststring || ctx2.v_liststring;
ctx2.v_liststring := '';
else
if self.v_templob = 0 then
dbms_lob.createtemporary(self.v_clob, true, dbms_lob.call);
self.v_templob := 1;
end if;
dbms_lob.writeappend(self.v_clob, length(self.v_liststring), self.v_liststring);
dbms_lob.writeappend(self.v_clob, length(ctx2.v_liststring), ctx2.v_liststring);
self.v_liststring := '';
ctx2.v_liststring := '';
end if;
return ODCIConst.Success;
end;
end;
/
sho err

CREATE or replace FUNCTION listagg_clob (input varchar2) RETURN clob
PARALLEL_ENABLE AGGREGATE USING listagg_clob_t;
/
sho err 

jQuery DataTables Getting selected row values

var table = $('#myTableId').DataTable();
var a= [];
$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});

console.log(a[0]);

How/when to use ng-click to call a route?

You can use:

<a ng-href="#/about">About</a>

If you want some dynamic variable inside href you can do like this way:

<a ng-href="{{link + 123}}">Link to 123</a>

Where link is Angular scope variable.

PHP Get name of current directory

To get only the name of the directory where script executed:

//Path to script: /data/html/cars/index.php
echo basename(dirname(__FILE__)); //"cars"

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

I fixed this error by upgrading the app from .Net Framework 4.5 to 4.6.2.

TLS-1.2 was correctly installed on the server, and older versions like TLS-1.1 were disabled. However, .Net 4.5 does not support TLS-1.2.

OpenCV & Python - Image too big to display

Try with this code:

from PIL import Image

Image.fromarray(image).show()

Can I have an IF block in DOS batch file?

Instead of this goto mess, try using the ampersand & or double ampersand && (conditional to errorlevel 0) as command separators.

I fixed a script snippet with this trick, to summarize, I have three batch files, one which calls the other two after having found which letters the external backup drives have been assigned. I leave the first file on the primary external drive so the calls to its backup routine worked fine, but the calls to the second one required an active drive change. The code below shows how I fixed it:

for %%b in (d e f g h i j k l m n o p q r s t u v w x y z) DO (
if exist "%%b:\Backup.cmd" %%b: & CALL "%%b:\Backup.cmd"
)

keytool error bash: keytool: command not found

If you are not using openjdk, use the below commands to set your keytool.

sudo update-alternatives --install "/usr/bin/keytool" "keytool" "/usr/lib/jvm/java8/jdk1.8.0_251/bin/keytool" 1

AND

sudo update-alternatives --set keytool /usr/lib/jvm/java8/jdk1.8.0_251/bin/keytool

This worked for me!

Highest Salary in each department

IF you want Department and highest salary, use

SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID

if you want more columns in employee and department, use

select  Department.Name , emp.Name, emp.Salary from Employee emp
inner join (select DeptID, max(salary) [salary] from employee group by DeptID) b
on emp.DeptID = b.DeptID and b.salary = emp.Salary
inner join Department on emp.DeptID = Department.id
order by Department.Name

if use salary in (select max(salary...)) like this, one person have same salary in another department then it will fail.

SQL Query NOT Between Two Dates

Do you mean that the date range of the selected rows should not lie fully within the specified date range? In which case:

select *
from test_table
where start_date < date '2009-12-15'
or end_date > date '2010-01-02';

(Syntax above is for Oracle, yours may differ slightly).

How to use onResume()?

onResume() is one of the methods called throughout the activity lifecycle. onResume() is the counterpart to onPause() which is called anytime an activity is hidden from view, e.g. if you start a new activity that hides it. onResume() is called when the activity that was hidden comes back to view on the screen.

You're question asks abou what method is used to restart an activity. onCreate() is called when the activity is first created. In practice, most activities persist in the background through a series of onPause() and onResume() calls. An activity is only really "restarted" by onRestart() if it is first fully stopped by calling onStop() and then brought back to life. Thus if you are not actually stopping activities with onStop() it is most likley you will be using onResume().

Read the android doc in the above link to get a better understanding of the relationship between the different lifestyle methods. Regardless of which lifecycle method you end up using the general format is the same. You must override the standard method and include your code, i.e. what you want the activity to do at that point, in the commented section.

@Override
public void onResume(){
 //will be executed onResume
}

How to resize JLabel ImageIcon?

Resizing the icon is not straightforward. You need to use Java's graphics 2D to scale the image. The first parameter is a Image class which you can easily get from ImageIcon class. You can use ImageIcon class to load your image file and then simply call getter method to get the image.

private Image getScaledImage(Image srcImg, int w, int h){
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = resizedImg.createGraphics();

    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();

    return resizedImg;
}

What are the differences between Mustache.js and Handlebars.js?

Another difference between them is the size of the file:

To see the performance benefits of Handlebars.js we must use precompiled templates.

Source: An Overview of JavaScript Templating Engines

Which is the preferred way to concatenate a string in Python?

While somewhat dated, Code Like a Pythonista: Idiomatic Python recommends join() over + in this section. As does PythonSpeedPerformanceTips in its section on string concatenation, with the following disclaimer:

The accuracy of this section is disputed with respect to later versions of Python. In CPython 2.5, string concatenation is fairly fast, although this may not apply likewise to other Python implementations. See ConcatenationTestCode for a discussion.

Resize a large bitmap file to scaled output file on Android

I don't know if my solution is best practice, but I achieved loading a bitmap with my desired scaling by using the inDensity and inTargetDensity options. inDensity is 0 initially when not loading a drawable resource, so this approach is for loading non resource images.

The variables imageUri, maxImageSideLength and context are parameters of my method. I posted only the method implementation without the wrapping AsyncTask for clarity.

            ContentResolver resolver = context.getContentResolver();
            InputStream is;
            try {
                is = resolver.openInputStream(imageUri);
            } catch (FileNotFoundException e) {
                Log.e(TAG, "Image not found.", e);
                return null;
            }
            Options opts = new Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, opts);

            // scale the image
            float maxSideLength = maxImageSideLength;
            float scaleFactor = Math.min(maxSideLength / opts.outWidth, maxSideLength / opts.outHeight);
            // do not upscale!
            if (scaleFactor < 1) {
                opts.inDensity = 10000;
                opts.inTargetDensity = (int) ((float) opts.inDensity * scaleFactor);
            }
            opts.inJustDecodeBounds = false;

            try {
                is.close();
            } catch (IOException e) {
                // ignore
            }
            try {
                is = resolver.openInputStream(imageUri);
            } catch (FileNotFoundException e) {
                Log.e(TAG, "Image not found.", e);
                return null;
            }
            Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts);
            try {
                is.close();
            } catch (IOException e) {
                // ignore
            }

            return bitmap;

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

I ran into this same problem these days and maybe some more detail might be helpful to somebody else.

I was looking some security guidelines for REST APIs and crossed a very intriguing issue with json arrays. Check the link for details, but basically, you should wrap them within an Object as we already saw in this post question.

So, instead of:

  [
    {
      "name": "order1"
    },
    {
      "name": "order2"
    }
  ]

It's advisable that we always do:

  {
    "data": [
      {
        "name": "order1"
      },
      {
        "name": "order2"
      }
    ]
  }

This is pretty straight-forward when you doing a GET, but might give you some trouble if, instead, your trying to POST/PUT the very same json.

In my case, I had more than one GET that was a List and more than one POST/PUT that would receive the very same json.

So what I end up doing was to use a very simple Wrapper object for a List:

public class Wrapper<T> {
  private List<T> data;

  public Wrapper() {}

  public Wrapper(List<T> data) {
    this.data = data;
  }
  public List<T> getData() {
    return data;
  }
  public void setData(List<T> data) {
    this.data = data;
  }
}

Serialization of my lists were made with a @ControllerAdvice:

@ControllerAdvice
public class JSONResponseWrapper implements ResponseBodyAdvice<Object> {

  @Override
  public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    return true;
  }

  @Override
  @SuppressWarnings("unchecked")
  public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    if (body instanceof List) {
      return new Wrapper<>((List<Object>) body);
    }
    else if (body instanceof Map) {
      return Collections.singletonMap("data", body);
    }  
    return body;
  }
}

So, all the Lists and Maps where wrapped over a data object as below:

  {
    "data": [
      {...}
    ]
  }

Deserialization was still default, just using de Wrapper Object:

@PostMapping("/resource")
public ResponseEntity<Void> setResources(@RequestBody Wrapper<ResourceDTO> wrappedResources) {
  List<ResourceDTO> resources = wrappedResources.getData();
  // your code here
  return ResponseEntity
           .ok()
           .build();
}

That was it! Hope it helps someone.

Note: tested with SpringBoot 1.5.5.RELEASE.

Get java.nio.file.Path object from java.io.File

As many have suggested, JRE v1.7 and above has File.toPath();

File yourFile = ...;
Path yourPath = yourFile.toPath();

On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;

File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());

How to add an extra row to a pandas dataframe

Upcoming pandas 0.13 version will allow to add rows through loc on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.

Description is here and this new feature is called Setting With Enlargement.

Multiline for WPF TextBox

Enable TextWrapping="Wrap" and AcceptsReturn="True" on your TextBox.

You might also wish to enable AcceptsTab and SpellCheck.IsEnabled too.

How to create localhost database using mysql?

removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.

What's the best way to share data between activities?

Assuming you are calling activity two from activity one using an Intent.
You can pass the data with the intent.putExtra(),

Take this for your reference. Sending arrays with Intent.putExtra

Hope that's what you want.

How do I 'git diff' on a certain directory?

You should make a habit of looking at the documentation for stuff like this. It's very useful and will improve your skills very quickly. Here's the relevant bit when you do git help diff

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

The two <path>s are what you need to change to the directories in question.

Create XML in Javascript

Your code is referencing this library

You can include it, and then your code in question should run as is. If you want to do this without prepending the library & build it with builtin functions only - follow answer from @Seb3736.

In Browser Example

<html>
<head>
    <script src="Global.js" language="javascript"></script>
    <script src="XMLWriter.js" language="javascript"></script>
    <script language="javascript" type="text/javascript">
        function genXML(){
            var XML = new XMLWriter();
            XML.BeginNode ("testing");
            XML.Node("testingOne");
            XML.Node("TestingTwo");
            XML.Node("TestingThree");
            XML.EndNode();
            //Do something... eg.
            console.log(XML.ToString); //Yes ToString() not toString()
        }
    </script>
</head>
<body>
    <input type="submit" value="genXML" onclick="genXML();">
</body>
</html>

How can I calculate the time between 2 Dates in typescript

It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.

There is a workaround this using the + prefix:

var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");

Or, if you prefer not to use Date.now():

var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));

See discussion here.

Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()

Oracle PL/SQL : remove "space characters" from a string

I'd go for regexp_replace, although I'm not 100% sure this is usable in PL/SQL

my_value := regexp_replace(my_value, '[[:space:]]*',''); 

How do I compare 2 rows from the same table (SQL Server)?

OK, after 2 years it's finally time to correct the syntax:

SELECT  t1.value, t2.value
FROM    MyTable t1
JOIN    MyTable t2
ON      t1.id = t2.id
WHERE   t1.id = @id
        AND t1.status = @status1
        AND t2.status = @status2

Why do we not have a virtual constructor in C++?

There's a very basic reason: Constructors are effectively static functions, and in C++ no static function can be virtual.

If you have much experience with C++, you know all about the difference between static & member functions. Static functions are associated with the CLASS, not the objects (instances), so they don't see a "this" pointer. Only member functions can be virtual, because the vtable- the hidden table of function pointers that makes 'virtual' work- is really a data member of each object.

Now, what is the constructor's job? It is in the name- a "T" constructor initializes T objects as they're allocated. This automatically precludes it being a member function! An object has to EXIST before it has a "this" pointer and thus a vtable. That means that even if the language treated constructors as ordinary functions (it doesn't, for related reasons I won't get into), they'd have to be static member functions.

A great way to see this is to look at the "Factory" pattern, especially factory functions. They do what you're after, and you'll notice that if class T has a factory method, it is ALWAYS STATIC. It has to be.

Looking for simple Java in-memory cache

Try Ehcache? It allows you to plug in your own caching expiry algorithms so you could control your peek functionality.

You can serialize to disk, database, across a cluster etc...

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".

Extract file basename without path and extension in bash

Here is another (more complex) way of getting either the filename or extension, first use the rev command to invert the file path, cut from the first . and then invert the file path again, like this:

filename=`rev <<< "$1" | cut -d"." -f2- | rev`
fileext=`rev <<< "$1" | cut -d"." -f1 | rev`

To get specific part of a string in c#

If you want to get the strings separated by the , you can use

string b = a.Split(',')[0];

Find element's index in pandas Series

Another way to do this, although equally unsatisfying is:

s = pd.Series([1,3,0,7,5],index=[0,1,2,3,4])

list(s).index(7)

returns: 3

On time tests using a current dataset I'm working with (consider it random):

[64]:    %timeit pd.Index(article_reference_df.asset_id).get_loc('100000003003614')
10000 loops, best of 3: 60.1 µs per loop

In [66]: %timeit article_reference_df.asset_id[article_reference_df.asset_id == '100000003003614'].index[0]
1000 loops, best of 3: 255 µs per loop


In [65]: %timeit list(article_reference_df.asset_id).index('100000003003614')
100000 loops, best of 3: 14.5 µs per loop

Convert timestamp to date in Oracle SQL

You can use:

select to_date(to_char(date_field,'dd/mm/yyyy')) from table

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

How to detect escape key press with pure JS or jQuery?

i think the simplest way is vanilla javascript:

document.onkeyup = function(event) {
   if (event.keyCode === 27){
     //do something here
   }
}

Updated: Changed key => keyCode

What is your most productive shortcut with Vim?

A third criteria for making editing faster is the number of keystrokes required. I would say this is more important than your other 2. In vim, almost all operations require fewer keystrokes than any other editor I'm familiar with.

You mention that you are having trouble with cut & paste, but it sounds like you need more experience with general motion commands in vim. yank 3 words: y3w yank from the cursor to the next semi-colon: yf; yank to the next occurrence of your most recent search: yn All of those are much faster than trying to navigate with a mouse while holding down a modifier key. Also, as seen in some of the examples in CMS's response, vim's motion commands are highly optimized for efficient navigation in C and C++ source code.

As to the question 'how do I use vim that makes me more productive?', I hope the answer is: "efficiently".

Facebook Architecture

"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"

I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.

Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.

If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.