Programs & Examples On #User interaction

User-interactivity is the dialog that occurs between a human being and a computer program.

SSL Error: unable to get local issuer certificate

If you are a linux user Update node to a later version by running

sudo apt update

 sudo apt install build-essential checkinstall libssl-dev

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash

nvm --version

nvm ls

nvm ls-remote

nvm install [version.number]

this should solve your problem

how to resolve DTS_E_OLEDBERROR. in ssis

I faced the similar issue.

Deselect the check box ("In wizard deselect the checkbox stating "First row has columns names") and before running the wizard make sure you have opened your excel sheet.

Then run the wizard by deselecting the checkbox.

This resolved my issue.

encrypt and decrypt md5

Hashes can not be decrypted check this out.

If you want to encrypt-decrypt, use a two way encryption function of your database like - AES_ENCRYPT (in MySQL).

But I'll suggest CRYPT_BLOWFISH algorithm for storing password. Read this- http://php.net/manual/en/function.crypt.php and http://us2.php.net/manual/en/function.password-hash.php

For Blowfish by crypt() function -

crypt('String', '$2a$07$twentytwocharactersalt$');

password_hash will be introduced in PHP 5.5.

$options = [
    'cost' => 7,
    'salt' => 'BCryptRequires22Chrcts',
];
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);

Once you have stored the password, you can then check if the user has entered correct password by hashing it again and comparing it with the stored value.

How to put a symbol above another in LaTeX?

Use \overset{above}{main} in math mode. In your case, \overset{a}{\#}.

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

Could not create work tree dir 'example.com'.: Permission denied

Turns out the problem was in the permission. I fix it with the following command

sudo chown -R $USER /var/www

Please make sure with the $USER variable. I tested and worked on Ubuntu Distro

How to get the name of a class without the package?

If using a StackTraceElement, use:

String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);

System.out.println(simpleClassName);

Java enum - why use toString instead of name

name() is a "built-in" method of enum. It is final and you cannot change its implementation. It returns the name of enum constant as it is written, e.g. in upper case, without spaces etc.

Compare MOBILE_PHONE_NUMBER and Mobile phone number. Which version is more readable? I believe the second one. This is the difference: name() always returns MOBILE_PHONE_NUMBER, toString() may be overriden to return Mobile phone number.

Removing duplicates from a SQL query (not just "use distinct")

Arbitrarily choosing to keep the minimum PIC_ID. Also, avoid using the implicit join syntax.

SELECT U.NAME, MIN(P.PIC_ID)
    FROM USERS U
        INNER JOIN POSTINGS P1
            ON U.EMAIL_ID = P1.EMAIL_ID
        INNER JOIN PICTURES P
            ON P1.PIC_ID = P.PIC_ID
    WHERE P.CAPTION LIKE '%car%'
    GROUP BY U.NAME;

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

tl;dr

LocalDateTime.parse( 
    "2012-07-10 14:58:00.000000".replace( " " , "T" )  
)

Microseconds do not fit

You are attempting to squeeze a value with microseconds (six decimal digits) into a data type capable only of milliseconds resolution (three decimal digits). That is impossible.

Instead, use a data type with fine enough resolution. The java.time classes use nanosecond resolution (nine decimal digits).

Unzoned input does not fit a zoned type

You are attempting to put a value lacking any offset-from-UTC or time zone into a data type (Date) that only represents values in UTC. So you are adding information (UTC offset) not intended by the input.

Use an appropriate data type instead. Specifically, java.time.LocalDateTime.

Case-sensitive

Other Answers and Comments correctly explain that the formatting pattern codes are case-sensitive. So MM and mm have different effects.

Avoid legacy classes

The troublesome old date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes built into Java 8 and later.

ISO 8601

Your input strings nearly comply with the ISO 8601 standard formats. Replace the SPACE in the middle with a T to comply fully.

The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

Date-time objects have no "format"

and I need the resultant date object to be of the same format.

No, date-time objects do not have a "format". Do not conflate date-time objects with mere strings. Strings are inputs and outputs of the objects. The objects maintain their own internal representions of the date-time info, the details of which are irrelevant to us as calling programmers.

java.time

Your input lacks any indicator of offset-from-UTC or troublesome me zone. So we parse as a LocalDateTime objects which lacks those concepts.

String input = "2012-07-10 14:58:00.000000".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

Generating strings

To generate a String representing the value of your LocalDateTime:

  • Call toString to get a String in standard ISO 8601 format.
  • Use DateTimeFormatter for producing strings in either custom formats or automatically-localized formats.

Search Stack Overflow for more info as these topics have been covered many many times already.

ZonedDateTime

A LocalDateTime does not represent an exact point on the timeline.

To determine an actual moment, assign a time zone. For example noon in Kolkata India comes much earlier than noon in Paris France. Noon without a time zone could be happening at any point over a range of about 26-27 hours.

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Two way sync with rsync

Rclone is what you are looking for. Rclone ("rsync for cloud storage") is a command line program to sync files and directories to and from different cloud storage providers including local filesystems. Rclone was previously known as Swiftsync and has been available since 2013.

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

function converToLocalTime(serverDate) {

    var dt = new Date(Date.parse(serverDate));
    var localDate = dt;
    
    var gmt = localDate;
        var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
        var localNow = new Date().getTimezoneOffset(); // get the timezone
        // offset in minutes
        var localTime = min - localNow; // get the local time

    var dateStr = new Date(localTime * 1000 * 60);
    // dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
    dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    return dateStr;
}

Display a jpg image on a JPanel

You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.

Getting the filenames of all files in a folder

Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.

List<String> results = new ArrayList<String>();


File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

How to copy files from host to Docker container?

The solution is given below,

From the Docker shell,

root@123abc:/root#  <-- get the container ID

From the host

cp thefile.txt /var/lib/docker/devicemapper/mnt/123abc<bunch-o-hex>/rootfs/root

The file shall be directly copied to the location where the container sits on the filesystem.

spark submit add multiple jars in classpath

I was trying to connect to mysql from the python code that was executed using spark-submit.

I was using HDP sandbox that was using Ambari. Tried lot of options such as --jars, --driver-class-path, etc, but none worked.

Solution

Copy the jar in /usr/local/miniconda/lib/python2.7/site-packages/pyspark/jars/

As of now I'm not sure if it's a solution or a quick hack, but since I'm working on POC so it kind of works for me.

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

I have a full explanation already posted here

Basically, General guidelines for designing images are:

ldpi is 0.75x dimensions of mdpi
hdpi is 1.5x dimensions of mdpi
xhdpi is 2x dimensinons of mdpi

Usually, I design mdpi images for a 320x480 screen and then multiply the dimensions as per the above rules to get images for other resolutions.

Please refer to the full explanation for a more detailed answer.

Can't use SURF, SIFT in OpenCV

As an Anaconda user, I wanted to find one or two appropriate commands to solve the problem. Fortunately, this answer helped. For conda 4.5.11 (use conda -V to check Anaconda version) I have performed next steps:

# Python version does not matter, most likely, check yourself
conda create -n myenv python=3.6     
conda activate myenv
conda install -c menpo opencv

That will install OpenCV 2.4.11. Anaconda's another command conda install -c menpo opencv3 will install OpenCV3, but Python has to be downgraded to 2.7. To install OpenCV3 with Python3 use next (due to the first link):

conda create -n myenv python  
pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16

Check the SIFT:

conda activate myenv
python
>>> cv2.xfeatures2d.SIFT_create()
<xfeatures2d_SIFT 000002A3478655B0>

Oracle Error ORA-06512

ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).

In a comment you said

"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"

Well, your code does this:

IF ((pNum < 12) OR (pNum > 14)) THEN     
    RAISE vSOME_EX;

That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?

ORA-06510: PL/SQL: unhandled user-defined exception

If so, all you need to do is add an exception block to handle the error. Perhaps:

PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
    vSOME_EX EXCEPTION;

BEGIN 
    IF ((pNum < 12) OR (pNum > 14)) THEN     
        RAISE vSOME_EX;
    ELSE  
        EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
    END IF;
exception
    when vsome_ex then
         raise_application_error(-20000
                                 , 'This is not a valid table:  M'||pNum||'GR');

END PX;

The documentation covers handling PL/SQL exceptions in depth.

NGinx Default public www location?

On Mac OS X installing nginx with brew makes the default directory:

/usr/local/var/www

So:

root html

means

root /usr/local/var/www/html

There is no html directory so it would have to be created manually.

Node.js console.log() not logging anything

This can be confusing for anyone using nodejs for the first time. It is actually possible to pipe your node console output to the browser console. Take a look at connect-browser-logger on github

UPDATE: As pointed out by Yan, connect-browser-logger appears to be defunct. I would recommend NodeMonkey as detailed here : Output to Chrome console from Node.js

Create a GUID in Java

Have a look at the UUID class bundled with Java 5 and later.

For example:

Use PHP composer to clone git repo

If you want to use a composer.json from GitHub you would look at this example (under the VCS section).

The package section is for packages that do not have the composer.json. However, you didn't follow that example as well or it would also have worked. Do read what it says about package repositories:

Basically, you define the same information that is included in the composer repository's packages.json, but only for a single package. Again, the minimum required fields are name, version, and either of dist or source.

How can I start PostgreSQL server on Mac OS X?

PostgreSQL is integrated in Server.app available through the App Store in Mac OS X v10.8 (Mountain Lion). That means that it is already configured, and you only need to launch it, and then create users and databases.

Tip: Do not start with defining $PGDATA and so on. Take file locations as is.

You would have this file: /Library/Server/PostgreSQL/Config/org.postgresql.postgres.plist

To start:

sudo serveradmin start postgres

Process started with arguments:

/Applications/Server.app/Contents/ServerRoot/usr/bin/postgres_real -D /Library/Server/PostgreSQL/Data -c listen_addresses=127.0.0.1,::1 -c log_connections=on -c log_directory=/Library/Logs/PostgreSQL -c log_filename=PostgreSQL.log -c log_line_prefix=%t -c log_lock_waits=on -c log_statement=ddl -c logging_collector=on -c unix_socket_directory=/private/var/pgsql_socket -c unix_socket_group=_postgres -c unix_socket_permissions=0770

You can sudo:

sudo -u _postgres psql template1

Or connect:

psql -h localhost -U _postgres postgres

You can find the data directory, version, running status and so forth with

sudo serveradmin fullstatus postgres

Which to use <div class="name"> or <div id="name">?

ID provides a unique indentifier for the element, in case you want to manipulate it in JavaScript. The class attribute can be used to treat a group of HTML elements the same, particularly in regards to fonts, colors and other style properties...

JSON date to Java date?

That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.

Here's one

If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat to parse these kinds of strings.

Reversing a string in C

Just a rearrangement, and safety check. I also removed your non-used return type. I think this is a safe and clean as it gets:

