Programs & Examples On #Access synchronization

Process of establishing consistency among systems and subsequent continuous updates to maintain consistency.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

My guess is it's an encoding problem, for instance your file is UTF-8 but SQL will not read it the way it should, so it attempts to insert 100ÿ or something along these lines into your table.

Possible fixes:

  1. Specify Codepage
  2. Change the Encoding of the source using Powershell

Code samples:

1.
BULK INSERT myTable FROM 'c:\Temp\myfile.csv' WITH (
  FIELDTERMINATOR = '£',
  ROWTERMINATOR = '\n',
  CODEPAGE = 'ACP' -- ACP corresponds to ANSI, also try UTF-8 or 65001 for Unicode
);

2.
get-content "myfile.csv" | Set-content -Path "myfile.csv" -Encoding String
# String = ANSI, also try Ascii, Oem, Unicode, UTF7, UTF8, UTF32

How to make android listview scrollable?

Never put ListView in ScrollView. ListView itself is scrollable.

Retrofit 2.0 how to get deserialised error response.body

This way you do not need a Retrofit instance if you only are injecting a service created from Retrofit.

public class ErrorUtils {

  public static APIError parseError(Context context, Response<?> response) {

    APIError error = new APIError();

    try {
        Gson gson = new Gson();
        error = gson.fromJson(response.errorBody().charStream(), APIError.class);
    } catch (Exception e) {
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
    }

    if (TextUtils.isEmpty(error.getErrorMessage())) {
        error.setError(response.raw().message());
    }
    return error;
  }
}

Use it like this:

if (response.isSuccessful()) {

      ...

    } else {

      String msg = ErrorUtils.parseError(fragment.getActivity(), response).getError(); // would be from your error class
      Snackbar.make(someview, msg, Snackbar.LENGTH_LONG).show();
    }
  }

I have never set any passwords to my keystore and alias, so how are they created?

Signing in Debug Mode

The Android build tools provide a debug signing mode that makes it easier for you to develop and debug your application, while still meeting the Android system requirement for signing your APK. When using debug mode to build your app, the SDK tools invoke Keytool to automatically create a debug keystore and key. This debug key is then used to automatically sign the APK, so you do not need to sign the package with your own key.

The SDK tools create the debug keystore/key with predetermined names/passwords:

Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
CN: "CN=Android Debug,O=Android,C=US"

If necessary, you can change the location/name of the debug keystore/key or supply a custom debug keystore/key to use. However, any custom debug keystore/key must use the same keystore/key names and passwords as the default debug key (as described above). (To do so in Eclipse/ADT, go to Windows > Preferences > Android > Build.)

Caution: You cannot release your application to the public when signed with the debug certificate.

Source: Developer.Android

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

You can also try this:

try {
    Class res = R.drawable.class;
    Field field = res.getField("drawableName");
    int drawableId = field.getInt(null);
}
catch (Exception e) {
    Log.e("MyTag", "Failure to get drawable id.", e);
}

I have copied this source codes from below URL. Based on tests done in this page, it is 5 times faster than getIdentifier(). I also found it more handy and easy to use. Hope it helps you as well.

Link: Dynamically Retrieving Resources in Android

Sorting a Python list by two fields

No need to import anything when using lambda functions.
The following sorts list by the first element, then by the second element.

sorted(list, key=lambda x: (x[0], -x[1]))

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using Microsoft.Office.Interop.Excel;

namespace trg.satmap.portal.ParseAgentSkillMapping
{
    class ConvertXLStoDT
    {
        private StringBuilder errorMessages;

        public StringBuilder ErrorMessages
        {
            get { return errorMessages; }
            set { errorMessages = value; }
        }

        public ConvertXLStoDT()
        {
            ErrorMessages = new StringBuilder();
        }

        public System.Data.DataTable XLStoDTusingInterOp(string FilePath)
        {
            #region Excel important Note.
            /*
             * Excel creates XLS and XLSX files. These files are hard to read in C# programs. 
             * They are handled with the Microsoft.Office.Interop.Excel assembly. 
             * This assembly sometimes creates performance issues. Step-by-step instructions are helpful.
             * 
             * Add the Microsoft.Office.Interop.Excel assembly by going to Project -> Add Reference.
             */
            #endregion

            Microsoft.Office.Interop.Excel.Application excelApp = null;
            Microsoft.Office.Interop.Excel.Workbook workbook = null;


            System.Data.DataTable dt = new System.Data.DataTable(); //Creating datatable to read the content of the Sheet in File.

            try
            {

                excelApp = new Microsoft.Office.Interop.Excel.Application(); // Initialize a new Excel reader. Must be integrated with an Excel interface object.

                //Opening Excel file(myData.xlsx)
                workbook = excelApp.Workbooks.Open(FilePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);

                Microsoft.Office.Interop.Excel.Range excelRange = ws.UsedRange; //gives the used cells in sheet

                ws = null; // now No need of this so should expire.

                //Reading Excel file.               
                object[,] valueArray = (object[,])excelRange.get_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault);

                excelRange = null; // you don't need to do any more Interop. Now No need of this so should expire.

                dt = ProcessObjects(valueArray);                

            }
            catch (Exception ex)
            {
                ErrorMessages.Append(ex.Message);
            }
            finally
            {
                #region Clean Up                
                if (workbook != null)
                {
                    #region Clean Up Close the workbook and release all the memory.
                    workbook.Close(false, FilePath, Missing.Value);                    
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                    #endregion
                }
                workbook = null;

                if (excelApp != null)
                {
                    excelApp.Quit();
                }
                excelApp = null;                

                #endregion
            }
            return (dt);
        }

        /// <summary>
        /// Scan the selected Excel workbook and store the information in the cells
        /// for this workbook in an object[,] array. Then, call another method
        /// to process the data.
        /// </summary>
        private void ExcelScanIntenal(Microsoft.Office.Interop.Excel.Workbook workBookIn)
        {
            //
            // Get sheet Count and store the number of sheets.
            //
            int numSheets = workBookIn.Sheets.Count;

            //
            // Iterate through the sheets. They are indexed starting at 1.
            //
            for (int sheetNum = 1; sheetNum < numSheets + 1; sheetNum++)
            {
                Worksheet sheet = (Worksheet)workBookIn.Sheets[sheetNum];

                //
                // Take the used range of the sheet. Finally, get an object array of all
                // of the cells in the sheet (their values). You can do things with those
                // values. See notes about compatibility.
                //
                Range excelRange = sheet.UsedRange;
                object[,] valueArray = (object[,])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);

                //
                // Do something with the data in the array with a custom method.
                //
                ProcessObjects(valueArray);
            }
        }
        private System.Data.DataTable ProcessObjects(object[,] valueArray)
        {
            System.Data.DataTable dt = new System.Data.DataTable();

            #region Get the COLUMN names

            for (int k = 1; k <= valueArray.GetLength(1); k++)
            {
                dt.Columns.Add((string)valueArray[1, k]);  //add columns to the data table.
            }
            #endregion

            #region Load Excel SHEET DATA into data table

            object[] singleDValue = new object[valueArray.GetLength(1)];
            //value array first row contains column names. so loop starts from 2 instead of 1
            for (int i = 2; i <= valueArray.GetLength(0); i++)
            {
                for (int j = 0; j < valueArray.GetLength(1); j++)
                {
                    if (valueArray[i, j + 1] != null)
                    {
                        singleDValue[j] = valueArray[i, j + 1].ToString();
                    }
                    else
                    {
                        singleDValue[j] = valueArray[i, j + 1];
                    }
                }
                dt.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
            }
            #endregion


            return (dt);
        }
    }
}

How to list all methods for an object in Ruby?

The following will list the methods that the User class has that the base Object class does not have...

>> User.methods - Object.methods
=> ["field_types", "maximum", "create!", "active_connections", "to_dropdown",
    "content_columns", "su_pw?", "default_timezone", "encode_quoted_value", 
    "reloadable?", "update", "reset_sequence_name", "default_timezone=", 
    "validate_find_options", "find_on_conditions_without_deprecation", 
    "validates_size_of", "execute_simple_calculation", "attr_protected", 
    "reflections", "table_name_prefix", ...

Note that methods is a method for Classes and for Class instances.

Here's the methods that my User class has that are not in the ActiveRecord base class:

>> User.methods - ActiveRecord::Base.methods
=> ["field_types", "su_pw?", "set_login_attr", "create_user_and_conf_user", 
    "original_table_name", "field_type", "authenticate", "set_default_order",
    "id_name?", "id_name_column", "original_locking_column", "default_order",
    "subclass_associations",  ... 
# I ran the statements in the console.

Note that the methods created as a result of the (many) has_many relationships defined in the User class are not in the results of the methods call.

Added Note that :has_many does not add methods directly. Instead, the ActiveRecord machinery uses the Ruby method_missing and responds_to techniques to handle method calls on the fly. As a result, the methods are not listed in the methods method result.

How do I update/upsert a document in Mongoose?

Very elegant solution you can achieve by using chain of Promises:

app.put('url', (req, res) => {

    const modelId = req.body.model_id;
    const newName = req.body.name;

    MyModel.findById(modelId).then((model) => {
        return Object.assign(model, {name: newName});
    }).then((model) => {
        return model.save();
    }).then((updatedModel) => {
        res.json({
            msg: 'model updated',
            updatedModel
        });
    }).catch((err) => {
        res.send(err);
    });
});

Test a weekly cron job

A wee bit beyond the scope of your question... but here's what I do.

The "how do I test a cron job?" question is closely connected to "how do I test scripts that run in non-interactive contexts launched by other programs?" In cron, the trigger is some time condition, but lots of other *nix facilities launch scripts or script fragments in non-interactive ways, and often the conditions in which those scripts run contain something unexpected and cause breakage until the bugs are sorted out. (See also: https://stackoverflow.com/a/17805088/237059 )

A general approach to this problem is helpful to have.

One of my favorite techniques is to use a script I wrote called 'crontest'. It launches the target command inside a GNU screen session from within cron, so that you can attach with a separate terminal to see what's going on, interact with the script, even use a debugger.

To set this up, you would use "all stars" in your crontab entry, and specify crontest as the first command on the command line, e.g.:

* * * * * crontest /command/to/be/tested --param1 --param2

So now cron will run your command every minute, but crontest will ensure that only one instance runs at a time. If the command takes time to run, you can do a "screen -x" to attach and watch it run. If the command is a script, you can put a "read" command at the top to make it stop and wait for the screen attachment to complete (hit enter after attaching)

If your command is a bash script, you can do this instead:

* * * * * crontest --bashdb /command/to/be/tested --param1 --param2

Now, if you attach with "screen -x", you'll be facing an interactive bashdb session, and you can step through the code, examine variables, etc.

#!/bin/bash

# crontest
# See https://github.com/Stabledog/crontest for canonical source.

# Test wrapper for cron tasks.  The suggested use is:
#
#  1. When adding your cron job, use all 5 stars to make it run every minute
#  2. Wrap the command in crontest
#        
#
#  Example:
#
#  $ crontab -e
#     * * * * * /usr/local/bin/crontest $HOME/bin/my-new-script --myparams
#
#  Now, cron will run your job every minute, but crontest will only allow one
#  instance to run at a time.  
#
#  crontest always wraps the command in "screen -d -m" if possible, so you can
#  use "screen -x" to attach and interact with the job.   
#
#  If --bashdb is used, the command line will be passed to bashdb.  Thus you
#  can attach with "screen -x" and debug the remaining command in context.
#
#  NOTES:
#   - crontest can be used in other contexts, it doesn't have to be a cron job.
#       Any place where commands are invoked without an interactive terminal and
#       may need to be debugged.
#
#   - crontest writes its own stuff to /tmp/crontest.log
#
#   - If GNU screen isn't available, neither is --bashdb
#

crontestLog=/tmp/crontest.log
lockfile=$(if [[ -d /var/lock ]]; then echo /var/lock/crontest.lock; else echo /tmp/crontest.lock; fi )
useBashdb=false
useScreen=$( if which screen &>/dev/null; then echo true; else echo false; fi )
innerArgs="$@"
screenBin=$(which screen 2>/dev/null)

function errExit {
    echo "[-err-] $@" | tee -a $crontestLog >&2
}

function log {
    echo "[-stat-] $@" >> $crontestLog
}

function parseArgs {
    while [[ ! -z $1 ]]; do
        case $1 in
            --bashdb)
                if ! $useScreen; then
                    errExit "--bashdb invalid in crontest because GNU screen not installed"
                fi
                if ! which bashdb &>/dev/null; then
                    errExit "--bashdb invalid in crontest: no bashdb on the PATH"
                fi

                useBashdb=true
                ;;
            --)
                shift
                innerArgs="$@"
                return 0
                ;;
            *)
                innerArgs="$@"
                return 0
                ;;
        esac
        shift
    done
}

if [[ -z  $sourceMe ]]; then
    # Lock the lockfile (no, we do not wish to follow the standard
    # advice of wrapping this in a subshell!)
    exec 9>$lockfile
    flock -n 9 || exit 1

    # Zap any old log data:
    [[ -f $crontestLog ]] && rm -f $crontestLog

    parseArgs "$@"

    log "crontest starting at $(date)"
    log "Raw command line: $@"
    log "Inner args: $@"
    log "screenBin: $screenBin"
    log "useBashdb: $( if $useBashdb; then echo YES; else echo no; fi )"
    log "useScreen: $( if $useScreen; then echo YES; else echo no; fi )"

    # Were building a command line.
    cmdline=""

    # If screen is available, put the task inside a pseudo-terminal
    # owned by screen.  That allows the developer to do a "screen -x" to
    # interact with the running command:
    if $useScreen; then
        cmdline="$screenBin -D -m "
    fi

    # If bashdb is installed and --bashdb is specified on the command line,
    # pass the command to bashdb.  This allows the developer to do a "screen -x" to
    # interactively debug a bash shell script:
    if $useBashdb; then
        cmdline="$cmdline $(which bashdb) "
    fi

    # Finally, append the target command and params:
    cmdline="$cmdline $innerArgs"

    log "cmdline: $cmdline"


    # And run the whole schlock:
    $cmdline 

    res=$?

    log "Command result: $res"


    echo "[-result-] $(if [[ $res -eq 0 ]]; then echo ok; else echo fail; fi)" >> $crontestLog

    # Release the lock:
    9<&-
fi

UTF-8, UTF-16, and UTF-32

Depending on your development environment you may not even have the choice what encoding your string data type will use internally.

But for storing and exchanging data I would always use UTF-8, if you have the choice. If you have mostly ASCII data this will give you the smallest amount of data to transfer, while still being able to encode everything. Optimizing for the least I/O is the way to go on modern machines.

Why do we check up to the square root of a prime number to determine if it is prime?

Because if a factor is greater than the square root of n, the other factor that would multiply with it to equal n is necessarily less than the square root of n.

Call Python function from MATLAB

I had a similar requirement on my system and this was my solution:

In MATLAB there is a function called perl.m, which allows you to call perl scripts from MATLAB. Depending on which version you are using it will be located somewhere like

C:\Program Files\MATLAB\R2008a\toolbox\matlab\general\perl.m

Create a copy called python.m, a quick search and replace of perl with python, double check the command path it sets up to point to your installation of python. You should now be able to run python scripts from MATLAB.

Example

A simple squared function in python saved as "sqd.py", naturally if I was doing this properly I'd have a few checks in testing input arguments, valid numbers etc.

import sys

def squared(x):
    y = x * x
    return y

if __name__ == '__main__':
    x = float(sys.argv[1])
    sys.stdout.write(str(squared(x)))

Then in MATLAB

>> r=python('sqd.py','3.5')
r =
12.25
>> r=python('sqd.py','5')
r =
25.0
>>

if A vs if A is not None:

A lot of functions return None if there are no appropriate results. For example, an SQLAlchemy query's .first() method returns None if there were no rows in the result. Suppose you were selecting a value that might return 0 and need to know whether it's actually 0 or whether the query had no results at all.

A common idiom is to give a function or method's optional argument the default value of None, and then to test that value being None to see if it was specified. For example:

def spam(eggs=None):
    if eggs is None:
        eggs = retrievefromconfigfile()

compare that to:

def spam(eggs=None):
    if not eggs:
        eggs = retrievefromconfigfile()

In the latter, what happens if you call spam(0) or spam([])? The function would (incorrectly) detect that you hadn't passed in a value for eggs and would compute a default value for you. That's probably not what you want.

Or imagine a method like "return the list of transactions for a given account". If the account does not exist, it might return None. This is different than returning an empty list (which would mean "this account exists but has not recorded transactions).

Finally, back to database stuff. There's a big difference between NULL and an empty string. An empty string typically says "there's a value here, and that value is nothing at all". NULL says "this value hasn't been entered."

In each of those cases, you'd want to use if A is None. You're checking for a specific value - None - not just "any value that happens to cast to False".

Including jars in classpath on commandline (javac or apt)

Use the -cp or -classpath switch.

$ java -help  
Usage: java [-options] class [args...]  
           (to execute a class)  
   or  java [-options] -jar jarfile [args...]  
           (to execute a jar file)  

where options include:  
...  
    -cp <class search path of directories and zip/jar files>  
    -classpath <class search path of directories and zip/jar files>  
                  A ; separated list of directories, JAR archives,  
                  and ZIP archives to search for class files.  

(Note that the separator used to separate entries on the classpath differs between OSes, on my Windows machine it is ;, in *nix it is usually :.)

"Could not find bundler" error

The system might be running "rootless". Try to set the firmware nvram variable boot-args to "rootless=0". Try to run set of commands:

sudo nvram boot-args="rootless=0"; 
sudo reboot

After reboot completes, run:

sudo gem install bundler

Jquery: Find Text and replace

$("#id1 p:contains('dog')").html("doll");

that'll do it.

http://jsfiddle.net/pgDFQ/

How to write an inline IF statement in JavaScript?

Isn't the question essentially: can I write the following?

if (foo)
  console.log(bar)
else
  console.log(foo + bar)

the answer is, yes, the above will translate.

however, be wary of doing the following

if (foo)
  if (bar)
    console.log(foo)
  else 
    console.log(bar)
else 
  console.log(foobar)

be sure to wrap ambiguous code in braces as the above will throw an exception (and similar permutations will produce undesired behaviour.)

How do I select a random value from an enumeration?

You could just do this:

var rnd = new Random();
return (MyEnum) rnd.Next(Enum.GetNames(typeof(MyEnum)).Length);

No need to store arrays

select rows in sql with latest date for each ID repeated multiple times

You can do this with a Correlated Subquery (That is a subquery wherein you reference a field in the main query). In this case:

SELECT * 
FROM yourtable t1
WHERE date = (SELECT max(date) from yourtable WHERE id = t1.id)

Here we give the yourtable table an alias of t1 and then use that alias in the subquery grabbing the max(date) from the same table yourtable for that id.

How to center an element horizontally and vertically

Source Link

Method 1) Display type flex

.child-element{
     display: flex;
     justify-content: center;
     align-items: center;
}

Method 2) 2D Transform

.child-element {
   top: 50%;
   left: 50%;
   transform: translate(-50% , -50%);
   position: absolute;
}

See other methods here

How to convert vector to array

std::vector<double> vec;
double* arr = vec.data();

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I was importing also some projects from VS2010 to VS 2012. I had the same errors. The errors disappeared when I set back Properties > Config. Properties > General > Platform Toolset to v100 (VS2010). That might not be the correct approach, however.

What's the best way to determine which version of Oracle client I'm running?

Run the installer, click "Installed Products...". This will give you a more detailed list of all installed components of the client install, e.g., drivers, SQL*Plus, etc.

Typical Oracle installations will store inventory information in C:\Program Files\Oracle\Inventory, but figuring out the installed versions isn't simply a matter of opening a text file.

This is AFAIK authoritative, and shows any patches that might have been applied as well (which running the utilities does not do).

EDIT: A CLI option would be to use the OPatch utility:

c:\> path=%path%;<path to OPatch directory in client home, e.g., C:\oracle\product\10.2.0\client_1\OPatch>
c:\>set ORACLE_HOME=<oracle home directory of client, e.g., C:\Oracle\product\10.2.0\client_1>
c:\>opatch lsinventory

This gives you the overall version of the client installed.

How do I pass along variables with XMLHTTPRequest

How about?

function callHttpService(url, params){
  // Assume params contains key/value request params
  let queryStrings = '';

  for(let key in params){
      queryStrings += `${key}=${params[key]}&`
    } 
 const fullUrl = `${url}?queryStrings`

  //make http request with fullUrl
}

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

1 line will do all

For message queue

ipcs -q | sed "$ d; 1,2d" |  awk '{ print "Removing " $2; system("ipcrm -q " $2) }'

ipcs -q will give the records of message queues

sed "$ d; 1,2d " will remove last blank line ("$ d") and first two header lines ("1,2d")

awk will do the rest i.e. printing and removing using command "ipcrm -q" w.r.t. the value of column 2 (coz $2)

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

You can use functions in pyspark.sql.functions: functions like year, month, etc

refer to here: https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame

from pyspark.sql.functions import *

newdf = elevDF.select(year(elevDF.date).alias('dt_year'), month(elevDF.date).alias('dt_month'), dayofmonth(elevDF.date).alias('dt_day'), dayofyear(elevDF.date).alias('dt_dayofy'), hour(elevDF.date).alias('dt_hour'), minute(elevDF.date).alias('dt_min'), weekofyear(elevDF.date).alias('dt_week_no'), unix_timestamp(elevDF.date).alias('dt_int'))

newdf.show()


+-------+--------+------+---------+-------+------+----------+----------+
|dt_year|dt_month|dt_day|dt_dayofy|dt_hour|dt_min|dt_week_no|    dt_int|
+-------+--------+------+---------+-------+------+----------+----------+
|   2015|       9|     6|      249|      0|     0|        36|1441497601|
|   2015|       9|     6|      249|      0|     0|        36|1441497601|
|   2015|       9|     6|      249|      0|     0|        36|1441497603|
|   2015|       9|     6|      249|      0|     1|        36|1441497694|
|   2015|       9|     6|      249|      0|    20|        36|1441498808|
|   2015|       9|     6|      249|      0|    20|        36|1441498811|
|   2015|       9|     6|      249|      0|    20|        36|1441498815|

How to convert list data into json in java

public static List<Product> getCartList() {

    JSONObject responseDetailsJson = new JSONObject();
    JSONArray jsonArray = new JSONArray();

    List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
    for(Product p : cartMap.keySet()) {
        cartList.add(p);
        JSONObject formDetailsJson = new JSONObject();
        formDetailsJson.put("id", "1");
        formDetailsJson.put("name", "name1");
       jsonArray.add(formDetailsJson);
    }
    responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format

    return cartList;

}

you can get the data in the following form

{
    "forms": [
        { "id": "1", "name": "name1" },
        { "id": "2", "name": "name2" } 
    ]
}

Determine if JavaScript value is an "integer"?

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

How do you run a command for each line of a file?

Yes.

while read in; do chmod 755 "$in"; done < file.txt

This way you can avoid a cat process.

cat is almost always bad for a purpose such as this. You can read more about Useless Use of Cat.

Add spaces between the characters of a string in Java?

  • Create a char array from your string
  • Loop through the array, adding a space +" " after each item in the array(except the last one, maybe)
  • BOOM...done!!

Angular cli generate a service and include the provider in one step

Angular 6+ Singleton Services

The recommended approach for a singleton service for Angular 6 and beyond is :

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

@Injectable({
  providedIn: 'root',
})
export class UserService {
}

In fact the CLI --module switch doesn't even exist any more for registering a service at the app level because it doesn't need to modify app.module.ts anymore.

This will create the above code, without needing to specify a module.

ng g s services/user

So if you don't want your service to be a singleton you must remove the providedIn code yourself - and then add it manually to providers for a component or lazy loaded module. Doesn't look like there is currently a switch to not generate the providedIn: 'root' part so you need to manually remove it.

Java Package Does Not Exist Error

You need to have org/name dirs at /usr/share/stuff and place your org.name package sources at this dir.

What is Android's file system?

Most answers here are pretty old.