#include <stdio.h>
#include <string.h>

void reverse_string(char *str)
{
    /* skip null */
    if (str == 0)
    {
        return;
    }

    /* skip empty string */
    if (*str == 0)
    {
        return;
    }

    /* get range */
    char *start = str;
    char *end = start + strlen(str) - 1; /* -1 for \0 */
    char temp;

    /* reverse */
    while (end > start)
    {
        /* swap */
        temp = *start;
        *start = *end;
        *end = temp;

        /* move */
        ++start;
        --end;
    }
}


int main(void)
{
    char s1[] = "Reverse me!";
    char s2[] = "abc";
    char s3[] = "ab";
    char s4[] = "a";
    char s5[] = "";

    reverse_string(0);

    reverse_string(s1);
    reverse_string(s2);
    reverse_string(s3);
    reverse_string(s4);
    reverse_string(s5);

    printf("%s\n", s1);
    printf("%s\n", s2);
    printf("%s\n", s3);
    printf("%s\n", s4);
    printf("%s\n", s5);

    return 0;
}

Edited so that end will not point to a possibly bad memory location when strlen is 0.

Interpreting segfault messages

This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).

If this were a program, not a shared library

Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d (and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.

Since it's a shared library

You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb.

What the error means

Here's the breakdown of the fields:

  • address (after the at) - the location in memory the code is trying to access (it's likely that 10 and 11 are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0)
  • ip - instruction pointer, ie. where the code which is trying to do this lives
  • sp - stack pointer
  • error - An error code for page faults; see below for what this means on x86.

    /*
     * Page fault error code bits:
     *
     *   bit 0 ==    0: no page found       1: protection fault
     *   bit 1 ==    0: read access         1: write access
     *   bit 2 ==    0: kernel-mode access  1: user-mode access
     *   bit 3 ==                           1: use of reserved bit detected
     *   bit 4 ==                           1: fault was an instruction fetch
     */
    

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

CAUTION: This method completely removes MySQL data!

I have same problem in Ubuntu 12.10 , mysql 5.5

I have tested lots of answer related to my issue but none of theme work

at last I had to reinstall remove my mysql server completely and then I install again Mysql server

but you should be aware that you should delete all directory which related to Mysql I use this link to remove mysql completely

sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser mysql
sudo rm -rf /var/lib/mysql
sudo rm -rf /etc/mysql
sudo rm -rf /var/lib/mysql
sudo rm -rf /var/run/mysqld

and then you install again LAMP by tasksel

Removing MySQL 5.5 Completely

https://serverfault.com/questions/254629/unable-to-install-mysql-server-in-ubuntu/296928#296928

MySQL "between" clause not inclusive?

You can run the query as:

select * from person where dob between '2011-01-01' and '2011-01-31 23:59:59'

like others pointed out, if your dates are hardcoded.

On the other hand, if the date is in another table, you can add a day and subtract a second (if the dates are saved without the second/time), like:

select * from person JOIN some_table ... where dob between some_table.initial_date and (some_table.final_date + INTERVAL 1 DAY - INTERVAL 1 SECOND)

Avoid doing casts on the dob fiels (like in the accepted answer), because that can cause huge performance problems (like not being able to use an index in the dob field, assuming there is one). The execution plan may change from using index condition to using where if you make something like DATE(dob) or CAST(dob AS DATE), so be careful!

Getting a machine's external IP address with Python

If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.

Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)

Install:

pip install upnpclient

Simple Code:

import upnpclient

devices = upnpclient.discover()

if(len(devices) > 0):
    externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
    print(externalIP)
else:
    print('No Connected network interface detected')

Full Code (to get more information as mentioned in the github readme)

In [1]: import upnpclient

In [2]: devices = upnpclient.discover()

In [3]: devices
Out[3]: 
[<Device 'OpenWRT router'>,
 <Device 'Harmony Hub'>,
 <Device 'walternate: root'>]

In [4]: d = devices[0]

In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]: 
{'NewConnectionStatus': 'Connected',
 'NewLastConnectionError': 'ERROR_NONE',
 'NewUptime': 14851479}

In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}

In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}

Test a weekly cron job

What about putting it into cron.hourly, waiting until the next run of hourly cron jobs, then removing it? That would run it once within an hour, and in the cron environment. You can also run ./your_script, but that won't have the same environment as under cron.

How to extract .war files in java? ZIP vs JAR

Just rename the .war into .jar and unzip it using Winrar (or any other archive manager).

Remove an item from a dictionary when its key is unknown

c is the new dictionary, and a is your original dictionary, {'z','w'} are the keys you want to remove from a

c = {key:a[key] for key in a.keys() - {'z', 'w'}}

Also check: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01.html

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

  1. :datetime (8 bytes)

    • Stores Date and Time formatted YYYY-MM-DD HH:MM:SS
    • Useful for columns like birth_date
  2. :timestamp (4 bytes)

    • Stores number of seconds since 1970-01-01
    • Useful for columns like updated_at, created_at
  3. :date (3 bytes)
    • Stores Date
  4. :time (3 bytes)
    • Stores Time

Figure out size of UILabel based on String in Swift

@IBOutlet weak var constraintTxtV: NSLayoutConstraint!
func TextViewDynamicallyIncreaseSize() {
    let contentSize = self.txtVDetails.sizeThatFits(self.txtVDetails.bounds.size)
    let higntcons = contentSize.height
    constraintTxtV.constant = higntcons
}

What is the difference between a symbolic link and a hard link?

A simple way to see the difference between a hard link and a symbolic link is through a simple example. A hard link to a file will point to the place where the file is stored, or the inode of that file. A symbolic link will point to the actual file itself.

So if we have a file called "a" and create a hard link "b" and a symbolic link "c" which all refer to file "a" :

echo "111" > a
ln a b
ln -s a c

The output of "a", "b", and "c" will be :

cat a --> 111
cat b --> 111
cat c --> 111

Now let's remove file "a" and see what happens to the output of "a", "b", and "c":

rm a
cat a --> No such file or directory
cat b --> 111
cat c --> No such file or directory

So what happened?

Because file "c" points to file "a" itself, if file "a" is deleted then file "c" will have nothing to point to, in fact it is also deleted.

However, file "b" points to the place of storage, or the inode, of file "a". So if file "a" is deleted then it will no longer point to the inode, but because file "b" does, the inode will continue to store whatever contents belonged to "a" until no more hard links point to it anymore.

Is Google Play Store supported in avd emulators?

Easiest way: You should create a new emulator, before opening it for the first time follow these 3 easy steps:

1- go to C:\Users[user].android\avd[your virtual device folder] open "config.ini" with text editor like notepad

2- change

"PlayStore.enabled=false" to "PlayStore.enabled=true"

3- change

mage.sysdir.1 = system-images\android-30\google_apis\x86\

to

image.sysdir.1 = system-images\android-30\google_apis_playstore\x86\

Magento - How to add/remove links on my account navigation?

The answer to your question is ultimately, it depends. The links in that navigation are added via different layout XML files. Here's the code that first defines the block in layout/customer.xml. Notice that it also defines some links to add to the menu:

<block type="customer/account_navigation" name="customer_account_navigation" before="-" template="customer/account/navigation.phtml">
    <action method="addLink" translate="label" module="customer"><name>account</name><path>customer/account/</path><label>Account Dashboard</label></action>
    <action method="addLink" translate="label" module="customer"><name>account_edit</name><path>customer/account/edit/</path><label>Account Information</label></action>
    <action method="addLink" translate="label" module="customer"><name>address_book</name><path>customer/address/</path><label>Address Book</label></action>
</block>

Other menu items are defined in other layout files. For example, the Reviews module uses layout/review.xml to define its layout, and contains the following:

<customer_account>
    <!-- Mage_Review -->
    <reference name="customer_account_navigation">
        <action method="addLink" translate="label" module="review"><name>reviews</name><path>review/customer</path><label>My Product Reviews</label></action>
    </reference>
</customer_account>

To remove this link, just comment out or remove the <action method=...> tag and the menu item will disappear. If you want to find all menu items at once, use your favorite file search and find any instances of name="customer_account_navigation", which is the handle that Magento uses for that navigation block.

How to create a DOM node as an object?

I'd put it in the DOM first. I'm not sure why my first example failed. That's really weird.

var e = $("<ul><li><div class='bar'>bla</div></li></ul>");
$('li', e).attr('id','a1234');  // set the attribute 
$('body').append(e); // put it into the DOM     

Putting e (the returns elements) gives jQuery context under which to apply the CSS selector. This keeps it from applying the ID to other elements in the DOM tree.

The issue appears to be that you aren't using the UL. If you put a naked li in the DOM tree, you're going to have issues. I thought it could handle/workaround this, but it can't.

You may not be putting naked LI's in your DOM tree for your "real" implementation, but the UL's are necessary for this to work. Sigh.

Example: http://jsbin.com/iceqo

By the way, you may also be interested in microtemplating.

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

Commands out of sync; you can't run this command now

I use CodeIgniter. One server OK ... this one probably older ... Anyway using

$this->db->reconnect();

Fixed it.

How to detect internet speed in JavaScript?

Well, this is 2017 so you now have Network Information API (albeit with a limited support across browsers as of now) to get some sort of estimate downlink speed information:

navigator.connection.downlink

This is effective bandwidth estimate in Mbits per sec. The browser makes this estimate from recently observed application layer throughput across recently active connections. Needless to say, the biggest advantage of this approach is that you need not download any content just for bandwidth/ speed calculation.

You can look at this and a couple of other related attributes here

Due to it's limited support and different implementations across browsers (as of Nov 2017), would strongly recommend read this in detail

HTML / CSS table with GRIDLINES

For internal gridlines, use the tag: td For external gridlines, use the tag: table

How to compare two files in Notepad++ v6.6.8

Update:

  • for Notepad++ 7.5 and above use Compare v2.0.0
  • for Notepad++ 7.7 and above use Compare v2.0.0 for Notepad++ 7.7, if you need to install manually follow the description below, otherwise use "Plugin Admin".

I use Compare plugin 2 for notepad++ 7.5 and newer versions. Notepad++ 7.5 and newer versions does not have plugin manager. You have to download and install plugins manually. And YES it matters if you use 64bit or 32bit (86x).

So Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin, and the same valid for 32bit.

I wrote a guideline how to install it:

  1. Start your Notepad++ as administrator mode.
  2. Press F1 to find out if your Notepad++ is 64bit or 32bit (86x), hence you need to download the correct plugin version. Download Compare-plugin 2.
  3. Unzip Compare-plugin in temporary folder.
  4. Import plugin from the temporary folder.
  5. The plugin should appear under Plugins menu.

Note:
It is also possible to drag and drop the plugin .dll file directly in plugin folder.
64bit: %programfiles%\Notepad++\plugins
32bit: %programfiles(x86)%\Notepad++\plugins