In the past when un managed nand was the most popular storage technology, yaffs2 was the most common file system. This days there are few devices using un-managed nand, and those still in use are slowly migrating to ubifs.

Today most common storage is emmc (managed nand), for such devices ext4 is far more popular, but, this file system is slowly clears its way for f2fs (flash friendly fs).

Edit: f2fs will probably won't make it as the common fs for flash devices (including android)

Bootstrap modal appearing under background

I resolved my issue by adding data-backdrop="false" to the div:

<div class="modal fade" id="exampleModalCenter" data-backdrop="false" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">

.....

How to initialize an array in one step using Ruby?

You can do

array = ['1', '2', '3']

As others have noted, you can also initialize an array with %w notation like so:

array = %w(1 2 3)

or

array = %w[1 2 3]

Please note that in both cases each element is a string, rather than an integer. So if you want an array whose elements are integers, you should not wrap each element with apostrophes:

array_of_integers = [1, 2, 3]

Also, you don't need to put comma in between the elements (which is necessary when creating an array without this %w notation). If you do this (which I often did by mistake), as in:

wrong_array = %w(1, 2, 3)

its elements will be three strings ---- "1,", "2,", "3". So if you do:

puts wrong_array

the output will be:

1,
2,
3
=>nil

which is not what we want here.

Hope this helps to clarify the point!

How to change the font size on a matplotlib plot

If you are a control freak like me, you may want to explicitly set all your font sizes:

import matplotlib.pyplot as plt

SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12

plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title

Note that you can also set the sizes calling the rc method on matplotlib:

import matplotlib

SMALL_SIZE = 8
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)

# and so on ...

How to concatenate variables into SQL strings

You could make use of Prepared Stements like this.

set @query = concat( "select name from " );
set @query = concat( "table_name"," [where condition] " );

prepare stmt from @like_q;
execute stmt;

MongoDB via Mongoose JS - What is findByID?

If the schema of id is not of type ObjectId you cannot operate with function : findbyId()

MySQL search and replace some text in a field

And if you want to search and replace based on the value of another field you could do a CONCAT:

update table_name set `field_name` = replace(`field_name`,'YOUR_OLD_STRING',CONCAT('NEW_STRING',`OTHER_FIELD_VALUE`,'AFTER_IF_NEEDED'));

Just to have this one here so that others will find it at once.

How do I set up curl to permanently use a proxy?

Curl will look for a .curlrc file in your home folder when it starts. You can create (or edit) this file and add this line:

proxy = yourproxy.com:8080

python pip - install from local dir

You were looking for help on installations with pip. You can find it with the following command:

pip install --help

Running pip install -e /path/to/package installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

Use existing functions for checking ObjectID.

var mongoose = require('mongoose');
mongoose.Types.ObjectId.isValid('your id here');

How to create an email form that can send email using html

Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.

Simple way to get element by id within a div tag?

A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.

You could change your HTML to this:

<div id="div1" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>
<div id="div2" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>

Then, you could get the first item in div1 with a CSS selector like this:

#div1 .edit1

On in jQuery:

$("#div1 .edit1")

Or, if you want to iterate the items in one of your divs, you can do it like this:

$("#div1 input").each(function(index) {
    // do something with one of the input objects
});

If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.

If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.

You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.

Circular gradient in android

You can get a circular gradient using android:type="radial":

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:type="radial" android:gradientRadius="250dp"
        android:startColor="#E9E9E9" android:endColor="#D4D4D4" />
</shape>

Eclipse Bug: Unhandled event loop exception No more handles

Happens with Eclipse Mars.2 Release (4.5.2) and Multimon TaskBar 2.1 on a dual monitor setup, too. It disappears if MM TaskBar is un-loaded.

UPDATE

Still the same with Oxygen.2 Release (4.7.2).

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options.

import timeit

setup = '''
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
'''

timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500)
timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500)
timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500)

Results:

1.1214002349999777 s  # WouterOvermeire
1.1922008498571748 s  # Jeff
1.7034366211428602 s  # Kikohs

Getting the location from an IP address

Ipdata.co is a fast, highly available IP Geolocation API with reliable performance.

It's extremely scalable with 10 endpoints around the world each able to handle >10,000 requests per second!

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

In php

php > $ip = '8.8.8.8';
php > $details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}?api-key=test"));
php > echo $details->region;
California
php > echo $details->city;
Mountain View
php > echo $details->country_name;
United States
php > echo $details->latitude;
37.751

Here's a client-side example showing how you'd get the country, region and city;

_x000D_
_x000D_
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
 $("#response").html(JSON.stringify(response, null, 4));_x000D_
  $("#country").html('Country: ' + response.country_name);_x000D_
  $("#region").html('Region ' + response.region);_x000D_
  $("#city").html('City' + response.city);  _x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="country"></div>_x000D_
<div id="region"></div>_x000D_
<div id="city"></div>_x000D_
<pre id="response"></pre>
_x000D_
_x000D_
_x000D_

Disclaimer;

I built the service.

For examples in multiple languages see the Docs

Also see this detailed analysis of the best IP Geolocation APIs.

How to configure SMTP settings in web.config

I don't have enough rep to answer ClintEastwood, and the accepted answer is correct for the Web.config file. Adding this in for code difference.

When your mailSettings are set on Web.config, you don't need to do anything other than new up your SmtpClient and .Send. It finds the connection itself without needing to be referenced. You would change your C# from this:

SmtpClient smtpClient = new SmtpClient("smtp.sender.you", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;
smtpClient.Send(msgMail);  

To this:

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(msgMail);

how to install tensorflow on anaconda python 3.6

This is what I did for Installing Anaconda Python 3.6 version and Tensorflow on Window 10 64bit.And It was success!

  1. Download Anaconda Python 3.6 version for Window 64bit.

  2. Create a conda environment named tensorflow by invoking the following command:

    C:> conda create -n tensorflow 
    
  3. Activate the conda environment by issuing the following command:

    C:> activate tensorflow
    (tensorflow)C:>  # Your prompt should change 
    
  4. Download “tensorflow-1.0.1-cp36-cp36m-win_amd64.whl” from here. (For my case, the file will be located in “C:\Users\Joshua\Downloads” once after downloaded).

  5. Install the Tensorflow by using following command:

    (tensorflow)C:>pip install C:\Users\Joshua\Downloads\ tensorflow-1.0.1-cp36-cp36m-win_amd64.whl
    

This is what I got after the installing: enter image description here

  1. Validate installation by entering following command in your Python environment:

    import tensorflow as tf
    hello = tf.constant('Hello, TensorFlow!')
    sess = tf.Session()
    print(sess.run(hello))
    

If the output you got is 'Hello, TensorFlow!',that means you have successfully install your Tensorflow.

Remove shadow below actionbar

What is the style item to make it disappear?

In order to remove the shadow add this to your app theme:

<style name="MyAppTheme" parent="android:Theme.Holo.Light">
    <item name="android:windowContentOverlay">@null</item>
</style>

UPDATE: As @Quinny898 stated, on Android 5.0 this has changed, you have to call setElevation(0) on your action bar. Note that if you're using the support library you must call it to that like so:

getSupportActionBar().setElevation(0);

Differences between Octave and MATLAB?

MATLAB is, first and foremost, a commercial offering. Therefore, everything in MATLAB pretty much works out of the box. All the core functionality is solid, and if you're working on a special project then MATLAB probably has an add-on they can sell you that adds a lot of additional domain-specific .m files for you. It ain't cheap, but it works and it will get the job done without complaint.

Octave always shows its open-source, information-wants-to-be-free roots. It's free, and it will remind you that it's free at every opportunity. It's developed by volunteers who hate Windows with a passion. Therefore Octave runs on Windows grudgingly. It's quite surprising that as many MATLAB features exist as they do.

But here's the rub. Anytime you try to do something more than trivially complex, Octave suddenly breaks in subtle and hard to understand ways. Oops -- the terminal driver had an overflow somewhere deep in the OpenGL layer. You can't print. Oops -- the figure plots do strange things with their fonts. Good luck figuring out why. Oops -- there's some hidden dependency between Octave and some other obscure bit of free software, so it won't compile. Good luck figuring out which it is.

And the Octave response is hey! It's free software! You have all the source code, you can fix all those bugs yourself! Maybe if I had infinite time and resources on my hands, I could spend all my time fixing bugs in free software, but I personally don't. If I worked in academia, I might.

So at the core, the issue of whether to choose MATLAB or Octave comes down to one question. Interestingly, that question is always the same, when choosing between commercial vs. free software variants.

And the question is:

Do you have more money than time?

Trouble setting up git with my GitHub Account error: could not lock config file

So I know this thread is Old, but I had the same issue and fixed it. Hopefully this works for someone else.

When i tried using "sudo" or anything in powershell/cmd it was an unrecognized command. So i reinstalled git for windows, during the install it failed and pointed me to C:/ProgramFiles/git/etc/gitconfig I deleted that file, and reinstalled. Same Error when saving credentials, So i moved the newly created gitconfig from programfiles, to my HomePath location C:/Users/Name

Now I can save credentials under file-->Options-->git Finally, I can commit/push on githubdesktop

How to extract public key using OpenSSL?

Though, the above technique works for the general case, it didn't work on Amazon Web Services (AWS) PEM files.

I did find in the AWS docs the following command works: ssh-keygen -y

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html

edit Thanks @makenova for the complete line:

ssh-keygen -y -f key.pem > key.pub

PHP __get and __set magic methods

From the PHP manual:

  • __set() is run when writing data to inaccessible properties.
  • __get() is utilized for reading data from inaccessible properties.

This is only called on reading/writing inaccessible properties. Your property however is public, which means it is accessible. Changing the access modifier to protected solves the issue.

How do I force detach Screen from another SSH session?

try with screen -d -r or screen -D -RR

Angular 2 - Redirect to an external URL and open in a new tab

in HTML:

<a class="main-item" (click)="onNavigate()">Go to URL</a>

OR

<button class="main-item" (click)="onNavigate()">Go to URL</button>

in TS file:

onNavigate(){
    // your logic here.... like set the url 
    const url = 'https://www.google.com';
    window.open(url, '_blank');
}

How can I check what version/edition of Visual Studio is installed programmatically?

All the information in this thread is now out of date with the recent release of vswhere. Download that and use it.

Play local (hard-drive) video file with HTML5 video tag?

Ran in to this problem a while ago. Website couldn't access video file on local PC due to security settings (understandable really) ONLY way I could get around it was to run a webserver on the local PC (server2Go) and all references to the video file from the web were to the localhost/video.mp4

<div id="videoDiv">
     <video id="video" src="http://127.0.0.1:4001/videos/<?php $videoFileName?>" width="70%" controls>
    </div>
<!--End videoDiv-->

Not an ideal solution but worked for me.

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

You also could just throw new HttpMessageNotReadableException("error description") to benefit from Spring's default error handling.

However, just as is the case with those default errors, no response body will be set.

I find these useful when rejecting requests that could reasonably only have been handcrafted, potentially indicating a malevolent intent, since they obscure the fact that the request was rejected based on a deeper, custom validation and its criteria.

Hth, dtk

How can I change the date format in Java?

How to convert from one date format to another using SimpleDateFormat:

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;

SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);

What's the -practical- difference between a Bare and non-Bare repository?

The distinction between a bare and non-bare Git repository is artificial and misleading since a workspace is not part of the repository and a repository doesn't require a workspace. Strictly speaking, a Git repository includes those objects that describe the state of the repository. These objects may exist in any directory, but typically exist in the .git directory in the top-level directory of the workspace. The workspace is a directory tree that represents a particular commit in the repository, but it may exist in any directory or not at all. Environment variable $GIT_DIR links a workspace to the repository from which it originates.

Git commands git clone and git init both have options --bare that create repositories without an initial workspace. It's unfortunate that Git conflates the two separate, but related concepts of workspace and repository and then uses the confusing term bare to separate the two ideas.

The module ".dll" was loaded but the entry-point was not found

I found the answer: I need to add a new application to the service components in my computer and then add the right DLL's.

Thanks! If anyone has the same problem, I'll be happy to help.

How can I increase the size of a bootstrap button?

Use block level buttons, those that span the full width of a parent You can achieve this by adding btn-block class your button element.