Update Thanks to @TylerH with this update: Notepad++ Now has "Plugin Admin" as a replacement for the old Plugin Manager. But this method (answer) is still valid for adding plugins manually for almost any Notepad++ plugins.

Disclaimer: the link of this guideline refer to my personal web site.

Null & empty string comparison in Bash

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';
fi

Or to verify that a variable is empty

#!/bin/bash      
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi

tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

UIButton: set image for selected-highlighted state

Correct me if I am wrong. By doing

   [button setSelected:YES];

you are clearly changing the state of the buttons as selected. So naturally by the code you have provided the image will that for the selected state in your case checked.png

Fastest way to update 120 Million records

If you have the disk space, you could use SELECT INTO and create a new table. It's minimally logged, so it would go much faster

select t.*, int_field = CAST(-1 as int)
into mytable_new 
from mytable t

-- create your indexes and constraints

GO

exec sp_rename mytable, mytable_old
exec sp_rename mytable_new, mytable

drop table mytable_old

Maven dependency for Servlet 3.0 API?

This seems to be added recently:

https://repo1.maven.org/maven2/javax/servlet/javax.servlet-api/3.0.1/

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

How can I beautify JSON programmatically?

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

Truncating a table in a stored procedure

try the below code

execute immediate 'truncate table tablename' ;

JOIN two SELECT statement results

If Age and Palt are columns in the same Table, you can count(*) all tasks and sum only late ones like this:

select ks,
       count(*) tasks,
       sum(case when Age > Palt then 1 end) late
  from Table
 group by ks

Getting the last element of a split string array

var title = 'fdfdsg dsgdfh dgdh dsgdh tyu hjuk yjuk uyk hjg fhjg hjj tytutdfsf sdgsdg dsfsdgvf dfgfdhdn dfgilkj,n, jhk jsu wheiu sjldsf dfdsf hfdkdjf dfhdfkd hsfd ,dsfk dfjdf ,yier djsgyi kds';
var shortText = $.trim(title).substring(1000, 150).split(" ").slice(0, -1).join(" ") + "...More >>";

Opening a folder in explorer and selecting a file

You need to put the arguments to pass ("/select etc") in the second parameter of the Start method.

Merge up to a specific commit

Recently we had a similar problem and had to solve it in a different way. We had to merge two branches up to two commits, which were not the heads of either branches:

branch A: A1 -> A2 -> A3 -> A4
branch B: B1 -> B2 -> B3 -> B4
branch C: C1 -> A2 -> B3 -> C2

For example, we had to merge branch A up to A2 and branch B up to B3. But branch C had cherry-picks from A and B. When using the SHA of A2 and B3 it looked like there was confusion because of the local branch C which had the same SHA.

To avoid any kind of ambiguity we removed branch C locally, and then created a branch AA starting from commit A2:

git co A
git co SHA-of-A2
git co -b AA

Then we created a branch BB from commit B3:

git co B
git co SHA-of-B3
git co -b BB

At that point we merged the two branches AA and BB. By removing branch C and then referencing the branches instead of the commits it worked.

It's not clear to me how much of this was superstition or what actually made it work, but this "long approach" may be helpful.

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

Depending on what you actually want to achieve, you should take a look at Android Handlers:

http://developer.android.com/reference/android/os/Handler.html

If you previously used javascript setTimeout() etc to schedule a task to run in the future, this is the Android way of doing it (postDelayed / sendMessageDelayed).

Note that neither Handlers or Timers makes an Android phone wake up from sleep mode. In other words, if you want to schedule something to actually happen even though the screen is off / cpu is sleeping, you need to check out the AlarmManager too.

form action with javascript

A form action set to a JavaScript function is not widely supported, I'm surprised it works in FireFox.

The best is to just set form action to your PHP script; if you need to do anything before submission you can just add to onsubmit

Edit turned out you didn't need any extra function, just a small change here:

function validateFormOnSubmit(theForm) {
    var reason = "";
    reason += validateName(theForm.name);
    reason += validatePhone(theForm.phone);
    reason += validateEmail(theForm.emaile);

    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
    } else {
        simpleCart.checkout();
    }
    return false;
}

Then in your form:

<form action="#" onsubmit="return validateFormOnSubmit(this);">

How to set the authorization header using curl

Just adding so you don't have to click-through:

curl --user name:password http://www.example.com

or if you're trying to do send authentication for OAuth 2:

curl -H "Authorization: OAuth <ACCESS_TOKEN>" http://www.example.com

How to update value of a key in dictionary in c#?

Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5

TypeError: Cannot read property 'then' of undefined

You need to return your promise to the calling function.

islogged:function(){
    var cUid=sessionService.get('uid');
    alert("in loginServce, cuid is "+cUid);
    var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
    $checkSessionServer.then(function(){
        alert("session check returned!");
        console.log("checkSessionServer is "+$checkSessionServer);
    });
    return $checkSessionServer; // <-- return your promise to the calling function
}

Git merge reports "Already up-to-date" though there is a difference

happend to me and was sent to this page, not sure if I had the same scenario, but mine was me trying to "re-merge" that "test" branch.

So I previously merged it but I intentionally exclude some specific changes during that merge, so it clearly has some diff between branches. I was then trying to re-merge it because I realize/forget that I should have and wanted to add a particular change/file that I have previously excluded and I was hoping if I do a merge again would show all changes that I excluded before, but I was wrong and I get the "Already up-to-date" message instead.

Upon reading @Bombe's comment/answer, he is right, and git I think behaves that way, so what I did was to make hard backup of the files on test branch, then checkout the master branch and manually paste the files in it and commit it as if it was new changes.

am not sure if this is the right way or could help others having this same issue, but it did provide solution to my particular case.

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.

This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.

The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.

By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.

Getting reference to child component in parent component

You may actually go with ViewChild API...

parent.ts

<button (click)="clicked()">click</button>

export class App {
  @ViewChild(Child) vc:Child;
  constructor() {
    this.name = 'Angular2'
  }

  func(e) {
    console.log(e)

  }
  clicked(){
   this.vc.getName();
  }
}

child.ts

export class Child implements OnInit{

  onInitialized = new EventEmitter<Child>();
  ...  
  ...
  getName()
  {
     console.log('called by vc')
     console.log(this.name);
  }
}

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

using sql count in a case statement

Depending on you flavor of SQL, you can also imply the else statement in your aggregate counts.

For example, here's a simple table Grades:

| Letters |
|---------|
| A       |
| A       |
| B       |
| C       |

We can test out each Aggregate counter syntax like this (Interactive Demo in SQL Fiddle):

SELECT
    COUNT(CASE WHEN Letter = 'A' THEN 1 END)           AS [Count - End],
    COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Count - Else Null],
    COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END)    AS [Count - Else Zero],
    SUM(CASE WHEN Letter = 'A' THEN 1 END)             AS [Sum - End],
    SUM(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END)   AS [Sum - Else Null],
    SUM(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END)      AS [Sum - Else Zero]
FROM Grades

And here are the results (unpivoted for readability):

|    Description    | Counts |
|-------------------|--------|
| Count - End       |    2   |
| Count - Else Null |    2   |
| Count - Else Zero |    4   | *Note: Will include count of zero values
| Sum - End         |    2   |
| Sum - Else Null   |    2   |
| Sum - Else Zero   |    2   |

Which lines up with the docs for Aggregate Functions in SQL

Docs for COUNT:

COUNT(*) - returns the number of items in a group. This includes NULL values and duplicates.
COUNT(ALL expression) - evaluates expression for each row in a group, and returns the number of nonnull values.
COUNT(DISTINCT expression) - evaluates expression for each row in a group, and returns the number of unique, nonnull values.

Docs for SUM:

ALL - Applies the aggregate function to all values. ALL is the default.
DISTINCT - Specifies that SUM return the sum of unique values.

Where does Git store files?

For me when I run git clone, Git will store the cloned package in the directory that I am running the command from.

- I use windows.

for example :

C:\Users\user>git clone https://github.com/broosaction/aria

will create a folder:

 C:\Users\user\aria

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

Input from the keyboard in command line application

The correct way to do this is to use readLine, from the Swift Standard Library.

Example:

let response = readLine()

Will give you an Optional value containing the entered text.

Unix's 'ls' sort by name

NOTICE: "a" comes AFTER "Z":

$ touch A.txt aa.txt Z.txt

$ ls

A.txt Z.txt aa.txt

Javascript | Set all values of an array

map is the most logical solution for this problem.

let xs = [1, 2, 3];
xs = xs.map(x => 42);
xs // -> [42, 42, 42]

However, if there is a chance that the array is sparse, you'll need to use for or, even better, for .. of.

See:

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

I fixed this problem.The device system version is older then the sdk minSdkVersion? I just modified the minSdkVersion from android_L to 19 to target my nexus 4.4.4.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.12.2'
    }
}
apply plugin: 'com.android.application'

repositories {
    jcenter()
}

android {
    **compileSdkVersion 'android-L'** modified to 19
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.antwei.uiframework.ui"
        minSdkVersion 14
        targetSdkVersion 'L'
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    **compile 'com.android.support:support-v4:21.+'** modified to compile 'com.android.support:support-v4:20.0.0'
}

how to modified the value by ide. select file->Project Structure -> Facets -> android-gradle and then modified the compile Sdk Version from android_L to 19

sorry I don't have enough reputation to add pictures

Can't concat bytes to str

subprocess.check_output() returns bytes.

so you need to convert '\n' to bytes as well:

 f.write (plaintext + b'\n')

hope this helps

How can I query a value in SQL Server XML column

You could do the following

declare @role varchar(100) = 'Alpha'
select * from xmltable where convert(varchar(max),xmlfield) like '%<role>'+@role+'</role>%'

Obviously this is a bit of a hack and I wouldn't recommend it for any formal solutions. However I find this technique very useful when doing adhoc queries on XML columns in SQL Server Management Studio for SQL Server 2012.

PHP - regex to allow letters and numbers only

try this way .eregi("[^A-Za-z0-9.]", $value)

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

The reason for the exception is the re-creation of the FragmentActivity during the runtime of the AsyncTask and the access to the previous, destroyed FragmentActivity in onPostExecute() afterwards.