Documentation here

Using LIKE operator with stored procedure parameters

Your datatype for @location nchar(20) should be @location nvarchar(20), since nChar has a fixed length (filled with Spaces).
If Location is nchar too you will have to convert it:

 ... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...   

To enable nullable parameters with and AND condition just use IsNull or Coalesce for comparison, which is not needed in your example using OR.

e.g. if you would like to compare for Location AND Date and Time.

@location nchar(20),
@time time,
@date date
as
select DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from Vechile, DonationsTruck
where Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+IsNull(@location,Location)+'%')) and [Date]=IsNUll(@date,date) and [Time] = IsNull(@time,Time))

How do you create a read-only user in PostgreSQL?

I’ve created a convenient script for that; pg_grant_read_to_db.sh. This script grants read-only privileges to a specified role on all tables, views and sequences in a database schema and sets them as default.

How can I plot with 2 different y-axes?

As its name suggests, twoord.plot() in the plotrix package plots with two ordinate axes.

library(plotrix)
example(twoord.plot)

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Git Commit Messages: 50/72 Formatting

Is the maximum recommended title length really 50?

I have believed this for years, but as I just noticed the documentation of "git commit" actually states

$ git help commit | grep -C 1 50
      Though not required, it’s a good idea to begin the commit message with
      a single short (less than 50 character) line summarizing the change,
      followed by a blank line and then a more thorough description. The text

$  git version
git version 2.11.0

One could argue that "less then 50" can only mean "no longer than 49".

remove objects from array by object property

You can use filter. This method always returns the element if the condition is true. So if you want to remove by id you must keep all the element that doesn't match with the given id. Here is an example:

arrayOfObjects = arrayOfObjects.filter(obj => obj.id != idToRemove)

Android Studio does not show layout preview

For me, in Android Studio 3.6.1, while in the layout.xml file, clicking here showed the preview of the layout again. Android Studio 3.6.1 Screenshot

I Don't think the "tab" Preview exists anymore, it does now appear to me here: View > Tool Windows > Preview.

What's the difference between REST & RESTful

REST(REpresentation State Transfer) is an architecture using which WebServices are created.

and

RESTful is way of writing services using the REST architectures. RESTful services exposes the resources to identify the targets to interact with clients.

What is the "realm" in basic authentication

From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)

The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.

In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.

Error when creating a new text file with python?

If the file does not exists, open(name,'r+') will fail.

You can use open(name, 'w'), which creates the file if the file does not exist, but it will truncate the existing file.

Alternatively, you can use open(name, 'a'); this will create the file if the file does not exist, but will not truncate the existing file.

What is the minimum I have to do to create an RPM file?

RPMs are usually built from source, not the binaries.

You need to write the spec file that covers how to configure and compile your application; also, which files to include in your RPM.

A quick glance at the manual shows that most of what you need is covered in Chapter 8 -- also, as most RPM-based distributions have sources available, there's literally a zillion of examples of different approaches you could look at.

getResourceAsStream() is always returning null

A call to Class#getResourceAsStream(String) delegates to the class loader and the resource is searched in the class path. In other words, you current code won't work and you should put abc.txt in WEB-INF/classes, or in WEB-INF/lib if packaged in a jar file.

Or use ServletContext.getResourceAsStream(String) which allows servlet containers to make a resource available to a servlet from any location, without using a class loader. So use this from a Servlet:

this.getServletContext().getResourceAsStream("/WEB-INF/abc.txt") ;

But is there a way I can call getServletContext from my Web Service?

If you are using JAX-WS, then you can get a WebServiceContext injected:

@Resource
private WebServiceContext wsContext;

And then get the ServletContext from it:

ServletContext sContext= wsContext.getMessageContext()
                             .get(MessageContext.SERVLET_CONTEXT));

Convert int to string?

None of the answers mentioned that the ToString() method can be applied to integer expressions

Debug.Assert((1000*1000).ToString()=="1000000");

even to integer literals

Debug.Assert(256.ToString("X")=="100");

Although integer literals like this are often considered to be bad coding style (magic numbers) there may be cases where this feature is useful...

How to go back to previous page if back button is pressed in WebView?

The first answer by FoamyGuy is correct but I have some additions; low reputations cannot allow me to do comments. If for some reasons your page fails to load, ensure that you set a flag to take note of the failure and then check it on the onBackPressed override. Otherwise your canGoBack() will be forever executed without heading to the actual back activity if it was there:

//flag with class wide access 
public boolean ploadFailFlag = false;

//your error handling override
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
    onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
    ploadFailFlag = true;       //note this change 
    .....
    .....
}

//finally to the answer to this question:
@Override
public void onBackPressed() {
    if(checkinWebView.canGoBack()){
        //if page load fails, go back for web view will not go back - no page to go to - yet overriding the super 
        if(ploadFailFlag){
            super.onBackPressed();
        }else {
            checkinWebView.goBack();
        }
    }else {
        Toast.makeText(getBaseContext(), "super:", Toast.LENGTH_LONG).show();
        super.onBackPressed();
    }
}

How to convert JSON to string?

Try to Use JSON.stringify

Regards

How Do I Convert an Integer to a String in Excel VBA?

The shortest way without declaring the variable is with Type Hints :

s$ =  123   ' s = "123"
i% = "123"  ' i =  123

This will not compile with Option Explicit. The types will not be Variant but String and Integer

How long do browsers cache HTTP 301s?

For testing purposes (to avoid cached redirects), people can open NEW PRIVATE WINDOW: click CTRL+SHIFT+N [if you use Mozilla, use P]

Execution failed for task :':app:mergeDebugResources'. Android Studio

I can see libc error in the log.

install these packages in your system

sudo apt-get install lib32stdc++6 lib32z1 lib32z1-dev

Restart android studio after installation

I forgot the password I entered during postgres installation

Just a note, on Linux You can simply run sudo su - postgres to become the postgres user and from there change what required using psql.

How can I determine the direction of a jQuery scroll event?

Store the previous scroll location, then see if the new one is greater than or less than that.

Here's a way to avoid any global variables (fiddle available here):

(function () {
    var previousScroll = 0;

    $(window).scroll(function(){
       var currentScroll = $(this).scrollTop();
       if (currentScroll > previousScroll){
           alert('down');
       } else {
          alert('up');
       }
       previousScroll = currentScroll;
    });
}()); //run this anonymous function immediately

Clear Cache in Android Application programmatically

Kotlin has an one-liner

context.cacheDir.deleteRecursively()

Execute curl command within a Python script

If you are not tweaking the curl command too much you can also go and call the curl command directly

import shlex
cmd = '''curl -X POST -d  '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001'''
args = shlex.split(cmd)
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()

java: use StringBuilder to insert at the beginning

You can use the insert method with the offset. as offset set to '0' means you are appending to the front of your StringBuilder.

StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
    sb.insert(0,i);
}

NOTE: as the insert method accept all types of primitives, you can use for int, long, char[] etc.

What is the difference between display: inline and display: inline-block?

splattne's answer probably covered most of everything so I won't repeat the same thing, but: inline and inline-block behave differently with the direction CSS property.

Within the next snippet you see one two (in order) is rendered, like it does in LTR layouts. I suspect the browser here auto-detected the English part as LTR text and rendered it from left to right.

_x000D_
_x000D_
body {_x000D_
  text-align: right;_x000D_
  direction: rtl;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  display: block; /* just being explicit */_x000D_
}_x000D_
_x000D_
span {_x000D_
  display: inline;_x000D_
}
_x000D_
<h2>_x000D_
  ??? ????? ????_x000D_
  <span>one</span>_x000D_
  <span>two</span>_x000D_
</h2>
_x000D_
_x000D_
_x000D_

However, if I go ahead and set display to inline-block, the browser appears to respect the direction property and render the elements from right to left in order, so that two one is rendered.