The problem is to get a valid reference to the new FragmentActivity. There is no method for this neither getActivity() nor findById() or something similar. This forum is full of threads according this issue (e.g. search for "Activity context in onPostExecute"). Some of them are describing workarounds (until now I didn't find a good one).

Maybe it would be a better solution to use a Service for my purpose.

How to run vi on docker container?

USE THIS:

apt-get update && apt-get install -y vim

Explanation of the above command

  1. apt-get update => Will update the current package
  2. apt-get install => Will install the package
  3. -y => Will by pass the permission, default permission will set to Yes.
  4. vim => Name of the package you want to install.

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

Got a similar error from CircleCi's error log.

"ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.3.0 but 3.3.3333 was found instead."

Just so you know this did not affect the Angular application, but the CircleCi error was becoming annoying. I am running Angular 7.1

I ran: $ npm i [email protected] --save-dev --save-exact to update the package-lock.json file.

Then I ran: $ npm i

After that I ran: $ npm audit fix

"This CircleCi error message" went away. So it works

How to find prime numbers between 0 - 100?

First, change your inner code for another loop (for and while) so you can repeat the same code for different values.

More specific for your problem, if you want to know if a given n is prime, you need to divide it for all values between 2 and sqrt(n). If any of the modules is 0, it is not prime.

If you want to find all primes, you can speed it and check n only by dividing by the previously found primes. Another way of speeding the process is the fact that, apart from 2 and 3, all the primes are 6*k plus or less 1.

How to make the main content div fill height of screen with css

There is a CSS unit called viewport height / viewport width.

Example

.mainbody{height: 100vh;} similarly html,body{width: 100vw;}

or 90vh = 90% of the viewport height.

**IE9+ and most modern browsers.

How to find the Target *.exe file of *.appref-ms

Simple answer to this; I was trying to figure out the same thing, and it just hit me.

GitHub IS a program installed on your computer, and when it runs, it WILL use threads and RAM. So that makes it a process. All you have to do is open Task Manager, click the Processes tab, find 'Github.exe', right click, Open File Location. Voila! Mine is in some App folder in Local, about 4 layers deep.

Screenshot

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

For the last Spring MVC app I wrote, I didn't inject the SecurityContext holder, but I did have a base controller that I had two utility methods related to this ... isAuthenticated() & getUsername(). Internally they do the static method call you described.

At least then it's only in once place if you need to later refactor.

Looping through a Scripting.Dictionary using index/item number

According to the documentation of the Item property:

Sets or returns an item for a specified key in a Dictionary object.

In your case, you don't have an item whose key is 1 so doing:

s = d.Item(i)

actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem argument.

The Dictionary also has the Items method which allows looping over the indices:

a = d.Items
For i = 0 To d.Count - 1
    s = a(i)
Next i

Intellij JAVA_HOME variable

If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:

  • Start your intellij from terminal /Applications/IntelliJ IDEA 14.app/Contents/MacOS (this will pick your bash env variables)
  • Add login env variable by executing: launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"

To directly answer your question, you can add launchctl line in your ~/.bash_profile

As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

You need to CAST the ParentId as an nvarchar, so that the output is always the same data type.

SELECT Id   'PatientId',
       ISNULL(CAST(ParentId as nvarchar(100)),'')  'ParentId'
FROM Patients

Pass props in Link react-router

Route:

<Route state={this.state} exact path="/customers/:id" render={(props) => <PageCustomer {...props} state={this.state} />} />

And then can access params in your PageCustomer component like this: this.props.match.params.id.

For example an api call in PageCustomer component:

axios({
   method: 'get',
   url: '/api/customers/' + this.props.match.params.id,
   data: {},
   headers: {'X-Requested-With': 'XMLHttpRequest'}
 })

How to calculate the sum of all columns of a 2D numpy array (efficiently)

a.sum(0)

should solve the problem. It is a 2d np.array and you will get the sum of all column. axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

Java - checking if parseInt throws exception

parseInt will throw NumberFormatException if it cannot parse the integer. So doing this will answer your question

try{
Integer.parseInt(....)
}catch(NumberFormatException e){
//couldn't parse
}

Code for Greatest Common Divisor in Python

def gcdIter(a, b):
gcd= min (a,b)
for i in range(0,min(a,b)):
    if (a%gcd==0 and b%gcd==0):
        return gcd
        break
    gcd-=1

Meaning of delta or epsilon argument of assertEquals for double values

The thing is that two double may not be exactly equal due to precision issues inherent to floating point numbers. With this delta value you can control the evaluation of equality based on a error factor.

Also some floating-point values can have special values like NAN and -Infinity/+Infinity which can influence results.

If you really intend to compare that two doubles are exactly equal it is best compare them as an long representation

Assert.assertEquals(Double.doubleToLongBits(expected), Double.doubleToLongBits(result));

Or

Assert.assertEquals(0, Double.compareTo(expected, result));

Which can take these nuances into account.

I have not delved into the Assert method in question, but I can only assume the previous was deprecated for this kind of issues and the new one does take them into account.

Is it safe to expose Firebase apiKey to the public?

You should not expose this info. in public, specially api keys. It may lead to a privacy leak.

Before making the website public you should hide it. You can do it in 2 or more ways

  1. Complex coding/hiding
  2. Simply put firebase SDK codes at bottom of your website or app thus firebase automatically does all works. you don't need to put API keys anywhere

Is it worth using Python's re.compile?

My understanding is that those two examples are effectively equivalent. The only difference is that in the first, you can reuse the compiled regular expression elsewhere without causing it to be compiled again.

Here's a reference for you: http://diveintopython3.ep.io/refactoring.html

Calling the compiled pattern object's search function with the string 'M' accomplishes the same thing as calling re.search with both the regular expression and the string 'M'. Only much, much faster. (In fact, the re.search function simply compiles the regular expression and calls the resulting pattern object's search method for you.)

Build a basic Python iterator

Inspired by Matt Gregory's answer here is a bit more complicated iterator that will return a,b,...,z,aa,ab,...,zz,aaa,aab,...,zzy,zzz

    class AlphaCounter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def __next__(self): # Python 3: def __next__(self)
        alpha = ' abcdefghijklmnopqrstuvwxyz'
        n_current = sum([(alpha.find(self.current[x])* 26**(len(self.current)-x-1)) for x in range(len(self.current))])
        n_high = sum([(alpha.find(self.high[x])* 26**(len(self.high)-x-1)) for x in range(len(self.high))])
        if n_current > n_high:
            raise StopIteration
        else:
            increment = True
            ret = ''
            for x in self.current[::-1]:
                if 'z' == x:
                    if increment:
                        ret += 'a'
                    else:
                        ret += 'z'
                else:
                    if increment:
                        ret += alpha[alpha.find(x)+1]
                        increment = False
                    else:
                        ret += x
            if increment:
                ret += 'a'
            tmp = self.current
            self.current = ret[::-1]
            return tmp

for c in AlphaCounter('a', 'zzz'):
    print(c)

findViewByID returns null

INFLATE THE LAYOUT !! (which contains the id)

In my case findViewById() returned null, because the layout in which the element was written, was not inflated...

Eg. fragment_layout.xml

<ListView
android:id="@+id/listview">

findViewById(R.id.listview) returned null, because I had not done inflater.inflate(R.layout.fragment_layout, ..., ...); before it.

Hope this answer helps some of y'all.

Difference between os.getenv and os.environ.get

One difference observed (Python27):

os.environ raises an exception if the environmental variable does not exist. os.getenv does not raise an exception, but returns None

Java: random long number in 0 <= x < n range

Starting from Java 7 (or Android API Level 21 = 5.0+) you could directly use ThreadLocalRandom.current().nextLong(n) (for 0 = x < n) and ThreadLocalRandom.current().nextLong(m, n) (for m = x < n). See @Alex's answer for detail.


If you are stuck with Java 6 (or Android 4.x) you need to use an external library (e.g. org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1), see @mawaldne's answer), or implement your own nextLong(n).

According to https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Random.html nextInt is implemented as

 public int nextInt(int n) {
     if (n<=0)
                throw new IllegalArgumentException("n must be positive");

     if ((n & -n) == n)  // i.e., n is a power of 2
         return (int)((n * (long)next(31)) >> 31);

     int bits, val;
     do {
         bits = next(31);
         val = bits % n;
     } while(bits - val + (n-1) < 0);
     return val;
 }

So we may modify this to perform nextLong:

long nextLong(Random rng, long n) {
   // error checking and 2^x checking removed for simplicity.
   long bits, val;
   do {
      bits = (rng.nextLong() << 1) >>> 1;
      val = bits % n;
   } while (bits-val+(n-1) < 0L);
   return val;
}

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How to close jQuery Dialog within the dialog?

Try This

$(this).closest('.ui-dialog-content').dialog('close'); 

It will close the dialog inside it.

How to check if the key pressed was an arrow key in Java KeyListener?

Just to complete the answer (using the KeyEvent is the way to go) but up arrow is 38 and down arrow is 40 so:

    else if (e.getKeyCode()==38)
    {
            //Up arrow key code
    }
    else if (e.getKeyCode()==40)
    {
            //down arrow key code
    }

Pass a javascript variable value into input type hidden value

Check out this jQuery page for some interesting examples of how to play with the value attribute, and how to call it:

http://api.jquery.com/val/

Otherwise - if you want to use jQuery rather than javascript in passing variables to an input of any kind, use the following to set the value of the input on an event click(), submit() et al:

on some event; assign or set the value of the input:

$('#inputid').val($('#idB').text());

where:

<input id = "inputid" type = "hidden" />

<div id = "idB">This text will be passed to the input</div>

Using such an approach, make sure the html input does not already specify a value, or a disabled attribute, obviously.

Beware the differences betwen .html() and .text() when dealing with html forms.

MySQL check if a table exists without throwing an exception

If you're using MySQL 5.0 and later, you could try:

SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = '[database name]' 
AND table_name = '[table name]';

Any results indicate the table exists.

From: http://www.electrictoolbox.com/check-if-mysql-table-exists/

Generate a random number in a certain range in MATLAB

Best solution is randint , but this function produce integer numbers.

You can use rand with rounding function

  r = round(a + (b-a).*rand(m,n));

This produces Real random number between a and b , size of output matrix is m*n

How to get parameters from a URL string?

A much more secure answer that I'm surprised is not mentioned here yet:

filter_input

So in the case of the question you can use this to get an email value from the URL get parameters:

$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );

For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING.

I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:

$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );

Might as well get into the habit of grabbing variables this way.

How do I get the resource id of an image if I know its name?

One other scenario which I encountered.

String imageName ="Hello" and then when it is passed into getIdentifier function as first argument, it will pass the name with string null termination and will always return zero. Pass this imageName.substring(0, imageName.length()-1)

How to iterate over array of objects in Handlebars?

This fiddle has both each and direct json. http://jsfiddle.net/streethawk707/a9ssja22/.

Below are the two ways of iterating over array. One is with direct json passing and another is naming the json array while passing to content holder.

Eg1: The below example is directly calling json key (data) inside small_data variable.

In html use the below code:

<div id="small-content-placeholder"></div>

The below can be placed in header or body of html:

<script id="small-template" type="text/x-handlebars-template">
    <table>
        <thead>
            <th>Username</th>
            <th>email</th>
        </thead>
        <tbody>
            {{#data}}
                <tr>
                    <td>{{username}}
                    </td>
                    <td>{{email}}</td>
                </tr>
            {{/data}}
        </tbody>
    </table>
</script>

The below one is on document ready:

var small_source   = $("#small-template").html();
var small_template = Handlebars.compile(small_source);

The below is the json:

var small_data = {
            data: [
                {username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                {username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" }
            ]
        };

Finally attach the json to content holder:

$("#small-content-placeholder").html(small_template(small_data));

Eg2: Iteration using each.

Consider the below json.

var big_data = [
            {
                name: "users1",
                details: [
                    {username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                    {username: "allison1", firstName: "Allison", lastName: "House", email: "[email protected]" },
                    {username: "ryan1", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
                  ]
            },
            {
                name: "users2",
                details: [
                    {username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                    {username: "allison2", firstName: "Allison", lastName: "House", email: "[email protected]" },
                    {username: "ryan2", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
                  ]
            }
      ];

While passing the json to content holder just name it in this way:

$("#big-content-placeholder").html(big_template({big_data:big_data}));

And the template looks like :

<script id="big-template" type="text/x-handlebars-template">
    <table>
        <thead>
            <th>Username</th>
            <th>email</th>
        </thead>
        <tbody>
            {{#each big_data}}
                <tr>
                    <td>{{name}}
                            <ul>
                                {{#details}}
                                    <li>{{username}}</li>
                                    <li>{{email}}</li>
                                {{/details}}
                            </ul>
                    </td>
                    <td>{{email}}</td>
                </tr>
            {{/each}}
        </tbody>
    </table>
</script>

How to get host name with port from a http or https request

If you want the original URL just use the method as described by jthalborn. If you want to rebuild the url do like David Levesque explained, here is a code snippet for it:

final javax.servlet.http.HttpServletRequest req = (javax.servlet.http.HttpServletRequest) ...;
final int serverPort = req.getServerPort();
if ((serverPort == 80) || (serverPort == 443)) {
  // No need to add the server port for standard HTTP and HTTPS ports, the scheme will help determine it.
  url = String.format("%s://%s/...", req.getScheme(), req.getServerName(), ...);
} else {
  url = String.format("%s://%s:%s...", req.getScheme(), req.getServerName(), serverPort, ...);
}

You still need to consider the case of a reverse-proxy:

Could use constants for the ports but not sure if there is a reliable source for them, default ports:

Most developers will know about port 80 and 443 anyways, so constants are not that helpful.

Also see this similar post.

In bash, how to store a return value in a variable?

It is easy you need to echo the value you need to return and then capture it like below

demofunc(){
    local variable="hellow"
    echo $variable    
}

val=$(demofunc)
echo $val

Jquery Setting Value of Input Field

use this code for set value in input tag by another id.

$(".formdata").val(document.getElementById("fsd").innerHTML);

or use this code for set value in input tag using classname="formdata"

$(".formdata").val("hello");

Convert char to int in C#

By default you use UNICODE so I suggest using faulty's method

int bar = int.Parse(foo.ToString());

Even though the numeric values under are the same for digits and basic Latin chars.

Java finished with non-zero exit value 2 - Android Gradle

This issue is quite possibly due to exceeding the 65K methods dex limit imposed by Android. This problem can be solved either by cleaning the project, and removing some unused libraries and methods from dependencies in build.gradle, OR by adding multidex support.

So, If you have to keep libraries and methods, then you can enable multi dex support by declaring it in the gradle config.

defaultConfig {        
    // Enabling multidex support.
    multiDexEnabled true
}

You can read more about multidex support and developing apps with more than 65K methods here.

What is a stack pointer used for in microprocessors?

On some CPUs, there is a dedicated set of registers for the stack. When a call instruction is executed, one register is loaded with the program counter at the same time as a second register is loaded with the contents of the first, a third register is be loaded with the second, and a fourth with the third, etc. When a return instruction is executed, the program counter is latched with the contents of the first stack register and the same time as that register is latched from the second; that second register is loaded from a third, etc. Note that such hardware stacks tend to be rather small (many the smaller PIC series micros, for example, have a two-level stack).

While a hardware stack does have some advantages (push and pop don't add any time to a call/return, for example) having registers which can be loaded with two sources adds cost. If the stack gets very big, it will be cheaper to replace the push-pull registers with an addressable memory. Even if a small dedicated memory is used for this, it's cheaper to have 32 addressable registers and a 5-bit pointer register with increment/decrement logic, than it is to have 32 registers each with two inputs. If an application might need more stack than would easily fit on the CPU, it's possible to use a stack pointer along with logic to store/fetch stack data from main RAM.

Installing Android Studio, does not point to a valid JVM installation error

Try using the above options But this one worked for me. my JAVA_HOME looked like this C:\Program Files\Java\jdk1.7.0_21;F:\Software\apache-ant-1.9.4-bin\apache-ant-1.9.4\bin Only keeping the JAVA path in the JAVA_HOME Remove any additional path if you had given C:\Program Files\Java\jdk1.7.0_21

Invalid URI: The format of the URI could not be determined

Check possible reasons here: http://msdn.microsoft.com/en-us/library/z6c2z492(v=VS.100).aspx

EDIT:

You need to put the protocol prefix in front the address, i.e. in your case "ftp://"

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

Can an Android App connect directly to an online mysql database

You can use PHP, JSP, ASP or any other server side script to connect with mysql database and and return JSON data that you can parse it to in your android app this link how to do it

Looping over elements in jQuery

Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...

$("#formID").serialize()

It creates a string for you with all of the values automatically.

As for looping through objects, you can also do this.

$.each($("input, select, textarea"), function(i,v) {
    var theTag = v.tagName;
    var theElement = $(v);
    var theValue = theElement.val();
});

Which sort algorithm works best on mostly sorted data?

Try introspective sort. http://en.wikipedia.org/wiki/Introsort

It's quicksort based, but it avoids the worst case behaviour that quicksort has for nearly sorted lists.

The trick is that this sort-algorithm detects the cases where quicksort goes into worst-case mode and switches to heap or merge sort. Nearly sorted partitions are detected by some non naiive partition method and small partitions are handled using insertion sort.

You get the best of all major sorting algorithms for the cost of a more code and complexity. And you can be sure you'll never run into worst case behaviour no matter how your data looks like.

If you're a C++ programmer check your std::sort algorithm. It may already use introspective sort internally.

Play multiple CSS animations at the same time

You can indeed run multiple animations simultaneously, but your example has two problems. First, the syntax you use only specifies one animation. The second style rule hides the first. You can specify two animations using syntax like this:

-webkit-animation-name: spin, scale
-webkit-animation-duration: 2s, 4s

as in this fiddle (where I replaced "scale" with "fade" due to the other problem explained below... Bear with me.): http://jsfiddle.net/rwaldin/fwk5bqt6/

Second, both of your animations alter the same CSS property (transform) of the same DOM element. I don't believe you can do that. You can specify two animations on different elements, the image and a container element perhaps. Just apply one of the animations to the container, as in this fiddle: http://jsfiddle.net/rwaldin/fwk5bqt6/2/

How to make an empty div take space

Simply add a zero width space character inside a pseudo element

.class:after {
    content: '\200b';
}

Convert INT to DATETIME (SQL)

Try this:

select CONVERT(datetime, convert(varchar(10), 20120103))

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

Static methods use the class as the object for locking, which is Utils.class for your example. So yes, it is OK.

How to escape % in String.Format?

Here's an option if you need to escape multiple %'s in a string with some already escaped.

(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])

To sanitise the message before passing it to String.format, you can use the following

Pattern p = Pattern.compile("(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])");
Matcher m1 = p.matcher(log);

StringBuffer buf = new StringBuffer();
while (m1.find())
    m1.appendReplacement(buf, log.substring(m1.start(), m1.start(2)) + "%%" + log.substring(m1.end(2), m1.end()));

// Return the sanitised message
String escapedString = m1.appendTail(buf).toString();

This works with any number of formatting characters, so it will replace % with %%, %%% with %%%%, %%%%% with %%%%%% etc.

It will leave any already escaped characters alone (e.g. %%, %%%% etc.)

How to track down access violation "at address 00000000"

Here is a real quick temporary fix, at least until you reboot again but it will get rid of a persistent access. I had installed a program that works fine but for some reason, there is a point that did not install correctly in the right file. So when it cannot access the file, it pops up the access denied but instead of just one, it keeps trying to start it up so even searching for the location to stop it permanently, it will continue to pop up more and more and more every 3 seconds. To stop that from happening at least temporarily, do the following...

  1. Ctl+Alt+Del
  2. Open your Task Manager
  3. Note down the name of the program that's requesting access (you may see it in your application's tab)
  4. Click on your Processes tab
  5. Scroll through until you find the Process matching the program name and click on it
  6. Click End Process

That will prevent the window from persistently popping up, at least until you reboot. I know that does not solve the problem but like anything, there is a process of elimination and this step here will at least make it a little less annoying.

JSON Naming Convention (snake_case, camelCase or PascalCase)

Notably for me on NodeJS, if I'm working with databases and my field names are underscore separated, I also use them in the struct keys.

This is because db fields have a lot of acronyms/abbreviations so something like appSNSInterfaceRRTest looks a bit messy but app_sns_interface_rr_test is nicer.

In Javascript variables are all camelCase and class names (constructors) are ProperCase, so you'd see something like

var devTask = {
        task_id: 120,
        store_id: 2118,
        task_name: 'generalLedger'
    };

or

generalLedgerTask = new GeneralLedgerTask( devTask );

And of course in JSON keys/strings are wrapped in double quotes, but then you just use the JSON.stringify and pass in JS objects, so don't need to worry about that.

I struggled with this a bit until I found this happy medium between JSON and JS naming conventions.

Forward host port to docker container

As stated in one of the comments, this works for Mac (probably for Windows/Linux too):

I WANT TO CONNECT FROM A CONTAINER TO A SERVICE ON THE HOST

The host has a changing IP address (or none if you have no network access). We recommend that you connect to the special DNS name host.docker.internal which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.

You can also reach the gateway using gateway.docker.internal.

Quoted from https://docs.docker.com/docker-for-mac/networking/

This worked for me without using --net=host.

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.

Is there a label/goto in Python?

To answer the @ascobol's question using @bobince's suggestion from the comments:

for i in range(5000):
    for j in range(3000):
        if should_terminate_the_loop:
           break
    else: 
        continue # no break encountered
    break

The indent for the else block is correct. The code uses obscure else after a loop Python syntax. See Why does python use 'else' after for and while loops?

Creating multiline strings in JavaScript

I like this syntax and indendation:

string = 'my long string...\n'
       + 'continue here\n'
       + 'and here.';

(but actually can't be considered as multiline string)

Disable/Enable Submit Button until all forms have been filled

Here is the code

<html>
   <body>
      <input type="text" name="name" id="name" required="required"                                    aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
      <script>
       function func()
       {
        var namdata=document.form1.name.value;
         if(namdata.match("[a-z]{1,5}"))
        {
         document.getElementById("but1").disabled=false;
        }
        }
        </script>
  </body>
</html>

Using Javascript

How to iterate object keys using *ngFor

1.Create a custom pipe to get keys.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'keys'
})
export class KeysPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return Object.keys(value);
  }
}
  1. In angular template file, you can use *ngFor and iterate over your object object
<div class ="test" *ngFor="let key of Obj | keys">
    {{key}}
    {{Obj[key].property}
<div>

How to check visibility of software keyboard in Android?

This is probably not suitable for production because it will open the keyboard. Note that the boolean returned by similar functions is not specified in the API and are therefore unreliable. Refer to the documentation here...

https://developer.android.com/reference/android/view/inputmethod/InputMethodManager#showSoftInput(android.view.View,%20int,%20android.os.ResultReceiver)

public boolean showSoftInput (View view, 
            int flags, 
            ResultReceiver resultReceiver)

Note that this method takes a ResultReceiver. It can get the results: RESULT_UNCHANGED_SHOWN, RESULT_UNCHANGED_HIDDEN, RESULT_SHOWN, or RESULT_HIDDEN. If you get RESULT_UNCHANGED_SHOWN, the keyboard was visible. If you need it to stay closed if it was closed, you will need to close it.

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

@NathanClement was a bit faster. Yet, here is the complete code (slightly more elaborate):

Option Explicit

Public Sub ExportWorksheetAndSaveAsCSV()

Dim wbkExport As Workbook
Dim shtToExport As Worksheet

Set shtToExport = ThisWorkbook.Worksheets("Sheet1")     'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False                       'Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\tmp\test.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False

End Sub

How to connect to my http://localhost web server from Android Emulator

You can actually use localhost:8000 to connect to your machine's localhost by running below command each time when you run your emulator (tested on Mac only):

adb reverse tcp:8000 tcp:8000

Just put it to Android Studio terminal.

It basically sets up a reverse proxy in which a http server running on your phone accepts connections on a port and wires them to your computer or vice versa.

Python, Matplotlib, subplot: How to set the axis range?

If you know the exact axis you want, then

pylab.ylim([0,1000])

works as answered previously. But if you want a more flexible axis to fit your exact data, as I did when I found this question, then set axis limit to be the length of your dataset. If your dataset is fft as in the question, then add this after your plot command:

length = (len(fft)) pylab.ylim([0,length])

How do I pass data to Angular routed components?

It is 2019 and many of the answers here would work, depending on what you want to do. If you want to pass in some internal state not visible in URL (params, query) you can use state since 7.2 (as I have learned just today :) ).

From the blog (credits Tomasz Kula) - you navigate to route....

...from ts: this.router.navigateByUrl('/details', { state: { hello: 'world' } });

...from HTML template: <a routerLink="/details" [state]="{ hello: 'world' }">Go</a>

And to pick it up in the target component:

constructor(public activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.state$ = this.activatedRoute.paramMap
      .pipe(map(() => window.history.state))
  }

Late, but hope this helps someone with recent Angular.

How to convert time milliseconds to hours, min, sec format in JavaScript?

How about doing this by creating a function in javascript as shown below:

_x000D_
_x000D_
function msToTime(duration) {_x000D_
  var milliseconds = parseInt((duration % 1000) / 100),_x000D_
    seconds = Math.floor((duration / 1000) % 60),_x000D_
    minutes = Math.floor((duration / (1000 * 60)) % 60),_x000D_
    hours = Math.floor((duration / (1000 * 60 * 60)) % 24);_x000D_
_x000D_
  hours = (hours < 10) ? "0" + hours : hours;_x000D_
  minutes = (minutes < 10) ? "0" + minutes : minutes;_x000D_
  seconds = (seconds < 10) ? "0" + seconds : seconds;_x000D_
_x000D_
  return hours + ":" + minutes + ":" + seconds + "." + milliseconds;_x000D_
}_x000D_
console.log(msToTime(300000))
_x000D_
_x000D_
_x000D_

conversion from infix to prefix

(a–b)/c*(d + e – f / g)

step 1: (a-b)/c*(d+e- /fg))

step 2: (a-b)/c*(+de - /fg)

step 3: (a-b)/c * -+de/fg

Step 4: -ab/c * -+de/fg

step 5: /-abc * -+de/fg

step 6: */-abc-+de/fg

This is prefix notation.

Failed to start mongod.service: Unit mongod.service not found

For those that run into this and end up on this answer, as I did, where they got this error during uninstall orupgrade and Ubuntu keeps failing to uninstall the previous because the service doesn't exist this one line will get you past that and allow the uninstall or upgrade to continue.

sudo touch /lib/systemd/system/mongod.service

What is the best project structure for a Python application?

The "Python Packaging Authority" has a sampleproject:

https://github.com/pypa/sampleproject

It is a sample project that exists as an aid to the Python Packaging User Guide's Tutorial on Packaging and Distributing Projects.

Generic deep diff between two objects

I know I'm late to the party, but I needed something similar that the above answers didn't help.

I was using Angular's $watch function to detect changes in a variable. Not only did I need to know whether a property had changed on the variable, but I also wanted to make sure that the property that changed was not a temporary, calculated field. In other words, I wanted to ignore certain properties.

Here's the code: https://jsfiddle.net/rv01x6jo/

Here's how to use it:

// To only return the difference
var difference = diff(newValue, oldValue);  

// To exclude certain properties
var difference = diff(newValue, oldValue, [newValue.prop1, newValue.prop2, newValue.prop3]);

Hope this helps someone.

Best method to download image from url in Android

First Declare Permission in Android Manifest:-

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

MainActivityForDownloadImages.java

public class MainActivityForDownloadImages extends AppCompatActivity {


//    String urls = "https://stimg.cardekho.com/images/carexteriorimages/930x620/Kia/Kia-Seltos/6232/1562746799300/front-left-side-47.jpg";
    String urls = "https://images5.alphacoders.com/609/609173.jpg";
    Button button;
     public final Context context = this;
    ProgressDialog progressDialog ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_for_download_images);
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
        }


        progressDialog = new ProgressDialog(context);
        button = findViewById(R.id.downloadImagebtn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // initialize the progress dialog like in the first example
                // this is how you fire the downloader

                Intent intent = new Intent(context, DownloadService.class);
                intent.putExtra("url", urls);
                intent.putExtra("receiver", new DownloadReceiver(new Handler()));
                startService(intent);


            }
        });


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {


            }
        }
    }

    private class DownloadReceiver extends ResultReceiver {

        public DownloadReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {

            super.onReceiveResult(resultCode, resultData);

            if (resultCode == DownloadService.UPDATE_PROGRESS) {

                int progress = resultData.getInt("progress"); //get the progress
                progressDialog.setProgress(progress);
                progressDialog.setMessage("Images Is Downloading");
                progressDialog.show();

                if (progress == 100) {

                    progressDialog.dismiss();

                }
            }
        }
    }

}

DownloadService.java

public class DownloadService extends IntentService {

public static final int UPDATE_PROGRESS = 8344;
String folder_main = "ImagesFolder";


public DownloadService() {
    super("DownloadService");
}


@Override
protected void onHandleIntent(Intent intent) {

    String urlToDownload = intent.getStringExtra("url");
    ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");

    try {

        //create url and connect
        URL url = new URL(urlToDownload);
        URLConnection connection = url.openConnection();
        connection.connect();

        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(connection.getInputStream());


        File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
        File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");


        if (!outerFolder.exists()) {
            outerFolder.mkdirs();
        }

        inerDire.createNewFile();


        FileOutputStream output = new FileOutputStream(inerDire);

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;

            // publishing the progress....
            Bundle resultData = new Bundle();
            resultData.putInt("progress", (int) (total * 100 / fileLength));
            receiver.send(UPDATE_PROGRESS, resultData);
            output.write(data, 0, count);
        }

        // close streams
        output.flush();
        output.close();
        input.close();

    } catch (IOException e) {
        e.printStackTrace();

    }

    Bundle resultData = new Bundle();
    resultData.putInt("progress", 100);

    receiver.send(UPDATE_PROGRESS, resultData);
}

}