_x000D_
_x000D_
body {_x000D_
  text-align: right;_x000D_
  direction: rtl;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  display: block; /* just being explicit */_x000D_
}_x000D_
_x000D_
span {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<h2>_x000D_
  ??? ????? ????_x000D_
  <span>one</span>_x000D_
  <span>two</span>_x000D_
</h2>
_x000D_
_x000D_
_x000D_

I don't know if there are any other quirks to this, I only found about this empirically on Chrome.

How to call a function from a string stored in a variable?

My favorite version is the inline version:

${"variableName"} = 12;

$className->{"propertyName"};
$className->{"methodName"}();

StaticClass::${"propertyName"};
StaticClass::{"methodName"}();

You can place variables or expressions inside the brackets too!

Simple way to count character occurrences in a string

Something a bit more functional, without Regex:

public static int count(String s, char c) {
    return s.length()==0 ? 0 : (s.charAt(0)==c ? 1 : 0) + count(s.substring(1),c);
}

It's no tail recursive, for the sake of clarity.

Getting a timestamp for today at midnight?

If you are using Carbon you can do the following. You could also format this date to set an Expire HTTP Header.

Carbon::parse('tomorrow midnight')->format(Carbon::RFC7231_FORMAT)

How to find if a file contains a given string using Windows command line

From other post:

    find /c "string" file >NUL
    if %errorlevel% equ 1 goto notfound
        echo found
    goto done
    :notfound
        echo notfound
    goto done
    :done

Use the /i switch when you want case insensitive checking:

    find /i /c "string" file >NUL

Or something like: if not found write to file.

    find /c "%%P" file.txt  || ( echo %%P >> newfile.txt )

Or something like: if found write to file.

    find /c "%%P" file.txt  && ( echo %%P >> newfile.txt )

Or something like:

    find /c "%%P" file.txt  && ( echo found ) || ( echo not found )

how to get the host url using javascript from the current page

Depending on your needs, you can use one of the window.location properties. In your question you are asking about the host, which may be retrieved using window.location.hostname (e.g. www.example.com). In your example you are showing something what is called origin, which may be retrieved using window.location.origin (e.g. http://www.example.com).

var path = window.location.origin + "/";

//result = "http://localhost:60470/"

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

Because some database can throw an exception at dbContextTransaction.Commit() so better this:

using (var context = new BloggingContext()) 
{ 
  using (var dbContextTransaction = context.Database.BeginTransaction()) 
  { 
    try 
    { 
      context.Database.ExecuteSqlCommand( 
          @"UPDATE Blogs SET Rating = 5" + 
              " WHERE Name LIKE '%Entity Framework%'" 
          ); 

      var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
      foreach (var post in query) 
      { 
          post.Title += "[Cool Blog]"; 
      } 

      context.SaveChanges(false); 

      dbContextTransaction.Commit(); 

      context.AcceptAllChanges();
    } 
    catch (Exception) 
    { 
      dbContextTransaction.Rollback(); 
    } 
  } 
} 

What's NSLocalizedString equivalent in Swift?

Probably the best way is this one here.

fileprivate func NSLocalizedString(_ key: String) -> String {
    return NSLocalizedString(key, comment: "")
}

and

import Foundation
extension String {
    static let Hello = NSLocalizedString("Hello")
    static let ThisApplicationIsCreated = NSLocalizedString("This application is created by the swifting.io team")
    static let OpsNoFeature = NSLocalizedString("Ops! It looks like this feature haven't been implemented yet :(!")
}

you can then use it like this

let message: String = .ThisApplicationIsCreated
print(message)

to me this is the best because

  • The hardcoded strings are in one specific file, so the day you want to change it it's really easy
  • Easier to use than manually typing the strings in your file every time
  • genstrings will still work
  • you can add more extensions, like one per view controller to keep things neat

How to enter command with password for git pull?

Doesn't answer the question directly, but I found this question when searching for a way to, basically, not re-enter the password every single time I pull on a remote server.

Well, git allows you to cache your credentials for a finite amount of time. It's customizable in git config and this page explains it very well:

https://help.github.com/articles/caching-your-github-password-in-git/#platform-linux

In a terminal, run:

$ git config --global credential.helper cache
# Set git to use the credential memory cache

To customize the cache timeout, you can do:

$ git config --global credential.helper 'cache --timeout=3600'
# Set the cache to timeout after 1 hour (setting is in seconds)

Your credentials will then be stored in-memory for the requested amount of time.

How to play a sound using Swift?

import UIKit
import AVFoundation

class ViewController: UIViewController{

    var player: AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func notePressed(_ sender: UIButton) {

        guard let url = Bundle.main.url(forResource: "note1", withExtension: "wav") else { return }

        do {
            try AVAudioSession.sharedInstance().setCategory((AVAudioSession.Category.playback), mode: .default, options: [])
            try AVAudioSession.sharedInstance().setActive(true)


            /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
            player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)

            /* iOS 10 and earlier require the following line:
             player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) *//

            guard let player = player else { return }

            player.play()

        } catch let error {
            print(error.localizedDescription)
        }

    }

}

T-SQL loop over query results

You could do something like this:

create procedure test
as
BEGIN

    create table #ids
    (
        rn int,
        id int
    )

    insert into #ids (rn, id)
    select distinct row_number() over(order by id) as rn, id
    from table

    declare @id int
    declare @totalrows int = (select count(*) from #ids)
    declare @currentrow int = 0

    while @currentrow <  @totalrows  
    begin 
        set @id = (select id from #ids where rn = @currentrow)

        exec stored_proc @varName=@id, @otherVarName='test'

        set @currentrow = @currentrow +1
    end  

END

Cannot connect to repo with TortoiseSVN

SVN is case-sensitive. Make sure that you're spelling it properly. If it got renamed, you can relocate the working folder to the new URL. See https://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-relocate.html

Regular expression to stop at first match

Because you are using quantified subpattern and as descried in Perl Doc,

By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a "?" . Note that the meanings don't change, just the "greediness":

*?        //Match 0 or more times, not greedily (minimum matches)
+?        //Match 1 or more times, not greedily

Thus, to allow your quantified pattern to make minimum match, follow it by ? :

/location="(.*?)"/

How to increase font size in NeatBeans IDE?

Check this image with red arrow direction enter image description here

What is the difference between a token and a lexeme?

Using "Compilers Principles, Techniques, & Tools, 2nd Ed." (WorldCat) by Aho, Lam, Sethi and Ullman, AKA the Purple Dragon Book,

Lexeme pg. 111

A lexeme is a sequence of characters in the source program that matches the pattern for a token and is identified by the lexical analyzer as an instance of that token.

Token pg. 111

A token is a pair consisting of a token name and an optional attribute value. The token name is an abstract symbol representing a kind of lexical unit, e.g., a particular keyword, or sequence of input characters denoting an identifier. The token names are the input symbols that the parser processes.

Pattern pg. 111

A pattern is a description of the form that the lexemes of a token may take. In the case of a keyword as a token, the pattern is just the sequence of characters that form the keyword. For identifiers and some other tokens, the pattern is more complex structure that is matched by many strings.

Figure 3.2: Examplesof tokens pg.112

[Token]       [Informal Description]                  [Sample Lexemes]
if            characters i, f                         if
else          characters e, l, s, e                   else
comparison    < or > or <= or >= or == or !=          <=, !=
id            letter followed by letters and digits   pi, score, D2
number        any numeric constant                    3.14159, 0, 6.02e23
literal       anything but ", surrounded by "'s       "core dumped"

To better understand this relation to a lexer and parser we will start with the parser and work backwards to the input.

To make it easier to design a parser, a parser does not work with the input directly but takes in a list of tokens generated by a lexer. Looking at the token column in Figure 3.2 we see tokens such as if, else, comparison, id, number and literal; these are names of tokens. Typically with a lexer/parser a token is a structure that holds not only the name of the token, but the characters/symbols that make up the token and the start and end position of the string of characters that make up the token, with the start and end position being used for error reporting, highlighting, etc.

Now the lexer takes the input of characters/symbols and using the rules of the lexer converts the input characters/symbols into tokens. Now people who work with lexer/parser have their own words for things they use often. What you think of as a sequence of characters/symbols that make up a token are what people who use lexer/parsers call lexeme. So when you see lexeme, just think of a sequence of characters/symbols representing a token. In the comparison example, the sequence of characters/symbols can be different patterns such as < or > or else or 3.14, etc.

Another way to think of the relation between the two is that a token is a programming structure used by the parser that has a property called lexeme that holds the character/symbols from the input. Now if you look at most definitions of token in code you may not see lexeme as one of the properties of the token. This is because a token will more likely hold the start and end position of the characters/symbols that represent the token and the lexeme, sequence of characters/symbols can be derived from the start and end position as needed because the input is static.

Dynamically add child components in React

Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

How to do a SOAP wsdl web services call from the command line

For Windows:

Save the following as MSFT.vbs:

set SOAPClient = createobject("MSSOAP.SOAPClient")
SOAPClient.mssoapinit "https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc?wsdl"
WScript.Echo "MSFT = " & SOAPClient.GetQuote("MSFT")

Then from a command prompt, run:

C:\>MSFT.vbs

Reference: http://blogs.msdn.com/b/bgroth/archive/2004/10/21/246155.aspx

Image library for Python 3

If you are on Python3 you can also use the library PILasOPENCV which works in Python 2 and 3. Function api calls are the same as in PIL or pillow but internally it works with OpenCV and numpy to load, save and manipulate images. Have a look at https://github.com/bunkahle/PILasOPENCV or install it with pip install PILasOPENCV. Not all PIL functions have been simulated but the most common functions work.

Can I have two JavaScript onclick events in one element?

You can attach a handler which would call as many others as you like:

<a href="#blah" id="myLink"/>

<script type="text/javascript">

function myOtherFunction() {
//do stuff...
}

document.getElementById( 'myLink' ).onclick = function() {
   //do stuff...
   myOtherFunction();
};

</script>

Disabling Minimize & Maximize On WinForm?

Right Click the form you want to hide them on, choose Controls -> Properties.

In Properties, set

  • Control Box -> False
  • Minimize Box -> False
  • Maximize Box -> False

You'll do this in the designer.

How to implement OnFragmentInteractionListener

I'd like to add the destruction of the listener when the fragment is detached from the activity or destroyed.

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

and when using the new onStart() method with Context

@Override
public void onDestroy() {
    super.onDestroy();
    mListener = null;
}

Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

How to send HTML-formatted email?

This works for me

msg.BodyFormat = MailFormat.Html;

and then you can use html in your body

msg.Body = "<em>It's great to use HTML in mail!!</em>"

Why does SSL handshake give 'Could not generate DH keypair' exception?

You can disable DHE completely in your jdk, edit jre/lib/security/java.security and make sure DHE is disabled, eg. like

jdk.tls.disabledAlgorithms=SSLv3, DHE.

PHP date() with timezone?

You can replace database value in date_default_timezone_set function, date_default_timezone_set(SOME_PHP_VARIABLE); but just needs to take care of exact values relevant to the timezones.

twitter bootstrap 3.0 typeahead ajax example

Here is my step by step experience, inspired by typeahead examples, from a Scala/PlayFramework app we are working on.

In a script LearnerNameTypeAhead.coffee (convertible of course to JS) I have:

$ ->
  learners = new Bloodhound(
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value")
    queryTokenizer: Bloodhound.tokenizers.whitespace
    remote: "/learner/namelike?nameLikeStr=%QUERY"
  )
  learners.initialize()
  $("#firstName").typeahead 
    minLength: 3
    hint: true
    highlight:true
   ,
    name: "learners"
    displayKey: "value"
    source: learners.ttAdapter()

I included the typeahead bundle and my script on the page, and there is a div around my input field as follows:

<script [email protected]("javascripts/typeahead.bundle.js")></script>
<script [email protected]("javascripts/LearnerNameTypeAhead.js") type="text/javascript" ></script>
<div>
  <input name="firstName" id="firstName" class="typeahead" placeholder="First Name" value="@firstName">
</div>

The result is that for each character typed in the input field after the first minLength (3) characters, the page issues a GET request with a URL looking like /learner/namelike?nameLikeStr= plus the currently typed characters. The server code returns a json array of objects containing fields "id" and "value", for example like this:

[ {
    "id": "109",
    "value": "Graham Jones"
  },
  {
    "id": "5833",
    "value": "Hezekiah Jones"
} ]

For play I need something in the routes file:

GET /learner/namelike controllers.Learners.namesLike(nameLikeStr:String)

And finally, I set some of the styling for the dropdown, etc. in a new typeahead.css file which I included in the page's <head> (or accessible .css)

.tt-dropdown-menu {
  width: 252px;
  margin-top: 12px;
  padding: 8px 0;
  background-color: #fff;
  border: 1px solid #ccc;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 8px;
     -moz-border-radius: 8px;
          border-radius: 8px;
  -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
     -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
          box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.typeahead {
  background-color: #fff;
}
.typeahead:focus {
  border: 2px solid #0097cf;
}
.tt-query {
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
     -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
  color: #999
}
.tt-suggestion {
  padding: 3px 20px;
  font-size: 18px;
  line-height: 24px;
}
.tt-suggestion.tt-cursor {
  color: #fff;
  background-color: #0097cf;
}
.tt-suggestion p {
  margin: 0;
}

'Static readonly' vs. 'const'

This is just a supplement to the other answers. I will not repeat them (now four years later).

There are situations where a const and a non-const have different semantics. For example:

const int y = 42;

static void Main()
{
  short x = 42;
  Console.WriteLine(x.Equals(y));
}

prints out True, whereas:

static readonly int y = 42;

static void Main()
{
  short x = 42;
  Console.WriteLine(x.Equals(y));
}

writes False.

The reason is that the method x.Equals has two overloads, one that takes in a short (System.Int16) and one that takes an object (System.Object). Now the question is whether one or both apply with my y argument.

When y is a compile-time constant (literal), the const case, it becomes important that there does exist an implicit conversion from int to short provided that the int is a constant, and provided that the C# compiler verifies that its value is within the range of a short (which 42 is). See Implicit constant expression conversions in the C# Language Specification. So both overloads have to be considered. The overload Equals(short) is preferred (any short is an object, but not all object are short). So y is converted to short, and that overload is used. Then Equals compares two short of identical value, and that gives true.

When y is not a constant, no implicit conversion from int to short exists. That's because in general an int may be too huge to fit into a short. (An explicit conversion does exist, but I didn't say Equals((short)y), so that's not relevant.) We see that only one overload applies, the Equals(object) one. So y is boxed to object. Then Equals is going to compare a System.Int16 to a System.Int32, and since the run-time types do not even agree, that will yield false.

We conclude that in some (rare) cases, changing a const type member to a static readonly field (or the other way, when that is possible) can change the behavior of the program.

C++ - Hold the console window open?

You can also lean on the IDE a little. If you run the program using the "Start without debugging" command (Ctrl+F5 for me), the console window will stay open even after the program ends with a "Press any key to continue . . ." message.

Of course, if want to use the "Hit any key" to keep your program running (i.e. keep a thread alive), this won't work. And it does not work when you run "with debugging". But then you can use break points to hold the window open.

How to get a context in a recycler view adapter

You can define:

Context ctx; 

And on onCreate initialise ctx to:

ctx=parent.getContext(); 

Note: Parent is a ViewGroup.

Cannot run Eclipse; JVM terminated. Exit code=13

In my case JAVA path was not set in Env variables. Started to work after correct path was set in Env PATH.

Type javac in command prompt and make sure JAVA PATH is correct.

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, Both are functionally the same thing. But in C++ you should switch to nullptr in the place of NULL;

Attribute Error: 'list' object has no attribute 'split'

what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not

`def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = str(readfile.readlines())

    Type = readlines.split(",")
    x = Type[1]
    y = Type[2]
    for points in Type:
        print(x,y)
getQuakeData()`

Set select option 'selected', by value

You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue], so in your case you can select the option and set the selected attribute.

$("div.id_100 > select > option[value=" + value + "]").prop("selected",true);

Where value is the value you wish to select by.

If you need to removed any prior selected values, as would be the case if this is used multiple times you'd need to change it slightly so as to first remove the selected attribute

$("div.id_100 option:selected").prop("selected",false);
$("div.id_100 option[value=" + value + "]")
        .prop("selected",true);

mysql after insert trigger which updates another table's column

DELIMITER //

CREATE TRIGGER contacts_after_insert
AFTER INSERT
   ON contacts FOR EACH ROW

BEGIN

   DECLARE vUser varchar(50);

   -- Find username of person performing the INSERT into table
   SELECT USER() INTO vUser;

   -- Insert record into audit table
   INSERT INTO contacts_audit
   ( contact_id,
     deleted_date,
     deleted_by)
   VALUES
   ( NEW.contact_id,
     SYSDATE(),
     vUser );

END; //

DELIMITER ;

How to get Javascript Select box's selected text

I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()

Django gives Bad Request (400) when DEBUG = False

I had to stop the apache server first.

(f.e. sudo systemctl stop httpd.service / sudo systemctl disable httpd.service).

That solved my problem besides editing the 'settings.py' file

to ALLOWED_HOSTS = ['se.rv.er.ip', 'www.example.com']

How to hide elements without having them take space on the page?

Toggling display does not allow for smooth CSS transitions. Instead toggle both the visibility and the max-height.

visibility: hidden;
max-height: 0;

Twitter Bootstrap Datepicker within modal window

I had this error, because i scrolled bottom. Datepicker had wrong top position in fixed. I just use it now like:

$('#myModal').on('show.bs.modal', function (e) {
            $(document).scrollTop(0);
});

and its working fine now.

How to detect Windows 64-bit platform with .NET?

Enjoy ;-)

Function Is64Bit() As Boolean

    Return My.Computer.FileSystem.SpecialDirectories.ProgramFiles.Contains("Program Files (x86)")

End Function

Java: Reading integers from a file into an array

You must have an empty line in your file.

You may want to wrap your parseInt calls in a "try" block:

try {
  tall[i++] = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
  continue;
}

Or simply check for empty strings before parsing:

if (s.length() == 0) 
  continue;

Note that by initializing your index variable i inside the loop, it is always 0. You should move the declaration before the while loop. (Or make it part of a for loop.)

ES6 exporting/importing in index file

You can easily re-export the default import:

export {default as Comp1} from './Comp1.jsx';
export {default as Comp2} from './Comp2.jsx';
export {default as Comp3} from './Comp3.jsx';

There also is a proposal for ES7 ES8 that will let you write export Comp1 from '…';.

How to refresh activity after changing language (Locale) inside application

You can use recreate(); to restart your activity when Language change.

I am using following code to restart activity when language change:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Configuration config = getBaseContext().getResources().getConfiguration();

String lang = settings.getString("lang_list", "");

if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang)) {
      recreate();  //this is used for recreate activity
      Locale locale = new Locale(lang);
      Locale.setDefault(locale);
      config.locale = locale;
      getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}