How to Remove Array Element and Then Re-Index Array?

array_splice($array, array_search(array_value, $array), 1);

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

ORA-12170: TNS:Connect timeout occurred

I was getting the same error while connecting my "hr" user of ORCLPDB which is a pluggable database.

First, get hostname and port number by typing a command lsnrctl status on windows command prompt. In my case, it was 127.0.0.1 with port number as 1521

Second, enter the below command with your hostname and port number:

sqlplus username/password@HostName:Port Number/PluggableDatabaseName.

For example:

sqlplus hr/[email protected]:1521/ORCLPDB.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

set <ORACLE_HOME> path variable

example

path ORACLE_HOME

value is C:\oraclexe\app\oracle\product\10.2.0\server

enter image description here

Usage of @see in JavaDoc?

I use @see to annotate methods of an interface implementation class where the description of the method is already provided in the javadoc of the interface. When we do that I notice that Eclipse pulls up the interface's documentation even when I am looking up method on the implementation reference during code complete

What is a Memory Heap?

Presumably you mean heap from a memory allocation point of view, not from a data structure point of view (the term has multiple meanings).

A very simple explanation is that the heap is the portion of memory where dynamically allocated memory resides (i.e. memory allocated via malloc). Memory allocated from the heap will remain allocated until one of the following occurs:

  1. The memory is free'd
  2. The program terminates