Processing Symbol Files in Xcode

It compares crash logs retrieved from the device to archived (symbolized to be correct) version of your applications to try to retrieved where on your code the crash occurred.

Look at xcode symbol file location for details

Algorithm to find Largest prime factor of a number

#python implementation
import math
n = 600851475143
i = 2
factors=set([])
while i<math.sqrt(n):
   while n%i==0:
       n=n/i
       factors.add(i)
   i+=1
factors.add(n)
largest=max(factors)
print factors
print largest

Accessing constructor of an anonymous class

From the Java Language Specification, section 15.9.5.1:

An anonymous class cannot have an explicitly declared constructor.

Sorry :(

EDIT: As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:

public class Test {
    public static void main(String[] args) throws Exception {
        final int fakeConstructorArg = 10;

        Object a = new Object() {
            {
                System.out.println("arg = " + fakeConstructorArg);
            }
        };
    }
}

It's grotty, but it might just help you. Alternatively, use a proper nested class :)

Adding JPanel to JFrame

Your Test2 class is not a Component, it has a Component which is a difference.

Either you do something like

frame.add(test.getPanel() );

after you introduced a getter for the panel in your class, or you make sure your Test2 class becomes a Component (e.g. by extending a JPanel)

Reading a text file with SQL Server

Just discovered this:

SELECT * FROM OPENROWSET(BULK N'<PATH_TO_FILE>', SINGLE_CLOB) AS Contents

It'll pull in the contents of the file as varchar(max). Replace SINGLE_CLOB with:

SINGLE_NCLOB for nvarchar(max) SINGLE_BLOB for varbinary(max)

Thanks to http://www.mssqltips.com/sqlservertip/1643/using-openrowset-to-read-large-files-into-sql-server/ for this!

DisplayName attribute from Resources?

public class Person
{
    // Before C# 6.0
    [Display(Name = "Age", ResourceType = typeof(Testi18n.Resource))]
    public string Age { get; set; }

    // After C# 6.0
    // [Display(Name = nameof(Resource.Age), ResourceType = typeof(Resource))]
}
  1. Define ResourceType of the attribute so it looks for a resource
  2. Define Name of the attribute which is used for the key of resource, after C# 6.0, you can use nameof for strong typed support instead of hard coding the key.

  3. Set the culture of current thread in the controller.

Resource.Culture = CultureInfo.GetCultureInfo("zh-CN");

  1. Set the accessibility of the resource to public

  2. Display the label in cshtml like this

@Html.DisplayNameFor(model => model.Age)

SQL how to make null values come last when sorting ascending

Thanks RedFilter for providing excellent solution to the bugging issue of sorting nullable datetime field.

I am using SQL Server database for my project.

Changing the datetime null value to '1' does solves the problem of sorting for datetime datatype column. However if we have column with other than datetime datatype then it fails to handle.

To handle a varchar column sort, I tried using 'ZZZZZZZ' as I knew the column does not have values beginning with 'Z'. It worked as expected.

On the same lines, I used max values +1 for int and other data types to get the sort as expected. This also gave me the results as were required.

However, it would always be ideal to get something easier in the database engine itself that could do something like:

Order by Col1 Asc Nulls Last, Col2 Asc Nulls First 

As mentioned in the answer provided by a_horse_with_no_name.

How to navigate through a vector using iterators? (C++)

Typically, iterators are used to access elements of a container in linear fashion; however, with "random access iterators", it is possible to access any element in the same fashion as operator[].

To access arbitrary elements in a vector vec, you can use the following:

vec.begin()                  // 1st
vec.begin()+1                // 2nd
// ...
vec.begin()+(i-1)            // ith
// ...
vec.begin()+(vec.size()-1)   // last

The following is an example of a typical access pattern (earlier versions of C++):

int sum = 0;
using Iter = std::vector<int>::const_iterator;
for (Iter it = vec.begin(); it!=vec.end(); ++it) {
    sum += *it;
}

The advantage of using iterator is that you can apply the same pattern with other containers:

sum = 0;
for (Iter it = lst.begin(); it!=lst.end(); ++it) {
    sum += *it;
}

For this reason, it is really easy to create template code that will work the same regardless of the container type. Another advantage of iterators is that it doesn't assume the data is resident in memory; for example, one could create a forward iterator that can read data from an input stream, or that simply generates data on the fly (e.g. a range or random number generator).

Another option using std::for_each and lambdas:

sum = 0;
std::for_each(vec.begin(), vec.end(), [&sum](int i) { sum += i; });

Since C++11 you can use auto to avoid specifying a very long, complicated type name of the iterator as seen before (or even more complex):

sum = 0;
for (auto it = vec.begin(); it!=vec.end(); ++it) {
    sum += *it;
}

And, in addition, there is a simpler for-each variant:

sum = 0;
for (auto value : vec) {
    sum += value;
}

And finally there is also std::accumulate where you have to be careful whether you are adding integer or floating point numbers.

Batch file to copy files from one folder to another folder

@echo off

rem The * at the end of the destination file is to avoid File/Directory Internal Question.

rem You can do this for each especific file. (Make sure you already have permissions to the path)
xcopy /Y "\\Oldeserver\storage\data\MyFile01.txt" "\\New server\storage\data\MyFile01.txt"*
pause

rem You can use "copy" instead of "xcopy "for this example.

PHP Call to undefined function

I happened that problem on a virtual server, when everything worked correctly on other hosting. After several modifications I realized that I include or require_one works on all calls except in a file. The problem of this file was the code < ?php ? > At the beginning and end of the text. It was a script that was only < ?, and in that version of apache that was running did not work

Copying the cell value preserving the formatting from one cell to another in excel using VBA

Copying the Bold Text From one sheet to another sheet in excel By using VBScript 'Create instance Object

Set oXL = CreateObject("Excel.application")
oXL.Visible = True

Set oWB = oXL.Workbooks.Open("FilePath.xlsx")
Set oSheet = oWB.Worksheets("Sheet1")         'Source Sheet in workbook
Set oDestSheet = oWB.Worksheets("Sheet2")       'Destination sheet in workbook

r = oSheet.usedrange.rows.Count
c = oSheet.usedrange.columns.Count

For i = 1 To r
    For j = 1 To c
        If oSheet.Cells(i,j).font.Bold = True Then

            oSheet.cells(i,j).copy
            oDestSheet.Cells(i,j).pastespecial
        End If
    Next
Next

oWB.Close
oXL.Quit

SelectSingleNode returning null for known good xml node path using XPath

just use //id instead of /id. It works fine in my code

Enable IIS7 gzip

If you are also trying to gzip dynamic pages (like aspx) and it isnt working, its probably because the option is not enabled (you need to install the Dynamic Content Compression module using Windows Features):

http://support.esri.com/en/knowledgebase/techarticles/detail/38616

Parameterize an SQL IN clause

Use the following stored procedure. It uses a custom split function, which can be found here.

 create stored procedure GetSearchMachingTagNames 
    @PipeDelimitedTagNames varchar(max), 
    @delimiter char(1) 
    as  
    begin
         select * from Tags 
         where Name in (select data from [dbo].[Split](@PipeDelimitedTagNames,@delimiter) 
    end

What's the strangest corner case you've seen in C# or .NET?

I think the answer to the question is because .net uses string interning something that might cause equal strings to point to the same object (since a strings are mutable this is not a problem)

(I'm not talking about the overridden equality operator on the string class)

Powershell 2 copy-item which creates a folder if doesn't exist

Yes, add the -Force parameter.

copy-item $from $to -Recurse -Force

Java8: sum values from specific field of the objects in a list

You can do

int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();

or (using Method reference)

int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();

Reading in from System.in - Java

You probably looking for something like this.

FileInputStream in = new FileInputStream("inputFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));

Java generics - ArrayList initialization

You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.

ArrayList<? extends Object> is an ArrayList whose type parameter is known to be Object or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList<?>.

That is, you can put an ArrayList<String> into a variable declared with ArrayList<?>. That's why a1.add(3) is a compile time error. a1's declared type permits a1 to be an ArrayList<String>, to which no Integer can be added.

Clearly, an ArrayList<?> is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:

It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments

ArrayList<ArrayList<?>> in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList<?> only contains but is not a wildcard type, the above rule does not apply.

Creating a JSON dynamically with each input value using jquery

same from above example - if you are just looking for json (not an array of object) just use

function getJsonDetails() {
      item = {}
      item ["token1"] = token1val;
      item ["token2"] = token1val;
      return item;
}
console.log(JSON.stringify(getJsonDetails()))

this output ll print as (a valid json)

{ 
   "token1":"samplevalue1",
   "token2":"samplevalue2"
}

What are the differences between normal and slim package of jquery?

I found a difference when creating a Form Contact: slim (recommended by boostrap 4.5):

  • After sending an email the global variables get stuck, and that makes if the user gives f5 (reload page) it is sent again. min:
  • The previous error will be solved. how i suffered!

Advantage of switch over if-else statement

Im not the person to tell you about speed and memory usage, but looking at a switch statment is a hell of a lot easier to understand then a large if statement (especially 2-3 months down the line)

CSS3 100vh not constant in mobile browser

A nice read about the problem and its possible solutions can be found in this blog post: Addressing the iOS Address Bar in 100vh Layouts

The solution I ended up in my React application is utilising the react-div-100vh library described in the post above.

make bootstrap twitter dialog modal draggable

For the mouse cursor (with jQuery UI) :

$('#my-modal').draggable({
    handle: ".modal-header"
});

For the touch cursor (with jQuery):

var box = null;
var touchobj = null;
var position = {'x':0, 'y':0};
var positionbox = {'x':0, 'y':0};

// init touch
$('.modal-header').on('touchstart', function(e){
    box = $(this).closest('.modal-dialog');
    touchobj = e.changedTouches[0];

    // take position touch cursor
    position['x'] = touchobj.pageX;
    position['y'] = touchobj.pageY;

    //take original position box to move with touch
    positionbox['x'] = parseInt(box.css('left'));
    positionbox['y'] = parseInt(box.css('top'));

    e.preventDefault();
});

// on move touch
$('.modal-header').on('touchmove', function(e){
    var dist = {'x':0, 'y':0};
    touchobj = e.changedTouches[0];

    // we calculate the distance of move
    dist['x'] = parseInt(touchobj.clientX) - position['x'];
    dist['y'] = parseInt(touchobj.clientY) - position['y'];

    // we apply the movement distance on the box
    box.css('left', positionbox['x']+dist['x'] +"px");
    box.css('top', positionbox['y']+dist['y'] +"px");

    e.preventDefault();
});

The addition of the 2 solutions is compatible

Apache giving 403 forbidden errors

In my case it was failing as the IP of my source server was not whitelisted in the target server.

For e.g. I was trying to access https://prodcat.ref.test.co.uk from application running on my source server. On source server find IP by ifconfig

This IP should be whitelisted in the target Server's apache config file. If its not then get it whitelist.

Steps to add a IP for whitelisting (if you control the target server as well) ssh to the apache server sudo su - cd /usr/local/apache/conf/extra (actual directories can be different based on your config)

Find the config file for the target application for e.g. prodcat-443.conf

RewriteCond %{REMOTE_ADDR} <YOUR Server's IP> 
for e.g.
RewriteCond %{REMOTE_ADDR} !^192\.68\.2\.98

Hope this helps someone

Get selected row item in DataGrid WPF

You can also:

DataRowView row = dataGrid.SelectedItem as DataRowView;
MessageBox.Show(row.Row.ItemArray[1].ToString());

Autowiring fails: Not an managed Type

you need check packagesToScan.

<bean id="entityManagerFactoryDB" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    <property name="dataSource" ref="dataSourceDB" />
    <property name="persistenceUnitName" value="persistenceUnitDB" />
    <property name="packagesToScan" value="at.naviclean.domain" />
                                            //here
 .....

What is the difference between compare() and compareTo()?

Employee Table
Name, DoB, Salary
Tomas , 2/10/1982, 300
Daniel , 3/11/1990, 400
Kwame , 2/10/1998, 520

The Comparable interface allows you to sort a list of objects eg Employees with reference to one primary field – for instance, you could sort by name or by salary with the CompareTo() method

emp1.getName().compareTo(emp2.getName())

A more flexible interface for such requirements is provided by the Comparator interface, whose only method is compare()

public interface Comparator<Employee> {
 int compare(Employee obj1, Employee obj2);
}

Sample code

public class NameComparator implements Comparator<Employee> {

public int compare(Employee e1, Employee e2) {
     // some conditions here
        return e1.getName().compareTo(e2.getName()); // returns 1 since (T)omas > (D)an 
    return e1.getSalary().compareTo(e2.getSalary()); // returns -1 since 400 > 300
}

}

Style bottom Line in Android

Try next xml drawable code:

    <layer-list>
        <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
            <shape>
                <solid android:color="@android:color/transparent" />
                <stroke
                    android:width="1dp"
                    android:color="#fff" />
            </shape>
        </item>
    </layer-list>

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How to center buttons in Twitter Bootstrap 3?

Wrap the Button in div with "text-center" class.

Just change this:

<!-- wrong -->
<div class="col-md-4 center-block">
    <button id="singlebutton" name="singlebutton" class="btn btn-primary center-block">Next Step!</button>
</div>

To this:

<!-- correct -->
<div class="col-md-4 text-center"> 
    <button id="singlebutton" name="singlebutton" class="btn btn-primary">Next Step!</button> 
</div>

Edit

As of BootstrapV4, center-block was dropped #19102 in favor of m-*-auto

The provider is not compatible with the version of Oracle client

Here's what I did to solve this problem that persisted for 3 long hours:

  1. Under Oracle home located at C:\oracle\product\11.2.0 I had a folder called client_1 where I had previously installed ODP.NET bits for Windows 64 bits.

  2. Later while trying to debug my ASP.NET Web API app with Visual Studio 2012, I kept getting this error message: The provider is not compatible with the version of Oracle client.

  3. Searching Google I found that this was happening because I was using ODP.NET 64 bits. Then I grabbed ODP.NET for Windows 32 bits and installed it but I kept getting the same error message.

  4. SOLUTION: deleted the folder client_1 and resinstalled ODP.NET 32 bits. Somewhat the installer was mixing bits from the 64 bit version with the 32 bit version. Go figure...

  5. Now I'm happy again and I can open a new OracleConnection. FINALLY! :)

In AVD emulator how to see sdcard folder? and Install apk to AVD?

DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files.

Counting in a FOR loop using Windows Batch script

for a = 1 to 100 step 1

Command line in Windows . Please use %%a if running in Batch file.

    for /L %a in (1,1,100) Do echo %a 

How do I make my string comparison case insensitive?

  • The best would be using s1.equalsIgnoreCase(s2): (see javadoc)
  • You can also convert them both to upper/lower case and use s1.equals(s2)

curl : (1) Protocol https not supported or disabled in libcurl

Got the answer HERE for windows, it says there that:

curl -XPUT 'http://localhost:9200/api/twittervnext/tweet'

Woops, first try and already an error:

curl: (1) Protocol 'http not supported or disabled in libcurl

The reason for this error is kind of stupid, Windows doesn’t like it when you are using single quotes for commands. So the correct command is:

curl –XPUT "http://localhost:9200/api/twittervnext/tweet"

how to change default python version?

According to a quick google search, this update only applies to the current shell you have open. It can probably be fixed by typing python3, as mac and linux are similar enough for things like this to coincide. Link to the result of google search.

Also, as ninjagecko stated, most programs have not been updated to 3.x yet, so having the default python as 3.x would break many python scripts used in applications.

Find Oracle JDBC driver in Maven repository

For dependency

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>

Try

<repository>
    <id>mvnrepository</id>
    <url>http://nexus.saas.hand-china.com/content/repositories/rdc</url>
</repository>

Press TAB and then ENTER key in Selenium WebDriver

In python this work for me

self.set_your_value = "your value"

def your_method_name(self):      
    self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`

Using multiple .cpp files in c++ program?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.

other.h

void MyFunc();

main.cpp

#include "other.h"
int main() {
    MyFunc();
}

other.cpp

#include "other.h"
#include <iostream>
void MyFunc() {
    std::cout << "Ohai from another .cpp file!";
    std::cin.get();
}

Jquery: how to sleep or delay?

If you can't use the delay method as Robert Harvey suggested, you can use setTimeout.

Eg.

setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

How do I make a semi transparent background?

Try this:

.transparent
{ 
  opacity:.50;
  -moz-opacity:.50; 
  filter:alpha(opacity=50); 
}

Groovy / grails how to determine a data type?

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

Android ListView with different layouts for each row

ListView was intended for simple use cases like the same static view for all row items.
Since you have to create ViewHolders and make significant use of getItemViewType(), and dynamically show different row item layout xml's, you should try doing that using the RecyclerView, which is available in Android API 22. It offers better support and structure for multiple view types.

Check out this tutorial on how to use the RecyclerView to do what you are looking for.

Add one year in current date PYTHON

It seems from your question that you would like to simply increment the year of your given date rather than worry about leap year implications. You can use the date class to do this by accessing its member year.

from datetime import date
startDate = date(2012, 12, 21)

# reconstruct date fully
endDate = date(startDate.year + 1, startDate.month, startDate.day)
# replace year only
endDate = startDate.replace(startDate.year + 1)

If you're having problems creating one given your format, let us know.

Remove background drawable programmatically in Android

This work for me:

yourview.setBackground(null);

How to transfer some data to another Fragment?

            First Fragment Sending String To Next Fragment
            public class MainActivity extends AppCompatActivity {
                    private Button Add;
                    private EditText edt;
                    FragmentManager fragmentManager;
                    FragClass1 fragClass1;


                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        Add= (Button) findViewById(R.id.BtnNext);
                        edt= (EditText) findViewById(R.id.editText);

                        Add.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                fragClass1=new FragClass1();
                                Bundle bundle=new Bundle();

                                fragmentManager=getSupportFragmentManager();
                                fragClass1.setArguments(bundle);
                                bundle.putString("hello",edt.getText().toString());
                                FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
                                fragmentTransaction.add(R.id.activity_main,fragClass1,"");
                                fragmentTransaction.addToBackStack(null);
                                fragmentTransaction.commit();

                            }
                        });
                    }
                }
         Next Fragment to fetch the string.
            public class FragClass1 extends Fragment {
                  EditText showFrag1;


                    @Nullable
                    @Override
                    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

                        View view=inflater.inflate(R.layout.lay_frag1,null);
                        showFrag1= (EditText) view.findViewById(R.id.edtText);
                        Bundle bundle=getArguments();
                        String a=getArguments().getString("hello");//Use This or The Below Commented Code
                        showFrag1.setText(a);
                        //showFrag1.setText(String.valueOf(bundle.getString("hello")));
                        return view;
                    }
                }
    I used Frame Layout easy to use.
    Don't Forget to Add Background color or else fragment will overlap.
This is for First Fragment.
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@color/colorPrimary"
        tools:context="com.example.sumedh.fragmentpractice1.MainActivity">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/BtnNext"/>
    </FrameLayout>


Xml for Next Fragment.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
   android:background="@color/colorAccent"
    android:layout_height="match_parent">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtText"/>

</LinearLayout>

Validate form field only on submit or user input

Use $dirty flag to show the error only after user interacted with the input:

<div>
  <input type="email" name="email" ng-model="user.email" required />
  <span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span>
</div>

If you want to trigger the errors only after the user has submitted the form than you may use a separate flag variable as in:

<form ng-submit="submit()" name="form" ng-controller="MyCtrl">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
      Email is required
    </span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>
function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  } 
};

Then, if all that JS inside ng-showexpression looks too much for you, you can abstract it into a separate method:

function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  }

  $scope.hasError = function(field, validation){
    if(validation){
      return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
    }
    return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
  };

};
<form ng-submit="submit()" name="form">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="hasError('email', 'required')">required</span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>

How to find the difference in days between two dates?

This works for me:

A="2002-10-20"
B="2003-11-22"
echo $(( ($(date -d $B +%s) - $(date -d $A +%s)) / 86400 )) days

Prints

398 days

What is happening?

  1. Provide valid time string in A and B
  2. Use date -d to handle time strings
  3. Use date %s to convert time strings to seconds since 1970 (unix epoche)
  4. Use bash parameter expansion to subtract seconds
  5. divide by seconds per day (86400=60*60*24) to get difference as days
  6. ! DST is not taken into account ! See this answer at unix.stackexchange!

Run a Java Application as a Service on Linux

You can use Thrift server or JMX to communicate with your Java service.

Getting list of Facebook friends with latest API

If you want to use the REST end point,

$friends = $facebook->api(array('method' => 'friends.get'));

else if you are using the graph api, then use,

$friends = $facebook->api('/me/friends');

how to prevent css inherit

you can load the new content in an iframe to avoid css inheritance.

How do I show the changes which have been staged?

git gui and git-cola are graphical utilities that let you view and manipulate the index. Both include simple visual diffs for staged files, and git-cola can also launch a more sophisticated side-by-side visual diff tool.

See my closely related answer at How to remove a file from the index in git?, and also this official catalog of Git - GUI Clients.

How to create Password Field in Model Django

You should create a ModelForm (docs), which has a field that uses the PasswordInput widget from the forms library.

It would look like this:

models.py

from django import models
class User(models.Model):
    username = models.CharField(max_length=100)
    password = models.CharField(max_length=50)

forms.py (not views.py)

from django import forms
class UserForm(forms.ModelForm):
    class Meta:
        model = User
        widgets = {
        'password': forms.PasswordInput(),
    }

For more about using forms in a view, see this section of the docs.

Rotation of 3D vector?

Use scipy's Rotation.from_rotvec(). The argument is the rotation vector (a unit vector) multiplied by the rotation angle in rads.

from scipy.spatial.transform import Rotation
from numpy.linalg import norm


v = [3, 5, 0]
axis = [4, 4, 1]
theta = 1.2

axis = axis / norm(axis)  # normalize the rotation vector first
rot = Rotation.from_rotvec(theta * axis)

new_v = rot.apply(v)  
print(new_v)    # results in [2.74911638 4.77180932 1.91629719]

There are several more ways to use Rotation based on what data you have about the rotation:

  • from_quat Initialized from quaternions.

  • from_dcm Initialized from direction cosine matrices.

  • from_euler Initialized from Euler angles.


Off-topic note: One line code is not necessarily better code as implied by some users.

How to write one new line in Bitbucket markdown?

Feb 3rd 2020:

  • Atlassian Bitbucket v5.8.3 local installation.
  • I wanted to add a new line around an horizontal line. --- did produce the line, but I could not get new lines to work with suggestions above.
  • note: I did not want to use the [space][space] suggestion, since my editor removes trailing spaces on save, and I like this feature on.

I ended up doing this:

TEXT...
<br><hr><br>
TEXT...

Resulting in:

TEXT...
<AN EMPTY LINE>
----------------- AN HORIZONTAL LINE ----------------
<AN EMPTY LINE>
TEXT...

Show loading screen when navigating between routes in Angular 2

The current Angular Router provides Navigation Events. You can subscribe to these and make UI changes accordingly. Remember to count in other Events such as NavigationCancel and NavigationError to stop your spinner in case router transitions fail.

app.component.ts - your root component

...
import {
  Router,
  // import as RouterEvent to avoid confusion with the DOM Event
  Event as RouterEvent,
  NavigationStart,
  NavigationEnd,
  NavigationCancel,
  NavigationError
} from '@angular/router'

@Component({})
export class AppComponent {

  // Sets initial value to true to show loading spinner on first load
  loading = true

  constructor(private router: Router) {
    this.router.events.subscribe((e : RouterEvent) => {
       this.navigationInterceptor(e);
     })
  }

  // Shows and hides the loading spinner during RouterEvent changes
  navigationInterceptor(event: RouterEvent): void {
    if (event instanceof NavigationStart) {
      this.loading = true
    }
    if (event instanceof NavigationEnd) {
      this.loading = false
    }

    // Set loading state to false in both of the below events to hide the spinner in case a request fails
    if (event instanceof NavigationCancel) {
      this.loading = false
    }
    if (event instanceof NavigationError) {
      this.loading = false
    }
  }
}

app.component.html - your root view

<div class="loading-overlay" *ngIf="loading">
    <!-- show something fancy here, here with Angular 2 Material's loading bar or circle -->
    <md-progress-bar mode="indeterminate"></md-progress-bar>
</div>

Performance Improved Answer: If you care about performance there is a better method, it is slightly more tedious to implement but the performance improvement will be worth the extra work. Instead of using *ngIf to conditionally show the spinner, we could leverage Angular's NgZone and Renderer to switch on / off the spinner which will bypass Angular's change detection when we change the spinner's state. I found this to make the animation smoother compared to using *ngIf or an async pipe.

This is similar to my previous answer with some tweaks:

app.component.ts - your root component

...
import {
  Router,
  // import as RouterEvent to avoid confusion with the DOM Event
  Event as RouterEvent,
  NavigationStart,
  NavigationEnd,
  NavigationCancel,
  NavigationError
} from '@angular/router'
import {NgZone, Renderer, ElementRef, ViewChild} from '@angular/core'


@Component({})
export class AppComponent {

  // Instead of holding a boolean value for whether the spinner
  // should show or not, we store a reference to the spinner element,
  // see template snippet below this script
  @ViewChild('spinnerElement')
  spinnerElement: ElementRef

  constructor(private router: Router,
              private ngZone: NgZone,
              private renderer: Renderer) {
    router.events.subscribe(this._navigationInterceptor)
  }

  // Shows and hides the loading spinner during RouterEvent changes
  private _navigationInterceptor(event: RouterEvent): void {
    if (event instanceof NavigationStart) {
      // We wanna run this function outside of Angular's zone to
      // bypass change detection
      this.ngZone.runOutsideAngular(() => {
        // For simplicity we are going to turn opacity on / off
        // you could add/remove a class for more advanced styling
        // and enter/leave animation of the spinner
        this.renderer.setElementStyle(
          this.spinnerElement.nativeElement,
          'opacity',
          '1'
        )
      })
    }
    if (event instanceof NavigationEnd) {
      this._hideSpinner()
    }
    // Set loading state to false in both of the below events to
    // hide the spinner in case a request fails
    if (event instanceof NavigationCancel) {
      this._hideSpinner()
    }
    if (event instanceof NavigationError) {
      this._hideSpinner()
    }
  }

  private _hideSpinner(): void {
    // We wanna run this function outside of Angular's zone to
    // bypass change detection,
    this.ngZone.runOutsideAngular(() => {
      // For simplicity we are going to turn opacity on / off
      // you could add/remove a class for more advanced styling
      // and enter/leave animation of the spinner
      this.renderer.setElementStyle(
        this.spinnerElement.nativeElement,
        'opacity',
        '0'
      )
    })
  }
}

app.component.html - your root view

<div class="loading-overlay" #spinnerElement style="opacity: 0;">
    <!-- md-spinner is short for <md-progress-circle mode="indeterminate"></md-progress-circle> -->
    <md-spinner></md-spinner>
</div>

how to convert 2d list to 2d numpy array?

just use following code

c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

Then it will give you

you can check shape and dimension of matrix by using following code

c.shape

c.ndim

How can I echo the whole content of a .html file in PHP?

If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include or require. Simply do:

echo file_get_contents("/path/to/file.html");

retrieve links from web page using python and BeautifulSoup

Links can be within a variety of attributes so you could pass a list of those attributes to select

for example, with src and href attribute (here I am using the starts with ^ operator to specify that either of these attributes values starts with http. You can tailor this as required

from bs4 import BeautifulSoup as bs
import requests
r = requests.get('https://stackoverflow.com/')
soup = bs(r.content, 'lxml')
links = [item['href'] if item.get('href') is not None else item['src'] for item in soup.select('[href^="http"], [src^="http"]') ]
print(links)

Attribute = value selectors

[attr^=value]

Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.

Java Generate Random Number Between Two Given Values

You could use e.g. r.nextInt(101)

For a more generic "in between two numbers" use:

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

This gives you a random number in between 10 (inclusive) and 100 (exclusive)

Is it possible to install iOS 6 SDK on Xcode 5?

I currently have Xcode 4.6.3 and 5.0 installed. I used the following bash script to link 5.0 to the SDKs in the old version:

platforms_path="$1/Contents/Developer/Platforms";
if [ -d $platforms_path ]; then
    for platform in `ls $platforms_path`
    do
        sudo ln -sf $platforms_path/$platform/Developer/SDKs/* $(xcode-select --print-path)/Platforms/$platform/Developer/SDKs;
    done;
fi;

You just need to supply it with the path to the .app:

./xcode.sh /Applications/Xcode-463.app

Choice between vector::resize() and vector::reserve()

reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.

Is there any better choice in this kind of scenario?

it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.

fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?

Delete files older than 3 months old in a directory using .NET

An SSIS type of example .. (if this helps anyone)

          public void Main()
          {
                 // TODO: Add your code here
        // Author: Allan F 10th May 2019

        //first part of process .. put any files of last Qtr (or older) in Archive area 
        //e.g. if today is 10May2019 then last quarter is 1Jan2019 to 31March2019 .. any files earlier than 31March2019 will be archived

        //string SourceFileFolder = "\\\\adlsaasf11\\users$\\aford05\\Downloads\\stage\\";
        string SourceFilesFolder = (string)Dts.Variables["SourceFilesFolder"].Value;
        string ArchiveFolder = (string)Dts.Variables["ArchiveFolder"].Value;
        string FilePattern = (string)Dts.Variables["FilePattern"].Value;
        string[] files = Directory.GetFiles(SourceFilesFolder, FilePattern);

        //DateTime date = new DateTime(2019, 2, 15);//commented out line .. just for testing the dates .. 

        DateTime date = DateTime.Now;
        int quarterNumber = (date.Month - 1) / 3 + 1;
        DateTime firstDayOfQuarter = new DateTime(date.Year, (quarterNumber - 1) * 3 + 1, 1);
        DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);

        DateTime LastDayOfPriorQuarter = firstDayOfQuarter.AddDays(-1);
        int PrevQuarterNumber = (LastDayOfPriorQuarter.Month - 1) / 3 + 1;
        DateTime firstDayOfLastQuarter = new DateTime(LastDayOfPriorQuarter.Year, (PrevQuarterNumber - 1) * 3 + 1, 1);
        DateTime lastDayOfLastQuarter = firstDayOfLastQuarter.AddMonths(3).AddDays(-1);

        //MessageBox.Show("debug pt2: firstDayOfQuarter" + firstDayOfQuarter.ToString("dd/MM/yyyy"));
        //MessageBox.Show("debug pt2: firstDayOfLastQuarter" + firstDayOfLastQuarter.ToString("dd/MM/yyyy"));


        foreach (string file in files)
        {
            FileInfo fi = new FileInfo(file);

            //MessageBox.Show("debug pt2:" + fi.Name + " " + fi.CreationTime.ToString("dd/MM/yyyy HH:mm") + " " + fi.LastAccessTime.ToString("dd/MM/yyyy HH:mm") + " " + fi.LastWriteTime.ToString("dd/MM/yyyy HH:mm"));
            if (fi.LastWriteTime < firstDayOfQuarter)
            {

                try
                {

                    FileInfo fi2 = new FileInfo(ArchiveFolder);

                    //Ensure that the target does not exist.
                    //fi2.Delete();

                    //Copy the file.
                    fi.CopyTo(ArchiveFolder + fi.Name);
                    //Console.WriteLine("{0} was copied to {1}.", path, ArchiveFolder);

                    //Delete the old location file.
                    fi.Delete();
                    //Console.WriteLine("{0} was successfully deleted.", ArchiveFolder);

                }
                catch (Exception e)
                {
                    //do nothing
                    //Console.WriteLine("The process failed: {0}", e.ToString());
                }
            }
        }

        //second part of process .. delete any files in Archive area dated earlier than last qtr ..
        //e.g. if today is 10May2019 then last quarter is 1Jan2019 to 31March2019 .. any files earlier than 1Jan2019 will be deleted

        string[] archivefiles = Directory.GetFiles(ArchiveFolder, FilePattern);
        foreach (string archivefile in archivefiles)
        {
            FileInfo fi = new FileInfo(archivefile);
            if (fi.LastWriteTime < firstDayOfLastQuarter )
            {
                try
                {
                    fi.Delete();
                }
                catch (Exception e)
                {
                    //do nothing
                }
            }
        }


                 Dts.TaskResult = (int)ScriptResults.Success;
          }

Use a URL to link to a Google map with a marker on it

In May 2017 Google launched the official Google Maps URLs documentation. The Google Maps URLs introduces universal cross-platform syntax that you can use in your applications.

Have a look at the following document:

https://developers.google.com/maps/documentation/urls/guide

You can use URLs in search, directions, map and street view modes.

For example, to show the marker at specified position you can use the following URL:

https://www.google.com/maps/search/?api=1&query=36.26577,-92.54324

For further details please read aforementioned documentation.

You can also file feature requests for this API in Google issue tracker.

Hope this helps!

Laravel - Model Class not found

As @bulk said, it uses namespaces.

I recommend you to start using an IDE, it will suggest you to import all the required namespaces (\App\Post in this case).

android.view.InflateException: Binary XML file: Error inflating class fragment

I had this on a 4.4.2 device, but 5+ was fine. The cause: inside a custom view's initialisation, I was creating a TextView(Context context, AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes), which is API 21+.

Android Studio 2.1 doesn't complain about it even though it is annotated TargetApi(21). Apparently, Android Studio 2.2 will correct this and properly show it as an error.

Hope this helps someone.

Removing items from a list

for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
    String a = iter.next();
    if (...) {
        iter.remove();
    }
}

Making an additional assumption that the list is of strings. As already answered, an list.iterator() is needed. The listIterator can do a bit of navigation too.