If all references to allocated memory are lost (e.g. you don't store a pointer to it anymore), you have what is called a memory leak. This is where the memory has still been allocated, but you have no easy way of accessing it anymore. Leaked memory cannot be reclaimed for future memory allocations, but when the program ends the memory will be free'd up by the operating system.

Contrast this with stack memory which is where local variables (those defined within a method) live. Memory allocated on the stack generally only lives until the function returns (there are some exceptions to this, e.g. static local variables).

You can find more information about the heap in this article.

How do I pass multiple parameters in Objective-C?

Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray at a certain index, you would do it using the method:

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;

This method is called insertObject:atIndex: and it is clear that an object is being inserted at a specified index.

In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray called array would be called as follows:

NSString *obj = @"Hello, World!";
int index = 5;

[array insertObject:obj atIndex:index];

This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.

Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber class; this has several object creation methods, including:

  • + (id)numberWithBool:(BOOL)value;
  • + (id)numberWithFloat:(float)value;
  • + (id)numberWithDouble:(double)value;

In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.

How do I call an Angular.js filter with multiple arguments?

In this code, jsondata is our array and in function return we are checking the 'version' present in the jsondata.

var as = $filter('filter')(jsondata, function (n,jsondata){
   return n.filter.version==='V.0.3'
});

console.log("name is " + as[0].name+as[0]); 

Get startup type of Windows service using PowerShell

It is possible with PowerShell 4.

Get-Service *spool* | select name,starttype | ft -AutoSize

screenshot

Compare two files line by line and generate the difference in another file

diff(1) is not the answer, but comm(1) is.

NAME
       comm - compare two sorted files line by line

SYNOPSIS
       comm [OPTION]... FILE1 FILE2

...

       -1     suppress lines unique to FILE1

       -2     suppress lines unique to FILE2

       -3     suppress lines that appear in both files

So

comm -2 -3 file1 file2 > file3

The input files must be sorted. If they are not, sort them first. This can be done with a temporary file, or...

comm -2 -3 <(sort file1) <(sort file2) > file3

provided that your shell supports process substitution (bash does).

Cannot connect to SQL Server named instance from another SQL Server

I need to do 2 things to connect with instance name

1. Enable SQL Server Browser (in SQL server config manager)
2. Enable UDP, port 1434 trong file wall (if you using amazon EC2 or other service you need open port in their setting too)

Restart sql and done

Is Tomcat running?

Since my tomcat instances are named as tomcat_ . For example. tomcat_8086, I use

#

ps aux | grep tomcat

Other method is using nc utility

nc -l 8086 (port number )

Or

ps aux | grep java

Write objects into file with Node.js

If you're geting [object object] then use JSON.stringify

fs.writeFile('./data.json', JSON.stringify(obj) , 'utf-8');

It worked for me.

Table columns, setting both min and max width with css

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

_x000D_
_x000D_
table {_x000D_
  width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
  border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  min-width: 10px;_x000D_
  width: 20px;_x000D_
  max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  min-width: 40px;_x000D_
  width: 45px;_x000D_
  max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="a">A</td>_x000D_
    <td class="b">B</td>_x000D_
    <td class="c">C</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Can I get the name of the currently running function in JavaScript?

This should do it:

var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
alert(fn[1]);

For the caller, just use caller.toString().

Simple and clean way to convert JSON string to Object in Swift

It might be help someone. Similar example.

This is our Codable class to bind data. You can easily create this class using SwiftyJsonAccelerator

 class ModelPushNotificationFilesFile: Codable {

  enum CodingKeys: String, CodingKey {
    case url
    case id
    case fileExtension = "file_extension"
    case name
  }

  var url: String?
  var id: Int?
  var fileExtension: String?
  var name: String?

  init (url: String?, id: Int?, fileExtension: String?, name: String?) {
    self.url = url
    self.id = id
    self.fileExtension = fileExtension
    self.name = name
  }

  required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    url = try container.decodeIfPresent(String.self, forKey: .url)
    id = try container.decodeIfPresent(Int.self, forKey: .id)
    fileExtension = try container.decodeIfPresent(String.self, forKey: .fileExtension)
    name = try container.decodeIfPresent(String.self, forKey: .name)
  }

}

This is Json String

    let jsonString = "[{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/tulips.png\"},

{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/arctichare.png\"},

{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/serrano.png\"},

{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/peppers.png\"},

{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/pool.png\"}]"

Here we convert to swift object.

   let jsonData = Data(jsonString.utf8)

        let decoder = JSONDecoder()

        do {
            let fileArray = try decoder.decode([ModelPushNotificationFilesFile].self, from: jsonData)
            print(fileArray)
            print(fileArray[0].url)
        } catch {
            print(error.localizedDescription)
        }

Simple calculations for working with lat/lon and km distance?

Thanks Jim Lewis for his great answer and I would like to illustrate this solution by my function in Swift:

func getRandomLocation(forLocation location: CLLocation, withOffsetKM offset: Double) -> CLLocation {
        let latDistance = (Double(arc4random()) / Double(UInt32.max)) * offset * 2.0 - offset
        let longDistanceMax = sqrt(offset * offset - latDistance * latDistance)
        let longDistance = (Double(arc4random()) / Double(UInt32.max)) * longDistanceMax * 2.0 - longDistanceMax

        let lat: CLLocationDegrees = location.coordinate.latitude + latDistance / 110.574
        let lng: CLLocationDegrees = location.coordinate.longitude + longDistance / (111.320 * cos(lat / .pi / 180))
        return CLLocation(latitude: lat, longitude: lng)
    }

In this function to convert distance I use following formulas:

latDistance / 110.574
longDistance / (111.320 * cos(lat / .pi / 180))

Bootstrap - Removing padding or margin when screen size is smaller

Another css that can make the margin problem is that you have direction:someValue in your css, so just remove it by setting it to initial.

For example:

body {
     direction:rtl;
 }
@media (max-width: 480px) {
    body {
     direction:initial;
    }
}

Presenting modal in iOS 13 fullscreen

Change modalPresentationStyle before presenting

vc.modalPresentationStyle = UIModalPresentationFullScreen;

'node' is not recognized as an internal or external command

Watch out for other paths ending in \ too. I had this:

...bin;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files\nodejs\

and changed it to this:

bin;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files\nodejs

removing the final \, but it still didn't work. The previous path, for the Web Platform Installer, had a trailing \ too. Removing that fixed the problem.

Convert date yyyyMMdd to system.datetime format

string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
                                        "yyyyMMdd",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.None);

Styling Password Fields in CSS

When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)

SCSS styles

@font-face {
  font-family: 'pass';
  font-style: normal;
  font-weight: 400;
  src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}

input.password {
  font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
  font-size: 18px;
  &::-webkit-input-placeholder {
    transform: scale(0.77);
    transform-origin: 0 50%;
  }
  &::-moz-placeholder {
    font-size: 14px;
    opacity: 1;
  }
  &:-ms-input-placeholder {
    font-size: 14px;
    font-family: 'Roboto', Helvetica, Arial, sans-serif;
  }

After that, I got identical display input[password]

What are "named tuples" in Python?

In Python inside there is a good use of container called a named tuple, it can be used to create a definition of class and has all the features of the original tuple.

Using named tuple will be directly applied to the default class template to generate a simple class, this method allows a lot of code to improve readability and it is also very convenient when defining a class.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You can use it without casting such as:

select sum(`stuff`) as mySum from test;

Or cast it to decimal:

select sum(cast(`stuff` as decimal(4,2))) as mySum from test;

SQLFiddle

EDIT

For SQL Server, you can use:

select sum(cast(stuff as decimal(5,2))) as mySum from test;

SQLFiddle

How can I change Eclipse theme?

Eclipse... To just get everything done goto Window>Preferences>General and goto theme menu and change it... Then re-start to apply...

Get month name from number

I created my own function converting numbers to their corresponding month.

def month_name (number):
    if number == 1:
        return "January"
    elif number == 2:
        return "February"
    elif number == 3:
        return "March"
    elif number == 4:
        return "April"
    elif number == 5:
        return "May"
    elif number == 6:
        return "June"
    elif number == 7:
        return "July"
    elif number == 8:
        return "August"
    elif number == 9:
        return "September"
    elif number == 10:
        return "October"
    elif number == 11:
        return "November"
    elif number == 12:
        return "December"

Then I can call the function. For example:

print (month_name (12))

Outputs:

>>> December

How do servlets work? Instantiation, sessions, shared variables and multithreading

Sessions - what Chris Thompson said.

Instantiation - a servlet is instantiated when the container receives the first request mapped to the servlet (unless the servlet is configured to load on startup with the <load-on-startup> element in web.xml). The same instance is used to serve subsequent requests.

Use find command but exclude files in two directories

Try something like

find . \( -type f -name \*_peaks.bed -print \) -or \( -type d -and \( -name tmp -or -name scripts \) -and -prune \)

and don't be too surprised if I got it a bit wrong. If the goal is an exec (instead of print), just substitute it in place.

How can I get all sequences in an Oracle database?

You may not have permission to dba_sequences. So you can always just do:

select * from user_sequences;

System.Data.SqlClient.SqlException: Login failed for user

Numpty here used SQL authentication

enter image description here

instead of Windows (correct)

enter image description here

when adding the login to SQL Server, which also gives you this error if you are using Windows auth.

How to initialize an array in angular2 and typescript

you can create and initialize array of any object like this.

hero:Hero[]=[];

Combining (concatenating) date and time into a datetime

Concat date of one column with a time of another column in MySQL.

SELECT CONVERT(concat(CONVERT('dateColumn',DATE),' ',CONVERT('timeColumn', TIME)), DATETIME) AS 'formattedDate' FROM dbs.tableName;

jQuery get html of container including the container itself

Firefox doesn't support outerHTML, so you need to define a function to help support it:

function outerHTML(node) {
    return node.outerHTML || (
        function(n) {
            var div = document.createElement('div');
            div.appendChild( n.cloneNode(true) );
            var h = div.innerHTML;
            div = null;
            return h;
        }
    )(node);
}

Then, you can use outerHTML:

var x = outerHTML($('#container').get(0));
$('#save').val(x);

PHP Array to JSON Array using json_encode();

I want to add to Michael Berkowski's answer that this can also happen if the array's order is reversed, in which case it's a bit trickier to observe the issue, because in the json object, the order will be ordered ascending.

For example:

[
    3 => 'a',
    2 => 'b',
    1 => 'c',
    0 => 'd'
]

Will return:

{
    0: 'd',
    1: 'c',
    2: 'b',
    3: 'a'
}

So the solution in this case, is to use array_reverse before encoding it to json

Does Spring @Transactional attribute work on a private method?

If you need to wrap a private method inside a transaction and don't want to use aspectj, you can use TransactionTemplate.

@Service
public class MyService {

    @Autowired
    private TransactionTemplate transactionTemplate;

    private void process(){
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                processInTransaction();
            }
        });

    }

    private void processInTransaction(){
        //...
    }

}

Error "The connection to adb is down, and a severe error has occurred."

I know this question has already been answered, but thought I might add that I found the problem to be folder permissions on my android-sdk directory.

I tested it out by granting Full Control to Everyone (dodgy, I know...), and the problem went away. I am not sure yet what the specific mix of permissions might be that it was looking for, but I assume some or other service in Eclipse didn't have execute permissions on adb.exe. That said, I'm a complete noob to this - just wanted to put it out there in case someone else had some insights into this.

I am running Windows 7, 64-bit, 4.2.0 Eclipse, and 20.0.0v201206242043 ADT.

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Actually, the solutions is to open the php.ini file edit the include_path line and either completely change it to

include_path='.:/usr/share/php:/usr/share/pear' 

or append the

'.:/usr/share/php:/usr/share/pear' 

to the current value of include_path.

It is further explained in : http://pear.php.net/manual/en/installation.checking.php#installation.checking.cli.phpdir

Animate the transition between fragments

Nurik's answer was very helpful, but I couldn't get it to work until I found this. In short, if you're using the compatibility library (eg SupportFragmentManager instead of FragmentManager), the syntax of the XML animation files will be different.

How to use apply a custom drawable to RadioButton?

Give your radiobutton a custom style:

<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:button">@drawable/custom_btn_radio</item>
</style>

custom_btn_radio.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_on" />
    <item android:state_checked="false" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_off" />

    <item android:state_checked="true" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_on_pressed" />
    <item android:state_checked="false" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_off_pressed" />

    <item android:state_checked="true" android:state_focused="true"
          android:drawable="@drawable/btn_radio_on_selected" />
    <item android:state_checked="false" android:state_focused="true"
          android:drawable="@drawable/btn_radio_off_selected" />

    <item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
    <item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>

Replace the drawables with your own.

How to compare pointers?

For a bit of facts here is the relevant text from the specifications

Equality operator (==,!=)

Pointers to objects of the same type can be compared for equality with the 'intuitive' expected results:

From § 5.10 of the C++11 standard:

Pointers of the same type (after pointer conversions) can be compared for equality. Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address (3.9.2).

(leaving out details on comparison of pointers to member and or the null pointer constants - they continue down the same line of 'Do What I Mean':)

  • [...] If both operands are null, they compare equal. Otherwise if only one is null, they compare unequal.[...]

The most 'conspicuous' caveat has to do with virtuals, and it does seem to be the logical thing to expect too:

  • [...] if either is a pointer to a virtual member function, the result is unspecified. Otherwise they compare equal if and only if they would refer to the same member of the same most derived object (1.8) or the same subobject if they were dereferenced with a hypothetical object of the associated class type. [...]

Relational operators (<,>,<=,>=)

From § 5.9 of the C++11 standard:

Pointers to objects or functions of the same type (after pointer conversions) can be compared, with a result defined as follows:

  1. If two pointers p and q of the same type point to the same object or function, or both point one past the end of the same array, or are both null, then p<=q and p>=q both yield true and p<q and p>q both yield false.
  2. If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of p<q, p>q, p<=q, and p>=q are unspecified.
  3. If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, recursively, the pointer to the later declared member compares greater provided the two members have the same access control (Clause 11) and provided their class is not a union.
  4. If two pointers point to non-static data members of the same object with different access control (Clause 11) the result is unspecified.
  5. If two pointers point to non-static data members of the same union object, they compare equal (after conversion to void*, if necessary). If two pointers point to elements of the same array or one beyond the end of the array, the pointer to the object with the higher subscript compares higher.
  6. Other pointer comparisons are unspecified.

So, if you had:

int arr[3];
int *a = arr;
int *b = a + 1;
assert(a != b); // OK! well defined

Also OK:

struct X { int x,y; } s;
int *a = &s.x;
int *b = &s.y;
assert(b > a); // OK! well defined

But it depends on the something in your question:

int g; 
int main()
{
     int h;
     int i;

     int *a = &g;
     int *b = &h; // can't compare a <=> b
     int *c = &i; // can't compare b <=> c, or a <=> c etc.
     // but a==b, b!=c, a!=c etc. are supported just fine
}

Bonus: what else is there in the standard library?

§ 20.8.5/8: "For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not."

So, you can globally order any odd void* as long as you use std::less<> and friends, not bare operator<.

Changing the tmp folder of mysql

Here is an example to move the mysqld tmpdir from /tmp to /run/mysqld which already exists on Ubuntu 13.04 and is a tmpfs (memory/ram):

sudo vim /etc/mysql/conf.d/local.cnf

Add:

[mysqld]
tmpdir = /run/mysqld

Then:

sudo service mysql restart

Verify:

SHOW VARIABLES LIKE 'tmpdir';

==================================================================

If you get an error on MySQL restart, you may have AppArmor enabled:

sudo vim /etc/apparmor.d/local/usr.sbin.mysqld

Add:

# Site-specific additions and overrides for usr.sbin.mysqld.
# For more details, please see /etc/apparmor.d/local/README.
/run/mysqld/ r,
/run/mysqld/** rwk,

Then:

sudo service apparmor reload 

sources: http://2bits.com/articles/reduce-your-servers-resource-usage-moving-mysql-temporary-directory-ram-disk.html, https://blogs.oracle.com/jsmyth/entry/apparmor_and_mysql

Understanding checked vs unchecked exceptions in Java

Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?

For example let say you have some client-server application and client had made a request for some resource that couldn't be find out or for something else error some might have occurred at the server side while processing the user request then it is the duty of the server to tell the client why he couldn't get the thing he requested for,so to achieve that at server side, code is written to throw the exception using throw keyword instead of swallowing or handling it.if server handles it/swallow it, then there will be no chance of intimating to the client that what error had occurred.

Note:To give a clear description of what the error type has occurred we can create our own Exception object and throw it to the client.

Is there any WinSCP equivalent for linux?

scp file user@host:/path/on/host

ssl.SSLError: tlsv1 alert protocol version

Another source of this problem: I found that in Debian 9, the Python httplib2 is hardcoded to insist on TLS v1.0. So any application that uses httplib2 to connect to a server that insists on better security fails with TLSV1_ALERT_PROTOCOL_VERSION.

I fixed it by changing

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)

to

context = ssl.SSLContext()

in /usr/lib/python3/dist-packages/httplib2/__init__.py .

Debian 10 doesn't have this problem.

Maven2: Missing artifact but jars are in place

My problem: I forgot to import a newly added project (added by my co-worker) into my eclipse workspace.

File > Import > Maven > Existing Maven Projects, find it in the dir-tree, check the single non-ghosted one which is not already added.

Details: My co-worker had added a new project which was a git submodule. Existing projects referred to it in their pom.xml. I had already done "git submodule init" and "git submodule update". mvn built fine from the command-line but I kept getting this "Missing artifact" error in eclipse pointing at the top of my pom.xml.

Two models in one view in ASP MVC 3

ok, everyone is making sense and I took all the pieces and put them here to help newbies like myself that need beginning to end explanation.

You make your big class that holds 2 classes, as per @Andrew's answer.

public class teamBoards{
    public Boards Boards{get; set;}
    public Team Team{get; set;}
}

Then in your controller you fill the 2 models. Sometimes you only need to fill one. Then in the return, you reference the big model and it will take the 2 inside with it to the View.

            TeamBoards teamBoards = new TeamBoards();


        teamBoards.Boards = (from b in db.Boards
                               where b.TeamId == id
                               select b).ToList();
        teamBoards.Team = (from t in db.Teams
                              where t.TeamId == id
                          select t).FirstOrDefault();

 return View(teamBoards);

At the top of the View

@model yourNamespace.Models.teamBoards

Then load your inputs or displays referencing the big Models contents:

 @Html.EditorFor(m => Model.Board.yourField)
 @Html.ValidationMessageFor(m => Model.Board.yourField, "", new { @class = "text-danger-yellow" })

 @Html.EditorFor(m => Model.Team.yourField)
 @Html.ValidationMessageFor(m => Model.Team.yourField, "", new { @class = "text-danger-yellow" })

And. . . .back at the ranch, when the Post comes in, reference the Big Class:

 public ActionResult ContactNewspaper(teamBoards teamboards)

and make use of what the model(s) returned:

string yourVariable = teamboards.Team.yourField;

Probably have some DataAnnotation Validation stuff in the class and probably put if(ModelState.IsValid) at the top of the save/edit block. . .

Simple CSS: Text won't center in a button

As a more brute force method that I found worked for me:

First wrap the text inside the button in a span, and then apply this css to that span

var spanStyle = {
      position: "absolute",
      top: "50%",
      left: "50%",
      transform: "translate(-50%, -50%)"
    }

*above setup for inline styling

mysql datatype for telephone number and address

I usually store phone numbers as a BIGINT in E164 format.

E164 never start with a 0, with the first few digits being the country code.

+441234567890
+44 (0)1234 567890
01234 567890

etc. would be stored as 441234567890.

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

Calculate compass bearing / heading to location in Android

I am in the process of figuring it out now but it seems as though the math depends on where you and your target are on the earth relative to true and magnetic North. For example:

float thetaMeThem = 0.0;
if (myLocation.bearingTo(targetLocation) > myLocation.getBearing()){ 
     thetaMeThem = myLocation.bearingTo(targetLocation) - azimuth + declination;} 

See Sensor.TYPE_ORIENTATION for azimuth.

See getDeclination() for declination

This assumes declination is negative (west of true north) and theirBearing > yourBearing.

If declination is positive and yourBearing > theirBearing another option:

float thetaMeThem = 0.0;
if (myLocation.bearingTo(targetLocation) < myLocation.getBearing()){ 
     thetaMeThem = azimuth - (myLocation.bearingTo(targetLocation) - declination);} 

I haven't tested this fully but playing with the angles on paper got me here.

How to iterate over a std::map full of strings in C++

Another worthy optimization is the c_str ( ) member of the STL string classes, which returns an immutable null terminated string that can be passed around as a LPCTSTR, e. g., to a custom function that expects a LPCTSTR. Although I haven't traced through the destructor to confirm it, I suspect that the string class looks after the memory in which it creates the copy.

Add a UIView above all, even the navigation bar

You can do that by adding your view directly to the keyWindow:

UIView *myView = /* <- Your custom view */;
UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
[currentWindow addSubview:myView];

UPDATE -- For Swift 4.1 and above

let currentWindow: UIWindow? = UIApplication.shared.keyWindow
currentWindow?.addSubview(myView)

UPDATE for iOS13 and above

keyWindow is deprecated. You should use the following:

UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.addSubview(myView)

What is difference between XML Schema and DTD?

Differences between an XML Schema Definition (XSD) and Document Type Definition (DTD) include:

  • XML schemas are written in XML while DTD are derived from SGML syntax.
  • XML schemas define datatypes for elements and attributes while DTD doesn't support datatypes.
  • XML schemas allow support for namespaces while DTD does not.
  • XML schemas define number and order of child elements, while DTD does not.
  • XML schemas can be manipulated on your own with XML DOM but it is not possible in case of DTD.
  • using XML schema user need not to learn a new language but working with DTD is difficult for a user.
  • XML schema provides secure data communication i.e sender can describe the data in a way that receiver will understand, but in case of DTD data can be misunderstood by the receiver.
  • XML schemas are extensible while DTD is not extensible.

Not all these bullet points are 100% accurate, but you get the gist.

On the other hand:

  • DTD lets you define new ENTITY values for use in your XML file.
  • DTD lets you extend it local to an individual XML file.

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

Clearing coverage highlighting in Eclipse

I have used the Open Clover Tool for the code coverage, I have also been searching this for a long time. Its pretty straightforward, in the Coverage Explorer tab, you can find three square buttons which says the code lines you wanted to display, click on hide the coverage square box and its gone. Last button in the image below: enter image description here