Programs & Examples On #Explicit implementation

jQuery: Currency Format Number

Please find in the below code what I developed to support internationalization. It formats the given numeric value to language specific format. In the given example I have used ‘en’ while have tested for ‘es’, ‘fr’ and other countries where in the format varies. It not only stops user from keying characters but formats the value on tab out. Have created components for Number as well as for Decimal format. Apart from this have created parseNumber(value, locale) and parseDecimal(value, locale) functions which will parse the formatted data for any other business purposes. The said function will accept the formatted data and will return the non-formatted value. I have used JQuery validator plugin in the below shared code.

HTML:

<tr>
                            <td>
                                <label class="control-label">
                                    Number Field:
                                </label>
                                <div class="inner-addon right-addon">                                        
                                    <input type="text" id="numberField" 
                                           name="numberField"
                                           class="form-control"
                                           autocomplete="off"
                                           maxlength="17"
                                           data-rule-required="true"
                                           data-msg-required="Cannot be blank."
                                           data-msg-maxlength="Exceeding the maximum limit of 13 digits. Example: 1234567890123"
                                           data-rule-numberExceedsMaxLimit="en"
                                           data-msg-numberExceedsMaxLimit="Exceeding the maximum limit of 13 digits. Example: 1234567890123"
                                           onkeydown="return isNumber(event, 'en')"
                                           onkeyup="return updateField(this)"
                                           onblur="numberFormatter(this,                                                           
                                                       'en', 
                                                       'Invalid character(s) found. Please enter valid characters.')">
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <label class="control-label">
                                    Decimal Field:
                                </label>
                                <div class="inner-addon right-addon">                                        
                                    <input type="text" id="decimalField" 
                                           name="decimalField"
                                           class="form-control"
                                           autocomplete="off"
                                           maxlength="20"
                                           data-rule-required="true"
                                           data-msg-required="Cannot be blank."
                                           data-msg-maxlength="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"
                                           data-rule-decimalExceedsMaxLimit="en"
                                           data-msg-decimalExceedsMaxLimit="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"
                                           onkeydown="return isDecimal(event, 'en')"
                                           onkeyup="return updateField(this)"
                                           onblur="decimalFormatter(this,
                                               'en', 
                                               'Invalid character(s) found. Please enter valid characters.')">
                                </div>
                            </td>
                        </tr>

JavaScript:

            /* 
     * @author: dinesh.lomte
     */
    /* Holds the maximum limit of digits to be entered in number field. */
    var numericMaxLimit = 13;
    /* Holds the maximum limit of digits to be entered in decimal field. */
    var decimalMaxLimit = 16;

    /**
     * 
     * @param {type} value
     * @param {type} locale
     * @returns {Boolean}
     */
    parseDecimal = function(value, locale) {

        value = value.trim();
        if (isNull(value)) {
            return 0.00;
        }
        if (isNull(locale)) {
            return value;
        }
        if (getNumberFormat(locale)[0] === '.') {
            value = value.replace(/\./g, '');
        } else {
            value = value.replace(
                    new RegExp(getNumberFormat(locale)[0], 'g'), '');
        }
        if (getNumberFormat(locale)[1] === ',') {
            value = value.replace(
                    new RegExp(getNumberFormat(locale)[1], 'g'), '.');
        }
        return value;
    };

    /**
     * 
     * @param {type} element
     * @param {type} locale
     * @param {type} nanMessage
     * @returns {Boolean}
     */
    decimalFormatter = function (element, locale, nanMessage) {

        showErrorMessage(element.id, false, null);
        if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
            return true;
        }
        var value = element.value.trim();
        value = value.replace(/\s/g, '');
        value = parseDecimal(value, locale);
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
        );
        if (numberFormatObj.format(value) === 'NaN') {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        element.value =
                numberFormatObj.format(value);
        return true;
    };

    /**
     * 
     * @param {type} element
     * @param {type} locale
     * @param {type} nanMessage
     * @returns {Boolean}
     */
    numberFormatter = function (element, locale, nanMessage) {

        showErrorMessage(element.id, false, null);
        if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
            return true;
        }
        var value = element.value.trim();    
        var format = getNumberFormat(locale);
        if (hasDecimal(value, format[1])) {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        value = value.replace(/\s/g, '');
        value = parseNumber(value, locale);
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 0,
                    maximumFractionDigits: 0
                }
        );
        if (numberFormatObj.format(value) === 'NaN') {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        element.value =
                numberFormatObj.format(value);
        return true;
    };

    /**
     * 
     * @param {type} id
     * @param {type} flag
     * @param {type} message
     * @returns {undefined}
     */
    showErrorMessage = function(id, flag, message) {

        if (flag) {
            // only add if not added
            if ($('#'+id).parent().next('.app-error-message').length === 0) {
                var errorTag = '<div class=\'app-error-message\'>' + message + '</div>';
                $('#'+id).parent().after(errorTag);
            }
        } else {
            // remove it
            $('#'+id).parent().next(".app-error-message").remove(); 
        }
    };

    /**
     * 
     * @param {type} id             
     * @returns
     */
    setFocus = function(id) {

        id = id.trim();
        if (isNull(id)) {
            return;
        }
        setTimeout(function() {
            document.getElementById(id).focus();
        }, 10);
    };

    /**
     * 
     * @param {type} value
     * @param {type} locale
     * @returns {Array}
     */
    parseNumber = function(value, locale) {

        value = value.trim();
        if (isNull(value)) {
            return 0;
        }    
        if (isNull(locale)) {
            return value;
        }
        if (getNumberFormat(locale)[0] === '.') {
            return value.replace(/\./g, '');
        }
        return value.replace(
                new RegExp(getNumberFormat(locale)[0], 'g'), '');
    };

    /**
     * 
     * @param {type} locale
     * @returns {Array}
     */
    getNumberFormat = function(locale) {

        var format = [];
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
        );
        var value = numberFormatObj.format('132617.07');
        format[0] = value.charAt(3);
        format[1] = value.charAt(7);
        return format;
    };

    /**
     * 
     * @param {type} value
     * @param {type} fractionFormat
     * @returns {Boolean}
     */
    hasDecimal = function(value, fractionFormat) {

        value = value.trim();
        if (isNull(value) || isNull(fractionFormat)) {
            return false;
        }
        if (value.indexOf(fractionFormat) >= 1) {
            return true;
        }
    };

    /**
     * 
     * @param {type} event
     * @param {type} locale
     * @returns {Boolean}
     */
    isNumber = function(event, locale) {

        var keyCode = event.which ? event.which : event.keyCode;
        // Validating if user has pressed shift character
        if (keyCode === 16) {
            return false;
        }
        if (isNumberKey(keyCode)) {        
            return true;
        }
        var numberFormatter = [32, 110, 188, 190];
        if (keyCode === 32
                && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
            return true;
        }
        if (numberFormatter.indexOf(keyCode) >= 0
                && getNumberFormat(locale)[0] === getFormat(keyCode)) {        
            return true;
        }    
        return false;
    };

    /**
     * 
     * @param {type} event
     * @param {type} locale
     * @returns {Boolean}
     */
    isDecimal = function(event, locale) {

        var keyCode = event.which ? event.which : event.keyCode;
        // Validating if user has pressed shift character
        if (keyCode === 16) {
            return false;
        }
        if (isNumberKey(keyCode)) {
            return true;
        }
        var numberFormatter = [32, 110, 188, 190];
        if (keyCode === 32
                && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
            return true;
        }
        if (numberFormatter.indexOf(keyCode) >= 0
                && (getNumberFormat(locale)[0] === getFormat(keyCode)
                    || getNumberFormat(locale)[1] === getFormat(keyCode))) {
            return true;
        }
        return false;
    };

    /**
     * 
     * @param {type} keyCode
     * @returns {Boolean}
     */
    isNumberKey = function(keyCode) {

        if ((keyCode >= 48 && keyCode <= 57)
                || (keyCode >= 96 && keyCode <= 105)) {        
            return true;
        }
        var keys = [8, 9, 13, 35, 36, 37, 39, 45, 46, 109, 144, 173, 189];
        if (keys.indexOf(keyCode) !== -1) {        
            return true;
        }
        return false;
    };

    /**
     * 
     * @param {type} keyCode
     * @returns {JSON@call;parse.numberFormatter.value|String}
     */
    getFormat = function(keyCode) {

        var jsonString = '{"numberFormatter" : [{"key":"32", "value":" ", "description":"space"}, {"key":"188", "value":",", "description":"comma"}, {"key":"190", "value":".", "description":"dot"}, {"key":"110", "value":".", "description":"dot"}]}';
        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.numberFormatter) {
            if (jsonObject.numberFormatter.hasOwnProperty(key)
                    && keyCode === parseInt(jsonObject.numberFormatter[key].key)) {
                return jsonObject.numberFormatter[key].value;
            }
        }
        return '';
    };

    /**
     * 
     * @type String
     */
    var jsonString = '{"shiftCharacterNumberMap" : [{"char":")", "number":"0"}, {"char":"!", "number":"1"}, {"char":"@", "number":"2"}, {"char":"#", "number":"3"}, {"char":"$", "number":"4"}, {"char":"%", "number":"5"}, {"char":"^", "number":"6"}, {"char":"&", "number":"7"}, {"char":"*", "number":"8"}, {"char":"(", "number":"9"}]}';

    /**
     * 
     * @param {type} value
     * @returns {JSON@call;parse.shiftCharacterNumberMap.number|String}
     */
    getShiftCharSpecificNumber = function(value) {

        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.shiftCharacterNumberMap) {
            if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
                    && value === jsonObject.shiftCharacterNumberMap[key].char) {
                return jsonObject.shiftCharacterNumberMap[key].number;
            }
        }
        return '';
    };

    /**
     * 
     * @param {type} value
     * @returns {Boolean}
     */
    isShiftSpecificChar = function(value) {

        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.shiftCharacterNumberMap) {
            if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
                    && value === jsonObject.shiftCharacterNumberMap[key].char) {
                return true;
            }
        }
        return false;
    };

    /**
     * 
     * @param {type} element
     * @returns {undefined}
     */
    updateField = function(element) {

        var value = element.value;

        for (var index = 0; index < value.length; index++) {
            if (!isShiftSpecificChar(value.charAt(index))) {
                continue;
            }
            element.value = value.replace(
                    value.charAt(index),
                    getShiftCharSpecificNumber(value.charAt(index)));
        }
    };

    /**
     * 
     * @param {type} value
     * @param {type} element
     * @param {type} params
     */
    jQuery.validator.addMethod('numberExceedsMaxLimit', function(value, element, params) {

        value = parseInt(parseNumber(value, params));
        if (value.toString().length > numericMaxLimit) {
            showErrorMessage(element.id, false, null);
            setFocus(element.id);
            return false;
        }    
        return true;
    }, 'Exceeding the maximum limit of 13 digits. Example: 1234567890123.');

    /**
     * 
     * @param {type} value
     * @param {type} element
     * @param {type} params
     */
    jQuery.validator.addMethod('decimalExceedsMaxLimit', function(value, element, params) {

        value = parseFloat(parseDecimal(value, params)).toFixed(2);    
        if (value.toString().substring(
                0, value.toString().lastIndexOf('.')).length > numericMaxLimit
                || value.toString().length > decimalMaxLimit) {
            showErrorMessage(element.id, false, null);
            setFocus(element.id);
            return false;
        }    
        return true;
    }, 'Exceeding the maximum limit of 16 digits. Example: 1234567890123.00.');

    /**
     * @param {type} id
     * @param {type} locale
     * @returns {boolean}
     */
    isNumberExceedMaxLimit = function(id, locale) {

        var value = parseInt(parseNumber(
                document.getElementById(id).value, locale));
        if (value.toString().length > numericMaxLimit) {
            setFocus(id);
            return true;
        }    
        return false;
    };

    /**
     * @param {type} id
     * @param {type} locale
     * @returns {boolean}
     */
    isDecimalExceedsMaxLimit = function(id, locale) {

        var value = parseFloat(parseDecimal(
                document.getElementById(id).value, locale)).toFixed(2);
        if (value.toString().substring(
                0, value.toString().lastIndexOf('.')).length > numericMaxLimit
                || value.toString().length > decimalMaxLimit) {
            setFocus(id);
            return true;
        }
        return false;
    };

Javascript swap array elements

try this function...

_x000D_
_x000D_
$(document).ready(function () {_x000D_
        var pair = [];_x000D_
        var destinationarray = ['AAA','BBB','CCC'];_x000D_
_x000D_
        var cityItems = getCityList(destinationarray);_x000D_
        for (var i = 0; i < cityItems.length; i++) {_x000D_
            pair = [];_x000D_
            var ending_point = "";_x000D_
            for (var j = 0; j < cityItems[i].length; j++) {_x000D_
                pair.push(cityItems[i][j]);_x000D_
            }_x000D_
            alert(pair);_x000D_
            console.log(pair)_x000D_
        }_x000D_
_x000D_
    });_x000D_
    function getCityList(inputArray) {_x000D_
        var Util = function () {_x000D_
        };_x000D_
_x000D_
        Util.getPermuts = function (array, start, output) {_x000D_
            if (start >= array.length) {_x000D_
                var arr = array.slice(0);_x000D_
                output.push(arr);_x000D_
            } else {_x000D_
                var i;_x000D_
_x000D_
                for (i = start; i < array.length; ++i) {_x000D_
                    Util.swap(array, start, i);_x000D_
                    Util.getPermuts(array, start + 1, output);_x000D_
                    Util.swap(array, start, i);_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
_x000D_
        Util.getAllPossiblePermuts = function (array, output) {_x000D_
            Util.getPermuts(array, 0, output);_x000D_
        }_x000D_
_x000D_
        Util.swap = function (array, from, to) {_x000D_
            var tmp = array[from];_x000D_
            array[from] = array[to];_x000D_
            array[to] = tmp;_x000D_
        }_x000D_
        var output = [];_x000D_
        Util.getAllPossiblePermuts(inputArray, output);_x000D_
        return output;_x000D_
    }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Getting a "This application is modifying the autolayout engine from a background thread" error?

I had this issue when I was using TouchID if that helps anyone else, wrap your success logic which likely does something with the UI in the main queue.

How do I get a substring of a string in Python?

I would like to add two points to the discussion:

  1. You can use None instead on an empty space to specify "from the start" or "to the end":

    'abcde'[2:None] == 'abcde'[2:] == 'cde'
    

    This is particularly helpful in functions, where you can't provide an empty space as an argument:

    def substring(s, start, end):
        """Remove `start` characters from the beginning and `end` 
        characters from the end of string `s`.
    
        Examples
        --------
        >>> substring('abcde', 0, 3)
        'abc'
        >>> substring('abcde', 1, None)
        'bcde'
        """
        return s[start:end]
    
  2. Python has slice objects:

    idx = slice(2, None)
    'abcde'[idx] == 'abcde'[2:] == 'cde'
    

adb uninstall failed

If you have problems uninstalling through adb, I can recommend the following tool:

https://github.com/patrickfav/uber-adb-tools

you can use wildcards and supports multiple devices, also has some better error handling than the vanilla ADB (but uses it in background of course). Will work on your platform.

console showcase

Full disclaimer: I am the developer

How to format a floating number to fixed width in Python

for x in numbers:
    print "{:10.4f}".format(x)

prints

   23.2300
    0.1233
    1.0000
    4.2230
 9887.2000

The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:

  • The empty string before the colon means "take the next provided argument to format()" – in this case the x as the only argument.
  • The 10.4f part after the colon is the format specification.
  • The f denotes fixed-point notation.
  • The 10 is the total width of the field being printed, lefted-padded by spaces.
  • The 4 is the number of digits after the decimal point.

git checkout master error: the following untracked working tree files would be overwritten by checkout

do a :

git branch

if git show you something like :

* (no branch)
master
Dbranch

You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with

git checkout master 

Now you should be able to delete the Dbranch.

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

It should be CascadeType.Merge, in that case it will update if the record already exists.

How to check if a value exists in a dictionary (python)

In Python 3 you can use the values() function of the dictionary. It returns a view object of the values. This, in turn, can be passed to the iter function which returns an iterator object. The iterator can be checked using in, like this,

'one' in iter(d.values())

Or you can use the view object directly since it is similar to a list

'one' in d.values()

Difference between .dll and .exe?

There are a few more differences regarding the structure you could mention.

  1. Both DLL and EXE share the same file structure - Portable Executable, or PE. To differentiate between the two, one can look in the Characteristics member of IMAGE_FILE_HEADER inside IMAGE_NT_HEADERS. For a DLL, it has the IMAGE_FILE_DLL (0x2000) flag turned on. For a EXE it's the IMAGE_FILE_EXECUTABLE_IMAGE (0x2) flag.
  2. PE files consist of some headers and a number of sections. There's usually a section for code, a section for data, a section listing imported functions and a section for resources. Some sections may contain more than one thing. The header also describes a list of data directories that are located in the sections. Those data directories are what enables Windows to find what it needs in the PE. But one type of data directory that an EXE will never have (unless you're building a frankenstein EXE) is the export directory. This is where DLL files have a list of functions they export and can be used by other EXE or DLL files. On the other side, each DLL and EXE has an import directory where it lists the functions and DLL files it requires to run.
  3. Also in the PE headers (IMAGE_OPTIONAL_HEADER) is the ImageBase member. It specifies the virtual address at which the PE assumes it will be loaded. If it is loaded at another address, some pointers could point to the wrong memory. As EXE files are amongst the first to be loaded into their new address space, the Windows loader can assure a constant load address and that's usually 0x00400000. That luxury doesn't exist for a DLL. Two DLL files loaded into the same process can request the same address. This is why a DLL has another data directory called Base Relocation Directory that usually resides in its own section - .reloc. This directory contains a list of places in the DLL that need to be rebased/patched so they'll point to the right memory. Most EXE files don't have this directory, but some old compilers do generate them.

You can read more on this topic @ MSDN.

Client on Node.js: Uncaught ReferenceError: require is not defined

This is because require() does not exist in the browser/client-side JavaScript.

Now you're going to have to make some choices about your client-side JavaScript script management.

You have three options:

  1. Use the <script> tag.
  2. Use a CommonJS implementation. It has synchronous dependencies like Node.js
  3. Use an asynchronous module definition (AMD) implementation.

CommonJS client side-implementations include (most of them require a build step before you deploy):

  1. Browserify - You can use most Node.js modules in the browser. This is my personal favorite.
  2. Webpack - Does everything (bundles JavaScript code, CSS, etc.). It was made popular by the surge of React, but it is notorious for its difficult learning curve.
  3. Rollup - a new contender. It leverages ES6 modules and includes tree-shaking abilities (removes unused code).

You can read more about my comparison of Browserify vs (deprecated) Component.

AMD implementations include:

  1. RequireJS - Very popular amongst client-side JavaScript developers. It is not my taste because of its asynchronous nature.

Note, in your search for choosing which one to go with, you'll read about Bower. Bower is only for package dependencies and is unopinionated on module definitions like CommonJS and AMD.

Convert NSData to String?

Objective-C

You can use (see NSString Class Reference)

- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding

Example:

NSString *myString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];

Remark: Please notice the NSData value must be valid for the encoding specified (UTF-8 in the example above), otherwise nil will be returned:

Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding).

Prior Swift 3.0

String(data: yourData, encoding: NSUTF8StringEncoding)

Swift 3.0 Onwards

String(data: yourData, encoding: .utf8)

See String#init(data:encoding:) Reference

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

using jQuery .animate to animate a div from right to left?

If you know the width of the child element you are animating, you can use and animate a margin offset as well. For example, this will animate from left:0 to right:0

CSS:

.parent{
width:100%;
position:relative;
}

#itemToMove{
position:absolute;
width:150px;
right:100%;
margin-right:-150px;
}

Javascript:

$( "#itemToMove" ).animate({
"margin-right": "0",
"right": "0"
}, 1000 );

Timeout for python requests.get entire response

Set the timeout parameter:

r = requests.get(w, verify=False, timeout=10) # 10 seconds

As long as you don't set stream=True on that request, this will cause the call to requests.get() to timeout if the connection takes more than ten seconds, or if the server doesn't send data for more than ten seconds.

Java properties UTF-8 encoding in Eclipse

Properties props = new Properties();
URL resource = getClass().getClassLoader().getResource("data.properties");         
props.load(new InputStreamReader(resource.openStream(), "UTF8"));

Works like a charm

:-)

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.

e.g.:

Return None value.

>>> def test1():
...    print "In function."
... 
>>> a = test1()
In function.
>>> print a
None
>>> 
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>> 

Use return statement

>>> def test():
...   return "ACV"
... 
>>> print test()
ACV
>>> 
>>> a = test()
>>> print a
ACV
>>> 

Offset a background image from the right using CSS

The most appropriate answer is the new four-value syntax for background-position, but until all browsers support it your best approach is a combination of earlier responses in the following order:

background: url(image.png) no-repeat 97% center; /* default, Android, Sf < 6 */
background-position: -webkit-calc(100% - 10px) center; /* Sf 6 */
background-position: right 10px center; /* Cr 25+, FF 13+, IE 9+, Op 10.5+ */

SQL Server : check if variable is Empty or NULL for WHERE clause

If you can use some dynamic query, you can use LEN . It will give false on both empty and null string. By this way you can implement the option parameter.

ALTER PROCEDURE [dbo].[psProducts] 
(@SearchType varchar(50))
AS
BEGIN
    SET NOCOUNT ON;

DECLARE @Query nvarchar(max) = N'
    SELECT 
        P.[ProductId],
        P.[ProductName],
        P.[ProductPrice],
        P.[Type]
    FROM [Product] P'
    -- if @Searchtype is not null then use the where clause
    SET @Query = CASE WHEN LEN(@SearchType) > 0 THEN @Query + ' WHERE p.[Type] = ' + ''''+ @SearchType + '''' ELSE @Query END   

    EXECUTE sp_executesql @Query
    PRINT @Query
END

Combine two integer arrays

Here a simple function that use variable arguments:

final static
public int[] merge(final int[] ...arrays ) {
    int size = 0;
    for ( int[] a: arrays )
        size += a.length;

        int[] res = new int[size];

        int destPos = 0;
        for ( int i = 0; i < arrays.length; i++ ) {
            if ( i > 0 ) destPos += arrays[i-1].length;
            int length = arrays[i].length;
            System.arraycopy(arrays[i], 0, res, destPos, length);
        }

        return res;
}

To use:

int[] array1 = {1,2,3};
int[] array2 = {4,5,6};
int[] array3 = {7,8,9};
int[] array1and2and3 = merge(array1, array2, array3);
for ( int x: array1and2and3 ) 
    System.out.print( String.format("%3d", x) );

How to call URL action in MVC with javascript function?

try:

var url = '/Home/Index/' + e.value;
 window.location = window.location.host + url; 

That should get you where you want.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

I Understood your problem add this dependency in your pom.xml your problem will be solved,

https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.38

How do I add an "Add to Favorites" button or link on my website?

I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:

jQuery('.bookmarkMeLink').click(function() {
    if (window.sidebar && window.sidebar.addPanel) { 
        // Mozilla Firefox Bookmark
        window.sidebar.addPanel(document.title,window.location.href,'');
    }
    else if(window.sidebar && jQuery.browser.mozilla){
        //for other version of FF add rel="sidebar" to link like this:
        //<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
        jQuery(this).attr('rel', 'sidebar');
    }
    else if(window.external && ('AddFavorite' in window.external)) { 
        // IE Favorite
        window.external.AddFavorite(location.href,document.title); 
    } else if(window.opera && window.print) { 
        // Opera Hotlist
        this.title=document.title;
        return true;
    } else { 
        // webkit - safari/chrome
        alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');

    }
});

How to use and style new AlertDialog from appCompat 22.1 and above

Follow @reVerse answer but in my case, I already had some property in my AppTheme like

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    ...
    <item name="android:textColor">#111</item>
    <item name="android:textSize">13sp</item>
</style>

So my dialog will look like
enter image description here

I solved it by

1) Change the import from android.app.AlertDialog to android.support.v7.app.AlertDialog
2) I override 2 property in AppTheme with null value

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!-- Used for the buttons -->
    <item name="colorAccent">#FFC107</item>
    <!-- Used for the title and text -->
    <item name="android:textColorPrimary">#FFFFFF</item>
    <!-- Used for the background -->
    <item name="android:background">#4CAF50</item>


    <item name="android:textColor">@null</item>
    <item name="android:textSize">@null</item>
</style>

.

AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.MyAlertDialogStyle);

Hope it help another people

enter image description here

How to store images in mysql database using php

if(isset($_POST['form1']))
{
    try
    {


        $user=$_POST['username'];

        $pass=$_POST['password'];
        $email=$_POST['email'];
        $roll=$_POST['roll'];
        $class=$_POST['class'];



        if(empty($user)) throw new Exception("Name can not empty");
        if(empty($pass)) throw new Exception("Password can not empty");
        if(empty($email)) throw new Exception("Email can not empty");
        if(empty($roll)) throw new Exception("Roll can not empty");
        if(empty($class)) throw new Exception("Class can not empty");


        $statement=$db->prepare("show table status like 'tbl_std_info'");
        $statement->execute();
        $result=$statement->fetchAll();
        foreach($result as $row)
        $new_id=$row[10];


        $up_file=$_FILES["image"]["name"];

        $file_basename=substr($up_file, 0 , strripos($up_file, "."));
        $file_ext=substr($up_file, strripos($up_file, ".")); 
        $f1="$new_id".$file_ext;

        if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif"))
        {
            throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload / Empty Logo Field");
        }
        move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1);


        $statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)");

        $statement->execute(array($user,$f1,$pass,$email,$roll,$class));


        $success="Registration Successfully Completed";

        echo $success;
    }
    catch(Exception $e)
    {
        $msg=$e->getMessage();
    }
}

Inheriting constructors

This is straight from Bjarne Stroustrup's page:

If you so choose, you can still shoot yourself in the foot by inheriting constructors in a derived class in which you define new member variables needing initialization:

struct B1 {
    B1(int) { }
};

struct D1 : B1 {
    using B1::B1; // implicitly declares D1(int)
    int x;
};

void test()
{
    D1 d(6);    // Oops: d.x is not initialized
    D1 e;       // error: D1 has no default constructor
}

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
}
catch [System.SystemException] {
  write-host 'SystemException'
}
catch [System.Exception] {
  write-host 'Exception'
}
catch {
  write-host 'well, darn'
}

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
  do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
}
catch {
  write-host 'well, darn'
}

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    }
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    }
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    }
    'System.SystemException' {
      write-host 'SystemException'
    }
    'System.Exception' {
      write-host 'Exception'
    }
    default {'well, darn'}
  }
}

This writes 'ItemNotFound', as it should.

Cannot open Windows.h in Microsoft Visual Studio

The right combination of Windows SDK Version and Platform Toolset needs to be selected Depends of course what toolset you have currently installed

SDK Version and Platform Toolset

How can I add a vertical scrollbar to my div automatically?

To show vertical scroll bar in your div you need to add

height: 100px;   
overflow-y : scroll;

or

height: 100px; 
overflow-y : auto;

How can I do division with variables in a Linux shell?

Referencing Bash Variables Requires Parameter Expansion

The default shell on most Linux distributions is Bash. In Bash, variables must use a dollar sign prefix for parameter expansion. For example:

x=20
y=5
expr $x / $y

Of course, Bash also has arithmetic operators and a special arithmetic expansion syntax, so there's no need to invoke the expr binary as a separate process. You can let the shell do all the work like this:

x=20; y=5
echo $((x / y))

IE11 meta element Breaks SVG

I was having the same problem with 3 of 4 inline svgs I was using, and they only disappeared (in one case, partially) on IE11.

I had <meta http-equiv="x-ua-compatible" content="ie=edge"> on the page.

In the end, the problem was extra clipping paths on the svg file. I opened the files on Illustrator, removed the clipping path (normally at the bottom of the layers) and now they're all working.

How to checkout a specific Subversion revision from the command line?

If you already have it checked out locally then you can cd to where it is checked out, then use this syntax:

$ svn up -rXXXX

ref: Checkout a specific revision from subversion from command line

Is it possible to access an SQLite database from JavaScript?

Up to date answer

My fork of sql.js has now be merged into the original version, on kriken's repo.

The good documentation is also available on the original repo.

Original answer (outdated)

You should use the newer version of sql.js. It is a port of sqlite 3.8, has a good documentation and is actively maintained (by me). It supports prepared statements, and BLOB data type.

Cloning an Object in Node.js

There are some Node modules out there if don't want to "roll your own". This one looks good: https://www.npmjs.com/package/clone

Looks like it handles all kinds of stuff, including circular references. From the github page:

clone masters cloning objects, arrays, Date objects, and RegEx objects. Everything is cloned recursively, so that you can clone dates in arrays in objects, for example. [...] Circular references? Yep!

Drawing Isometric game worlds

If you have some tiles that exceed the bounds of your diamond, I recommend drawing in depth order:

...1...
..234..
.56789.
..abc..
...d...

How do I check for vowels in JavaScript?

  //function to find vowel
const vowel = (str)=>{
  //these are vowels we want to check for
  const check = ['a','e','i','o','u'];
  //keep track of vowels
  var count = 0;
  for(let char of str.toLowerCase())
  {
    //check if each character in string is in vowel array
    if(check.includes(char)) count++;
  }
  return count;
}

console.log(vowel("hello there"));

Convert char to int in C and C++

I have absolutely null skills in C, but for a simple parsing:

char* something = "123456";

int number = parseInt(something);

...this worked for me:

int parseInt(char* chars)
{
    int sum = 0;
    int len = strlen(chars);
    for (int x = 0; x < len; x++)
    {
        int n = chars[len - (x + 1)] - '0';
        sum = sum + powInt(n, x);
    }
    return sum;
}

int powInt(int x, int y)
{
    for (int i = 0; i < y; i++)
    {
        x *= 10;
    }
    return x;
}

Change all files and folders permissions of a directory to 644/755

This worked for me:

find /A -type d -exec chmod 0755 {} \;
find /A -type f -exec chmod 0644 {} \;

How can I get zoom functionality for images?

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageDetail = (ImageView) findViewById(R.id.imageView1);
    imageDetail.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            System.out.println("matrix=" + savedMatrix.toString());
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    savedMatrix.set(matrix);
                    startPoint.set(event.getX(), event.getY());
                    mode = DRAG;
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    oldDist = spacing(event);
                    if (oldDist > 10f) {
                        savedMatrix.set(matrix);
                        midPoint(midPoint, event);
                        mode = ZOOM;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        matrix.set(savedMatrix);
                        matrix.postTranslate(event.getX() - startPoint.x, event.getY() - startPoint.y);
                    } else if (mode == ZOOM) {
                        float newDist = spacing(event);
                        if (newDist > 10f) {
                            matrix.set(savedMatrix);
                            float scale = newDist / oldDist;
                            matrix.postScale(scale, scale, midPoint.x, midPoint.y);
                        }
                    }
                    break;
            }
            view.setImageMatrix(matrix);
            return true;

        }

        @SuppressLint("FloatMath")
        private float spacing(MotionEvent event) {
            float x = event.getX(0) - event.getX(1);
            float y = event.getY(0) - event.getY(1);
            return FloatMath.sqrt(x * x + y * y);
        }

        private void midPoint(PointF point, MotionEvent event) {
            float x = event.getX(0) + event.getX(1);
            float y = event.getY(0) + event.getY(1);
            point.set(x / 2, y / 2);
        }
    });
}

and drawable folder should have bticn image file. perfectly works :)

Set initial value in datepicker with jquery?

You can set the value in the HTML and then init datepicker to start/highlight the actual date

<input name="datefrom" type="text" class="datepicker" value="20-1-2011">
<input name="dateto" type="text" class="datepicker" value="01-01-2012">
<input name="dateto2" type="text" class="datepicker" >


$(".datepicker").each(function() {    
    $(this).datepicker('setDate', $(this).val());
});

The above even works with danish date formats

http://jsfiddle.net/DDsBP/2/

Division of integers in Java

Convert both completed and total to double or at least cast them to double when doing the devision. I.e. cast the varaibles to double not just the result.

Fair warning, there is a floating point precision problem when working with float and double.

How to tell if browser/tab is active

In addition to Richard Simões answer you can also use the Page Visibility API.

if (!document.hidden) {
    // do what you need
}

This specification defines a means for site developers to programmatically determine the current visibility state of the page in order to develop power and CPU efficient web applications.

Learn more (2019 update)

How to retrieve an element from a set without removing it?

I f you want just the first element try this: b = (a-set()).pop()

Change text color with Javascript?

Try below code:

$(document).ready(function(){
$('#about').css({'background-color':'black'});    
});

http://jsfiddle.net/jPCFC/

Compile c++14-code with g++

G++ does support C++14 both via -std=c++14 and -std=c++1y. The latter was the common name for the standard before it was known in which year it would be released. In older versions (including yours) only the latter is accepted as the release year wasn't known yet when those versions were released.

I used "sudo apt-get install g++" which should automatically retrieve the latest version, is that correct?

It installs the latest version available in the Ubuntu repositories, not the latest version that exists.

The latest GCC version is 5.2.

What is the best way to call a script from another script?

The usual way to do this is something like the following.

test1.py

def some_func():
    print 'in test 1, unproductive'

if __name__ == '__main__':
    # test1.py executed as script
    # do something
    some_func()

service.py

import test1

def service_func():
    print 'service func'

if __name__ == '__main__':
    # service.py executed as script
    # do something
    service_func()
    test1.some_func()

How do I debug error ECONNRESET in Node.js?

Had the same problem today. After some research i found a very useful --abort-on-uncaught-exception node.js option. Not only it provides much more verbose and useful error stack trace, but also saves core file on application crash allowing further debug.

ArrayAdapter in android to create simple listview

For your question answer is android.R.id.text1 is int: The id of the TextView within the layout resource to be populated.

ArrayAdapter has so many constructors with different number of arguments I'm mention some of them

ArrayAdapter(Context context, int resource)
ArrayAdapter(Context context, int resource, int textViewResourceId)
ArrayAdapter(Context context, int resource, T[] objects)
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
ArrayAdapter(Context context, int resource, List<T> objects)
ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects)

Now you can understand each and every constructor is different and they used different list of arguments.

And simple answer is you can use ArrayAdapter with text view inside a target xml file or without. It is doesn't matter. And you not need specify text view id you can use it without. But you may need to go with some advance option with your simple list view you must go with a text view.!

Here sample example

ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.ListView,StringArray);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);

This is also a valid code you can use with much more clear.

How to reverse a singly linked list using only two pointers?

A simple algorithm if you use the linked list as a stack structure:

 #include <stdio.h>
#include <stdlib.h>

typedef struct list {
    int key;
    char value;
    struct list* next;
} list;
void print(list*);
void add(list**, int, char);
void reverse(list**);
void deleteList(list*);

int main(void) {
    list* head = NULL;
    int i=0;
    while ( i++ < 26 ) add(&head, i, i+'a');
    printf("Before reverse: \n");
    print(head);
    printf("After reverse: \n");
    reverse(&head);
    print(head);
    deleteList(head);

}
void deleteList(list* l) {

    list* t = l;    
    while ( t != NULL ) {
        list* tmp = t;
        t = t->next;
        free(tmp);
    }

}
void print(list* l) {
    list* t = l;
    while ( t != NULL) {
        printf("%d:%c\n", t->key, t->value);
        t = t->next;
    }
}

void reverse(list** head) {
    list* tmp = *head;
    list* reversed = NULL;
    while ( tmp != NULL ) {
        add(&reversed, tmp->key, tmp->value);
        tmp = tmp->next;
    }
    deleteList(*head);
    *head = reversed;
}

void add(list** head, int k, char v) {

    list* t = calloc(1, sizeof(list));
    t->key = k; t->value = v;
    t->next = *head;
    *head = t;

}

The performance may be affected since additional function call to the add and malloc so the algorithms of address swaps are better but that one actually creates new list so you can use additional options like sort or remove items if you add a callback function as parameter to the reverse.

Hiding a password in a python script (insecure obfuscation only)

Why not have a simple xor?

Advantages:

  • looks like binary data
  • noone can read it without knowing the key (even if it's a single char)

I get to the point where I recognize simple b64 strings for common words and rot13 as well. Xor would make it much harder.

How to show the last queries executed on MySQL?

You can do the flowing thing for monitoring mysql query logs.

Open mysql configuration file my.cnf

sudo nano /etc/mysql/my.cnf

Search following lines under a [mysqld] heading and uncomment these lines to enable log

general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

Restart your mysql server for reflect changes

sudo service mysql start

Monitor mysql server log with following command in terminal

tail -f /var/log/mysql/mysql.log

RuntimeError on windows trying python multiprocessing

Try putting your code inside a main function in testMain.py

import parallelTestModule

if __name__ ==  '__main__':
  extractor = parallelTestModule.ParallelExtractor()
  extractor.runInParallel(numProcesses=2, numThreads=4)

See the docs:

"For an explanation of why (on Windows) the if __name__ == '__main__' 
part is necessary, see Programming guidelines."

which say

"Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process)."

... by using if __name__ == '__main__'

calling another method from the main method in java

You can only call instance method like do() (which is an illegal method name, incidentally) against an instance of the class:

public static void main(String[] args){
  new Foo().doSomething();
}

public void doSomething(){}

Alternatively, make doSomething() static as well, if that works for your design.

Javascript to set hidden form value on drop down change

Just to be different, changed my answer so that this question doesn't have 5 answers with the same code.

<html>
<head>
   <title>Page</title>  
   <script src="jquery-1.3.2.min.js"></script>
   <script>
       $(function() {
           var select = $("body").append('<form></form>').children('form')
                .append('<input type="hidden" value="" />').children('input[type=hidden]')
                .attr('id', 'hiddenValue').end()
                .append('<select></select>').children('select')
                .attr('id', 'dropdown')
                .change(function() {
                    alert($(this).val());
                });

           $.each({ one: 1, two: 2, three: 3, four: 4, five: 5 }, function(txt, val) {
               select.append('<option value="' + val + '">' + txt + '</option>');
           });
       });
</script>
</head>
   <body></body>
</html>

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

I had parsing enum problem when i was trying to pass Nullable Enum that we get from Backend. Of course it was working when we get value, but it was problem when the null comes up.

java.lang.IllegalArgumentException: No enum constant

Also the problem was when we at Parcelize read moment write some short if.

My solution for this was

1.Create companion object with parsing method.

enum class CarsType {
    @Json(name = "SMALL")
    SMALL,
    @Json(name = "BIG")
    BIG;

    companion object {
        fun nullableValueOf(name: String?) = when (name) {
            null -> null
            else -> valueOf(name)
        }
    }
}

2. In Parcerable read place use it like this

data class CarData(
    val carId: String? = null,
    val carType: CarsType?,
    val data: String?
) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        CarsType.nullableValueOf(parcel.readString()),
        parcel.readString())

Javascript for "Add to Home Screen" on iPhone?

In javascript, it is not possible but yes with the help of “Web Clips” we can create a "add to home screen" icon or shortcut in iPhone( by the code file of .mobileconfig)

https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/iPhoneOTAConfiguration/ConfigurationProfileExamples/ConfigurationProfileExamples.html

http://appdistro.cttapp.com/webclip/

after create a mobileconfig file we can pass this url in iphone safari browser install certificate and after done it check your iphone home screen there is a shortcut icon of your Web page or webapp..

Is there a method that calculates a factorial in Java?

Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.

POST string to ASP.NET Web Api application - returns null

([FromBody] IDictionary<string,object> data)

beyond top level package error in relative import

Not sure in python 2.x but in python 3.6, assuming you are trying to run the whole suite, you just have to use -t

-t, --top-level-directory directory Top level directory of project (defaults to start directory)

So, on a structure like

project_root
  |
  |----- my_module
  |          \
  |           \_____ my_class.py
  |
  \ tests
      \___ test_my_func.py

One could for example use:

python3 unittest discover -s /full_path/project_root/tests -t /full_path/project_root/

And still import the my_module.my_class without major dramas.

Using "like" wildcard in prepared statement

We can use the CONCAT SQL function.

PreparedStatement pstmt = con.prepareStatement(
      "SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();

This works perfectly for my case.

Commit history on remote repository

NB. "origin" below use to represent the upstream of a cloned repository, replace "origin" with a descriptive name for the remote repo. "remote reference" can use the same format used in clone command.

git remote add origin <remote reference>
git fetch
git log origin/master

Getting MAC Address

I dont know of a unified way, but heres something that you might find useful:

http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451

What I would do in this case would be to wrap these up into a function, and based on the OS it would run the proper command, parse as required and return only the MAC address formatted as you want. Its ofcourse all the same, except that you only have to do it once, and it looks cleaner from the main code.

Fully backup a git repo?

Whats about just make a clone of it?

git clone --mirror other/repo.git

Every repository is a backup of its remote.

How to add image in Flutter

When you adding assets directory in pubspec.yaml file give more attention in to spaces

this is wrong

flutter:
   assets:
    - assets/images/lake.jpg

This is the correct way,

flutter:
  assets:
    - assets/images/

How do you install an APK file in the Android emulator?

On Linux I do this:

  1. first see which devices I currently have: emulator -list-avds
  2. build the release cd android && ./gradlew assembleRelease
  3. install it at the emulated device "Nexus5" (you are inside the android directory, else use the full path to apk): adb -s '8e138a9c' install app/build/outputs/apk/app-release.apk

Thats it. You can also use ./gradlew installRelease

'tsc command not found' in compiling typescript

Non-admin solution

I do not have admin privileges since this machine was issued by my job.

  • get path of where node modules are being installed and copy to clipboard
    • npm config get prefix | clip
    • don't have clip? just copy output from npm config get prefix
  • add copied path to environment variables
    • my preferred method (Windows)
    • (Ctrl + R), paste rundll32 sysdm.cpl,EditEnvironmentVariables
    • under User Variables, double-click on Path > New > Paste copied path

How To Remove Outline Border From Input Button

button:focus{outline:none !important;}

add !important if it is used in Bootstrap

How do relative file paths work in Eclipse?

A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.

New run configurations default to using the project directory for the working directory, though this can also be changed.

This code shows the difference between the working directory, and the location of where the class was loaded from:

public class TellMeMyWorkingDirectory {
    public static void main(String[] args) {
        System.out.println(new java.io.File("").getAbsolutePath());
        System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
    }
}

The output is likely to be something like:

C:\your\project\directory
/C:/your/project/directory/bin/

How to get the <html> tag HTML with JavaScript / jQuery?

This is how to get the html DOM element purely with JS:

var htmlElement = document.getElementsByTagName("html")[0];

or

var htmlElement = document.querySelector("html");

And if you want to use jQuery to get attributes from it...

$(htmlElement).attr(INSERT-ATTRIBUTE-NAME);

Regular Expression Validation For Indian Phone Number and Mobile number

You can use regular expression like this.

/^[(]+\ ++\d{2}[)]+[^0]+\d{9}/

Java Generate Random Number Between Two Given Values

Assuming the upper is the upper bound and lower is the lower bound, then you can make a random number, r, between the two bounds with:

int r = (int) (Math.random() * (upper - lower)) + lower;

How to extract a single value from JSON response?

using json.loads will turn your data into a python dictionary.

Dictionaries values are accessed using ['key']

resp_str = {
  "name" : "ns1:timeSeriesResponseType",
  "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
  "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
  "value" : {
    "queryInfo" : {
      "creationTime" : 1349724919000,
      "queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
      "criteria" : {
        "locationParam" : "[ALL:103232434]",
        "variableParam" : "[00060, 00065]"
      },
      "note" : [ {
        "value" : "[ALL:103232434]",
        "title" : "filter:sites"
      }, {
        "value" : "[mode=LATEST, modifiedSince=null]",
        "title" : "filter:timeRange"
      }, {
        "value" : "sdas01",
        "title" : "server"
      } ]
    }
  },
  "nil" : false,
  "globalScope" : true,
  "typeSubstituted" : false
}

would translate into a python diction

resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000

Vertical Tabs with JQuery?

Have a look at the jQuery UI vertical Tabs Docu. I try out it, it worked fine.

<style type="text/css">
/* Vertical Tabs
----------------------------------*/
.ui-tabs-vertical { width: 55em; }
.ui-tabs-vertical .ui-tabs-nav { padding: .2em .1em .2em .2em; float: left; width: 12em; }
.ui-tabs-vertical .ui-tabs-nav li { clear: left; width: 100%; border-bottom-width: 1px !important; border-right-width: 0 !important; margin: 0 -1px .2em 0; }
.ui-tabs-vertical .ui-tabs-nav li a { display:block; }
.ui-tabs-vertical .ui-tabs-nav li.ui-tabs-selected { padding-bottom: 0; padding-right: .1em; border-right-width: 1px; border-right-width: 1px; }
.ui-tabs-vertical .ui-tabs-panel { padding: 1em; float: right; width: 40em;}
</style> 

<script>
    $(document).ready(function() {
        $("#tabs").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
        $("#tabs li").removeClass('ui-corner-top').addClass('ui-corner-left');

    });
</script>

In a bootstrap responsive page how to center a div

jsFiddle

HTML:

<div class="container" id="parent">
  <div class="row">
    <div class="col-lg-12">text
      <div class="row ">
        <div class="col-md-4 col-md-offset-4" id="child">TEXT</div>
      </div>
    </div>
  </div>
</div>

CSS:

#parent {    
    text-align: center;
}
#child {
    margin: 0 auto;
    display: inline-block;
    background: red;
    color: white;
}

How to save S3 object to a file using boto3

When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_download(s3path, destination) directly or the copy-pasted code:

def s3_download(source, destination,
                exists_strategy='raise',
                profile_name=None):
    """
    Copy a file from an S3 source to a local destination.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    destination : str
    exists_strategy : {'raise', 'replace', 'abort'}
        What is done when the destination already exists?
    profile_name : str, optional
        AWS profile

    Raises
    ------
    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    exists_strategies = ['raise', 'replace', 'abort']
    if exists_strategy not in exists_strategies:
        raise ValueError('exists_strategy \'{}\' is not in {}'
                         .format(exists_strategy, exists_strategies))
    session = boto3.Session(profile_name=profile_name)
    s3 = session.resource('s3')
    bucket_name, key = _s3_path_split(source)
    if os.path.isfile(destination):
        if exists_strategy is 'raise':
            raise RuntimeError('File \'{}\' already exists.'
                               .format(destination))
        elif exists_strategy is 'abort':
            return
    s3.Bucket(bucket_name).download_file(key, destination)

from collections import namedtuple

S3Path = namedtuple("S3Path", ["bucket_name", "key"])


def _s3_path_split(s3_path):
    """
    Split an S3 path into bucket and key.

    Parameters
    ----------
    s3_path : str

    Returns
    -------
    splitted : (str, str)
        (bucket, key)

    Examples
    --------
    >>> _s3_path_split('s3://my-bucket/foo/bar.jpg')
    S3Path(bucket_name='my-bucket', key='foo/bar.jpg')
    """
    if not s3_path.startswith("s3://"):
        raise ValueError(
            "s3_path is expected to start with 's3://', " "but was {}"
            .format(s3_path)
        )
    bucket_key = s3_path[len("s3://"):]
    bucket_name, key = bucket_key.split("/", 1)
    return S3Path(bucket_name, key)

How to remove an id attribute from a div using jQuery?

I'm not sure what jQuery api you're looking at, but you should only have to specify id.

$('#thumb').removeAttr('id');

Jquery submit form

Since a jQuery object inherits from an array, and this array contains the selected DOM elements. Saying you're using an id and so the element should be unique within the DOM, you could perform a direct call to submit by doing :

$(".nextbutton").click(function() { 
  $("#formID")[0].submit();
});

git error: failed to push some refs to remote

Because maybe have nothing to push (really, no thing to push). Do like this

git remote add origin https://github.com/donhuvy/accounting133.git
git remote -v
git add .
git commit -m"upload"
git push --set-upstream origin master

Change the remote repository url in your case. Command git remote -v you can skip, just for checking.

Insert picture/table in R Markdown

Update: since the answer from @r2evans, it is much easier to insert images into R Markdown and control the size of the image.

Images

The bookdown book does a great job of explaining that the best way to include images is by using include_graphics(). For example, a full width image can be printed with a caption below:

```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```

The reason this method is better than the pandoc approach ![your image](path/to/image):

  • It automatically changes the command based on the output format (HTML/PDF/Word)
  • The same syntax can be used to the size of the plot (fig.width), the output width in the report (out.width), add captions (fig.cap) etc.
  • It uses the best graphical devices for the output. This means PDF images remain high resolution.

Tables

knitr::kable() is the best way to include tables in an R Markdown report as explained fully here. Again, this function is intelligent in automatically selecting the correct formatting for the output selected.

```{r table}
knitr::kable(mtcars[1:5,, 1:5], caption = "A table caption")
```

If you want to make your own simple tables in R Markdown and are using R Studio, you can check out the insert_table package. It provides a tidy graphical interface for making tables.

Achieving custom styling of the table column width is beyond the scope of knitr, but the kableExtra package has been written to help achieve this: https://cran.r-project.org/web/packages/kableExtra/index.html

Style Tips

The R Markdown cheat sheet is still the best place to learn about most the basic syntax you can use.

If you are looking for potential extensions to the formatting, the bookdown package is also worth exploring. It provides the ability to cross-reference, create special headers and more: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html

when exactly are we supposed to use "public static final String"?

  1. Static means..You can use it without instantiate of the class or using any object.
  2. final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:

      public class StringTest { 
               static final String str = "Hello"; 
      public static void main(String args[]) { 
               // str = "world"; // gives error 
               System.out.println(str); // called without the help of an object                       
               System.out.println(StringTest.str);// called with class name  
                 } 
             } 
    

Thanks

Disable-web-security in Chrome 48+

Install This Chrome-plugin for Disable-web-security in Chrome::

" Allow-Control-Allow-Origin: * " link Here or you can google above plugin if you want.

it is very easy to enable and disable the security with this plugin.

Creating an instance of class

   /* 1 */ Foo* foo1 = new Foo ();

Creates an object of type Foo in dynamic memory. foo1 points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo was a POD-type, this would perform value-initialization (it doesn't apply here).

   /* 2 */ Foo* foo2 = new Foo;

Identical to before, because Foo is not a POD type.

   /* 3 */ Foo foo3;

Creates a Foo object called foo3 in automatic storage.

   /* 4 */ Foo foo4 = Foo::Foo();

Uses copy-initialization to create a Foo object called foo4 in automatic storage.

   /* 5 */ Bar* bar1 = new Bar ( *new Foo() );

Uses Bar's conversion constructor to create an object of type Bar in dynamic storage. bar1 is a pointer to it.

   /* 6 */ Bar* bar2 = new Bar ( *new Foo );

Same as before.

   /* 7 */ Bar* bar3 = new Bar ( Foo foo5 );

This is just invalid syntax. You can't declare a variable there.

   /* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );

Would work and work by the same principle to 5 and 6 if bar3 wasn't declared on in 7.

5 & 6 contain memory leaks.

Syntax like new Bar ( Foo::Foo() ); is not usual. It's usually new Bar ( (Foo()) ); - extra parenthesis account for most-vexing parse. (corrected)

How do I temporarily disable triggers in PostgreSQL?

You can also disable triggers in pgAdmin (III):

  1. Find your table
  2. Expand the +
  3. Find your trigger in Triggers
  4. Right-click, uncheck "Trigger Enabled?"

Batch files : How to leave the console window open

In the last line of the batch file that you want to keep open put a

pause >nul

Does List<T> guarantee insertion order?

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

According to MSDN:

...List "Represents a strongly typed list of objects that can be accessed by index."

The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.

You might be getting odd results from your code if you're moving the item later in the list, as your Remove() will move all of the other items down one place before the call to Insert().

Can you boil your code down to something small enough to post?

What is PHPSESSID?

PHPSESSID is an auto generated session cookie by the server which contains a random long number which is given out by the server itself

Match two strings in one line with grep

Found lines that only starts with 6 spaces and finished with:

 cat my_file.txt | grep
 -e '^      .*(\.c$|\.cpp$|\.h$|\.log$|\.out$)' # .c or .cpp or .h or .log or .out
 -e '^      .*[0-9]\{5,9\}$' # numers between 5 and 9 digist
 > nolog.txt

Auto height of div

Here is the Latest solution of the problem:

In your CSS file write the following class called .clearfix along with the pseudo selector :after

.clearfix:after {
content: "";
display: table;
clear: both;
}

Then, in your HTML, add the .clearfix class to your parent Div. For example:

<div class="clearfix">
    <div></div>
    <div></div>
</div>

It should work always. You can call the class name as .group instead of .clearfix , as it will make the code more semantic. Note that, it is Not necessary to add the dot or even a space in the value of Content between the double quotation "".

Source: http://css-snippets.com/page/2/

How to fix java.net.SocketException: Broken pipe?

SocketException: Broken pipe, is caused by the 'other end' (The client or the server) closing the connection while your code is either reading from or writing to the connection.

This is a very common exception in client/server applications that receive traffic from clients or servers outside of the application control. For example, the client is a browser. If the browser makes an Ajax call, and/or the user simply closes the page or browser, then this can effectively kill all communication unexpectedly. Basically, you will see this error any time the other end terminates their application, and you were not anticipating it.

If you experience this Exception in your application, then it means you should check your code where the IO (Input/Output) occurs and wrap it with a try/catch block to catch this IOException. It is then, up to you to decide how you want to handle this semi-valid situation.

In your case, the earliest place where you still have control is the call to HttpMethodDirector.executeWithRetry - So ensure that call is wrapped with the try/catch block, and handle it how you see fit.

I would strongly advise against logging SocketException-Broken Pipe specific errors at anything other than debug/trace levels. Else, this can be used as a form of DOS (Denial Of Service) attack by filling up the logs. Try and harden and negative-test your application for this common scenario.

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

Removing Duplicate Values from ArrayList

     public List<Contact> removeDuplicates(List<Contact> list) {
    // Set set1 = new LinkedHashSet(list);
    Set set = new TreeSet(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
                 if(((Contact)o1).getId().equalsIgnoreCase(((Contact)2).getId()) ) {
                return 0;
            }
            return 1;
        }
    });
    set.addAll(list);
    final List newList = new ArrayList(set);
    return newList;
}

Reading and displaying data from a .txt file

You most likely will want to use the FileInputStream class:

int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));

while( (character = inputStream.read()) != -1)
        buffer.append((char) character);

inputStream.close();
System.out.println(buffer);

You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.

Laravel 5 Application Key

You can generate a key by the following command:

php artisan key:generate 

The key will be written automatically in your .env file.

APP_KEY=YOUR_GENERATED_KEY

If you want to see your key after generation use --show option

php artisan key:generate --show

Note: The .env is a hidden file in your project folder.

enter image description here

ASP.NET Core Web API Authentication

You can implement a middleware which handles Basic authentication.

public async Task Invoke(HttpContext context)
{
    var authHeader = context.Request.Headers.Get("Authorization");
    if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
    {
        var token = authHeader.Substring("Basic ".Length).Trim();
        System.Console.WriteLine(token);
        var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
        var credentials = credentialstring.Split(':');
        if(credentials[0] == "admin" && credentials[1] == "admin")
        {
            var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
            var identity = new ClaimsIdentity(claims, "Basic");
            context.User = new ClaimsPrincipal(identity);
        }
    }
    else
    {
        context.Response.StatusCode = 401;
        context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
    }
    await _next(context);
}

This code is written in a beta version of asp.net core. Hope it helps.

C++ Array of pointers: delete or delete []?

Your second example is correct; you don't need to delete the monsters array itself, just the individual objects you created.

Switch in Laravel 5 - Blade

In Laravel 5.1, this works in a Blade:

<?php
    switch( $machine->disposal ) {
        case 'DISPO': echo 'Send to Property Disposition'; break;
        case 'UNIT':  echo 'Send to Unit'; break;
        case 'CASCADE': echo 'Cascade the machine'; break;
        case 'TBD':   echo 'To Be Determined (TBD)'; break;
    }
?>

Angular2 change detection: ngOnChanges not firing for nested object

In Case of Arrays you can do it like this:

In .ts file (Parent component) where you are updating your rawLapsData do it like this:

rawLapsData = somevalue; // change detection will not happen

Solution:

rawLapsData = {...somevalue}; //change detection will happen

and ngOnChanges will called in child component

Force add despite the .gitignore file

Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel

How to remove title bar from the android activity?

Add this two line in your style.xml

<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>

HTML CSS How to stop a table cell from expanding

To post Chris Dutrow's comment here as answer:

style="table-layout:fixed;" 

in the style of the table itself is what worked for me. Thanks Chris!

Full example:

<table width="55" height="55" border="0" cellspacing="0" cellpadding="0" style="border-radius:50%; border:0px solid #000000;table-layout:fixed" align="center" bgcolor="#152b47">
  <tbody>
    <td style="color:#ffffff;font-family:TW-Averta-Regular,Averta,Helvetica,Arial;font-size:11px;overflow:hidden;width:55px;text-align:center;valign:top;whitespace:nowrap;">

     Your table content here

    </td>
  </tbody>
</table>

How do I get milliseconds from epoch (1970-01-01) in Java?

How about System.currentTimeMillis()?

From the JavaDoc:

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

Java 8 introduces the java.time framework, particularly the Instant class which "...models a ... point on the time-line...":

long now = Instant.now().toEpochMilli();

Returns: the number of milliseconds since the epoch of 1970-01-01T00:00:00Z -- i.e. pretty much the same as above :-)

Cheers,

How do I make a composite key with SQL Server Management Studio?

In design mode (right click table select modify) highlight both columns right click and choose set primary key

@RequestBody and @ResponseBody annotations in Spring

Below is an example of a method in a Java controller.

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public HttpStatus something(@RequestBody MyModel myModel) 
{
    return HttpStatus.OK;
}

By using @RequestBody annotation you will get your values mapped with the model you created in your system for handling any specific call. While by using @ResponseBody you can send anything back to the place from where the request was generated. Both things will be mapped easily without writing any custom parser etc.

How to remove from a map while iterating it?

In short "How do I remove from a map while iterating it?"

  • With old map impl: You can't
  • With new map impl: almost as @KerrekSB suggested. But there are some syntax issues in what he posted.

From GCC map impl (note GXX_EXPERIMENTAL_CXX0X):

#ifdef __GXX_EXPERIMENTAL_CXX0X__
      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // DR 130. Associative erase should return an iterator.
      /**
       *  @brief Erases an element from a %map.
       *  @param  position  An iterator pointing to the element to be erased.
       *  @return An iterator pointing to the element immediately following
       *          @a position prior to the element being erased. If no such 
       *          element exists, end() is returned.
       *
       *  This function erases an element, pointed to by the given
       *  iterator, from a %map.  Note that this function only erases
       *  the element, and that if the element is itself a pointer,
       *  the pointed-to memory is not touched in any way.  Managing
       *  the pointer is the user's responsibility.
       */
      iterator
      erase(iterator __position)
      { return _M_t.erase(__position); }
#else
      /**
       *  @brief Erases an element from a %map.
       *  @param  position  An iterator pointing to the element to be erased.
       *
       *  This function erases an element, pointed to by the given
       *  iterator, from a %map.  Note that this function only erases
       *  the element, and that if the element is itself a pointer,
       *  the pointed-to memory is not touched in any way.  Managing
       *  the pointer is the user's responsibility.
       */
      void
      erase(iterator __position)
      { _M_t.erase(__position); }
#endif

Example with old and new style:

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>

using namespace std;
typedef map<int, int> t_myMap;
typedef vector<t_myMap::key_type>  t_myVec;

int main() {

    cout << "main() ENTRY" << endl;

    t_myMap mi;
    mi.insert(t_myMap::value_type(1,1));
    mi.insert(t_myMap::value_type(2,1));
    mi.insert(t_myMap::value_type(3,1));
    mi.insert(t_myMap::value_type(4,1));
    mi.insert(t_myMap::value_type(5,1));
    mi.insert(t_myMap::value_type(6,1));

    cout << "Init" << endl;
    for(t_myMap::const_iterator i = mi.begin(); i != mi.end(); i++)
        cout << '\t' << i->first << '-' << i->second << endl;

    t_myVec markedForDeath;

    for (t_myMap::const_iterator it = mi.begin(); it != mi.end() ; it++)
        if (it->first > 2 && it->first < 5)
            markedForDeath.push_back(it->first);

    for(size_t i = 0; i < markedForDeath.size(); i++)
        // old erase, returns void...
        mi.erase(markedForDeath[i]);

    cout << "after old style erase of 3 & 4.." << endl;
    for(t_myMap::const_iterator i = mi.begin(); i != mi.end(); i++)
        cout << '\t' << i->first << '-' << i->second << endl;

    for (auto it = mi.begin(); it != mi.end(); ) {
        if (it->first == 5)
            // new erase() that returns iter..
            it = mi.erase(it);
        else
            ++it;
    }

    cout << "after new style erase of 5" << endl;
    // new cend/cbegin and lambda..
    for_each(mi.cbegin(), mi.cend(), [](t_myMap::const_reference it){cout << '\t' << it.first << '-' << it.second << endl;});

    return 0;
}

prints:

main() ENTRY
Init
        1-1
        2-1
        3-1
        4-1
        5-1
        6-1
after old style erase of 3 & 4..
        1-1
        2-1
        5-1
        6-1
after new style erase of 5
        1-1
        2-1
        6-1

Process returned 0 (0x0)   execution time : 0.021 s
Press any key to continue.

Get the current date in java.sql.Date format

These are all too long.

Just use:

new Date(System.currentTimeMillis())

How to find path of active app.config file?

Depending on the location of your config file System.Reflection.Assembly.GetExecutingAssembly().Location might do what you need.

Minimum Hardware requirements for Android development

Its of no use even if you increase your RAM size because I tried it too. I am using P4 3.00GHz processor and 3 GB RAM(changed from 1 GB to 3GB), But even the Hello world application never turned up.

Its preferable to upgrade your system.

"No such file or directory" error when executing a binary

It is possible that the executable is statically linked and that is why ldd gzip does not see any links - because it isn't. I don't know much about things that far back so I don't know if there would be incompatibilities if libraries are linked in statically. I might expect there to be.

I know it's the most obvious thing going and I'm sure you've done it, but chmod +x ./gzip, yes? No such file or directory is a classic symptom of that not being done, that's why I mention it.

copy-item With Alternate Credentials

that evidently powershell's cmdlets such as copy-item, test-path, etc do not support alternate credentials...

It looks like they do here, copy-item certainly includes a -Credential parameter.

PS C:\> gcm -syn copy-item
Copy-Item [-Path] <String[]> [[-Destination] <String>] [-Container] [-Force] [-Filter <String>] [-I
nclude <String[]>] [-Exclude <String[]>] [-Recurse] [-PassThru] [-Credential <PSCredential>] [...]

Batch file to map a drive when the folder name contains spaces

I'm not sure this will help you to much by I once needed a batch file to open a game, the .exe was in a folder with blanks (duh!) and I tried : START "C:\Fold 1\fold 2\game.exe" and START C:\Fold 1\fold 2\game.exe - None worked, then I tried

   START C:\"Fold 1"\"fold 2"\game.exe and it worked 

Hope it helps :)

How to delete files/subfolders in a specific directory at the command prompt in Windows

None of the answers as posted on 2018-06-01, with the exception of the single command line posted by foxidrive, really deletes all files and all folders/directories in %PathToFolder%. That's the reason for posting one more answer with a very simple single command line to delete all files and subfolders of a folder as well as a batch file with a more complex solution explaining why all other answers as posted on 2018-06-01 using DEL and FOR with RD failed to clean up a folder completely.


The simple single command line solution which of course can be also used in a batch file:

pushd "%PathToFolder%" 2>nul && ( rd /Q /S "%PathToFolder%" 2>nul & popd )

This command line contains three commands executed one after the other.

The first command PUSHD pushes current directory path on stack and next makes %PathToFolder% the current directory for running command process.

This works also for UNC paths by default because of command extensions are enabled by default and in this case PUSHD creates a temporary drive letter that points to that specified network resource and then changes the current drive and directory, using the newly defined drive letter.

PUSHD outputs following error message to handle STDERR if the specified directory does not exist at all:

The system cannot find the path specified.

This error message is suppressed by redirecting it with 2>nul to device NUL.

The next command RD is executed only if changing current directory for current command process to specified directory was successful, i.e. the specified directory exists at all.

The command RD with the options /Q and /S removes a directory quietly with all subdirectories even if the specified directory contains files or folders with hidden attribute or with read-only attribute set. The system attribute does never prevent deletion of a file or folder.

Not deleted are:

  1. Folders used as the current directory for any running process. The entire folder tree to such a folder cannot be deleted if a folder is used as the current directory for any running process.

  2. Files currently opened by any running process with file access permissions set on file open to prevent deletion of the file while opened by the running application/process. Such an opened file prevents also the deletion of entire folder tree to the opened file.

  3. Files/folders on which the current user has not the required (NTFS) permissions to delete the file/folder which prevents also the deletion of the folder tree to this file/folder.

The first reason for not deleting a folder is used by this command line to delete all files and subfolders of the specified folder, but not the folder itself. The folder is made temporarily the current directory for running command process which prevents the deletion of the folder itself. Of course this results in output of an error message by command RD:

The process cannot access the file because it is being used by another process.

File is the wrong term here as in reality the folder is being used by another process, the current command process which executed command RD. Well, in reality a folder is for the file system a special file with file attribute directory which explains this error message. But I don't want to go too deep into file system management.

This error message, like all other error messages, which could occur because of the three reasons written above, is suppressed by redirecting it with 2>nul from handle STDERR to device NUL.

The third command, POPD, is executed independently of the exit value of command RD.

POPD pops the directory path pushed by PUSHD from the stack and changes the current directory for running the command process to this directory, i.e. restores the initial current directory. POPD deletes the temporary drive letter created by PUSHD in case of a UNC folder path.

Note: POPD can silently fail to restore the initial current directory in case of the initial current directory was a subdirectory of the directory to clean which does not exist anymore. In this special case %PathToFolder% remains the current directory. So it is advisable to run the command line above not from a subdirectory of %PathToFolder%.

One more interesting fact: I tried the command line also using a UNC path by sharing local directory C:\Temp with share name Temp and using UNC path \\%COMPUTERNAME%\Temp\CleanTest assigned to environment variable PathToFolder on Windows 7. If the current directory on running the command line is a subdirectory of a shared local folder accessed using UNC path, i.e. C:\Temp\CleanTest\Subfolder1, Subfolder1 is deleted by RD, and next POPD fails silently in making C:\Temp\CleanTest\Subfolder1 again the current directory resulting in Z:\CleanTest remaining as the current directory for the running command process. So in this very, very special case the temporary drive letter remains until the current directory is changed for example with cd /D %SystemRoot% to a local directory really existing. Unfortunately POPD does not exit with a value greater 0 if it fails to restore the initial current directory making it impossible to detect this very special error condition using just the exit code of POPD. However, it can be supposed that nobody ever runs into this very special error case as UNC paths are usually not used for accessing local files and folders.

For understanding the used commands even better, open a command prompt window, execute there the following commands, and read the help displayed for each command very carefully.

  • pushd /?
  • popd /?
  • rd /?

Single line with multiple commands using Windows batch file explains the operators && and & used here.


Next let us look on the batch file solution using the command DEL to delete files in %PathToFolder% and FOR and RD to delete the subfolders in %PathToFolder%.

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Clean the folder for temporary files if environment variable
rem PathToFolder is not defined already outside this batch file.
if not defined PathToFolder set "PathToFolder=%TEMP%"

rem Remove all double quotes from folder path.
set "PathToFolder=%PathToFolder:"=%"

rem Did the folder path consist only of double quotes?
if not defined PathToFolder goto EndCleanFolder

rem Remove a backslash at end of folder path.
if "%PathToFolder:~-1%" == "\" set "PathToFolder=%PathToFolder:~0,-1%"

rem Did the folder path consist only of a backslash (with one or more double quotes)?
if not defined PathToFolder goto EndCleanFolder

rem Delete all files in specified folder including files with hidden
rem or read-only attribute set, except the files currently opened by
rem a running process which prevents deletion of the file while being
rem opened by the application, or on which the current user has not
rem the required permissions to delete the file.
del /A /F /Q "%PathToFolder%\*" >nul 2>nul

rem Delete all subfolders in specified folder including those with hidden
rem attribute set recursive with all files and subfolders, except folders
rem being the current directory of any running process which prevents the
rem deletion of the folder and all folders above, folders containing a file
rem opened by the application which prevents deletion of the file and the
rem entire folder structure to this file, or on which the current user has
rem not the required permissions to delete a folder or file in folder tree
rem to delete.
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul

:EndCleanFolder
endlocal

The batch file first makes sure that environment variable PathToFolder is really defined with a folder path without double quotes and without a backslash at the end. The backslash at the end would not be a problem, but double quotes in a folder path could be problematic because of the value of PathToFolder is concatenated with other strings during batch file execution.

Important are the two lines:

del /A /F /Q "%PathToFolder%\*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul

The command DEL is used to delete all files in the specified directory.

  • The option /A is necessary to process really all files including files with the hidden attribute which DEL would ignore without using option /A.
  • The option /F is necessary to force deletion of files with the read-only attribute set.
  • The option /Q is necessary to run a quiet deletion of multiple files without prompting the user if multiple files should be really deleted.
  • >nul is necessary to redirect the output of the file names written to handle STDOUT to device NUL of which can't be deleted because of a file is currently opened or user has no permission to delete the file.
  • 2>nul is necessary to redirect the error message output for each file which can't be deleted from handle STDERR to device NUL.

The commands FOR and RD are used to remove all subdirectories in specified directory. But for /D is not used because of FOR is ignoring in this case subdirectories with the hidden attribute set. For that reason for /F is used to run the following command line in a separate command process started in the background with %ComSpec% /c:

dir "%PathToFolder%\*" /AD /B 2>nul

DIR outputs in bare format because of /B the directory entries with attribute D, i.e. the names of all subdirectories in specified directory independent on other attributes like the hidden attribute without a path. 2>nul is used to redirect the error message output by DIR on no directory found from handle STDERR to device NUL.

The redirection operator > must be escaped with the caret character, ^, on the FOR command line to be interpreted as a literal character when the Windows command interpreter processes this command line before executing the command FOR which executes the embedded dir command line in a separate command process started in the background.

FOR processes the captured output written to handle STDOUT of a started command process which are the names of the subdirectories without path and never enclosed in double quotes.

FOR with option /F ignores empty lines which don't occur here as DIR with option /B does not output empty lines.

FOR would also ignore lines starting with a semicolon which is the default end of line character. A directory name can start with a semicolon. For that reason eol=| is used to define the vertical bar character as the end-of-line character which no directory or file can have in its name.

FOR would split up the line into substrings using space and horizontal tab as delimiters and would assign only the first space/tab delimited string to specified loop variable I. This splitting behavior is not wanted here because of a directory name can contain one or more spaces. Therefore delims= is used to define an empty list of delimiters to disable the line splitting behavior and get assigned to the loop variable, I, always the complete directory name.

Command FOR runs the command RD for each directory name without a path which is the reason why on the RD command line the folder path must be specified once again which is concatenated with the subfolder name.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • del /?
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rd /?
  • rem /?
  • set /?
  • setlocal /?

Ruby String to Date Conversion

Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")

Should be:

Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')

How do I set up a private Git repository on GitHub? Is it even possible?

Update (2019, latest)

Since Jan 2019, GitHub allows private repositories for up to three collaborators.

Previous answer:

Here is the comparison for free plans listed by tree main Git Cloud based solutions:

Enter image description here

Here is the comparison for paid plans listed by tree main Git Cloud based solutions:

Enter image description here

Conclusion:

I'm not seeing people mentioning GitLab here, but it seems like the best free private plan for me. I myself am using it with no problems.

GitHub: If you have a student account or want to pay for $7 monthly, GitHub has the biggest community and you can take advantage of it's public repositories, forks, etc.

Bitbucket: If you use other products from Atlassian like Jira or Confluence, Bitbucket works great with them.

GitLab: Everything that I care about (free private repository, number of private repositories, number of collaborators, etc.) are offered for free. This seems like the best choice for me.

basic authorization command for curl

How do I set up the basic authorization?

All you need to do is use -u, --user USER[:PASSWORD]. Behind the scenes curl builds the Authorization header with base64 encoded credentials for you.

Example:

curl -u username:password -i -H 'Accept:application/json' http://example.com

How to get max value of a column using Entity Framework?

Selected answer throws exceptions, and the answer from Carlos Toledo applies filtering after retrieving all values from the database.

The following one runs a single round-trip and reads a single value, using any possible indexes, without an exception.

int maxAge = _dbContext.Persons
  .OrderByDescending(p => p.Age)
  .Select(p => p.Age)
  .FirstOrDefault();

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

Convert Base64 string to an image file?

$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";

This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma

Inputting a default image in case the src attribute of an html <img> is not valid?

If you have created dynamic Web project and have placed the required image in WebContent then you can access the image by using below mentioned code in Spring MVC:

<img src="Refresh.png" alt="Refresh" height="50" width="50">

You can also create folder named img and place the image inside the folder img and place that img folder inside WebContent then you can access the image by using below mentioned code:

<img src="img/Refresh.png" alt="Refresh" height="50" width="50">

What Process is using all of my disk IO

atop also works well and installs easily even on older CentOS 5.x systems which can't run iotop. Hit d to show disk details, ? for help.

ATOP - mybox                           2014/09/08  15:26:00                           ------                            10s elapsed
PRC |  sys    0.33s |  user   1.08s |                | #proc    161  |  #zombie    0 |  clones    31 |                | #exit         16  |
CPU |  sys   4% |  user     11% |  irq       0%  | idle    306%  |  wait     79% |               |  steal     1%  | guest     0%  |
cpu |  sys   2% |  user      8% |  irq       0%  | idle     11%  |  cpu000 w 78% |               |  steal     0%  | guest     0%  |
cpu |  sys   1% |  user      1% |  irq       0%  | idle     98%  |  cpu001 w  0% |               |  steal     0%  | guest     0%  |
cpu |  sys   1% |  user      1% |  irq       0%  | idle     99%  |  cpu003 w  0% |               |  steal     0%  | guest     0%  |
cpu |  sys   0% |  user      1% |  irq       0%  | idle     99%  |  cpu002 w  0% |               |  steal     0%  | guest     0%  |
CPL |  avg1    2.09 |  avg5    2.09 |  avg15   2.09  |               |  csw    54184 |  intr   33581 |                | numcpu     4  |
MEM |  tot     8.0G |  free   81.9M |  cache   2.9G  | dirty   0.8M  |  buff  174.7M |  slab  305.0M |                |               |
SWP |  tot     2.0G |  free    2.0G |                |               |               |               |  vmcom   8.4G  | vmlim   6.0G  |
LVM |  Group00-root |  busy     85% |  read       0  | write  30658  |  KiB/w      4 |  MBr/s   0.00 |  MBw/s  11.98  | avio 0.28 ms  |
DSK |          xvdb |  busy     85% |  read       0  | write  23706  |  KiB/w      5 |  MBr/s   0.00 |  MBw/s  11.97  | avio 0.36 ms  |
NET |  transport    |  tcpi    2705 |  tcpo    2008  | udpi      36  |  udpo      43 |  tcpao     14 |  tcppo     45  | tcprs      1  |
NET |  network      |  ipi     2788 |  ipo     2072  | ipfrw      0  |  deliv   2768 |               |  icmpi      7  | icmpo     20  |
NET |  eth0    ---- |  pcki    2344 |  pcko    1623  | si 1455 Kbps  |  so  781 Kbps |  erri       0 |  erro       0  | drpo       0  |
NET |  lo      ---- |  pcki     423 |  pcko     423  | si   88 Kbps  |  so   88 Kbps |  erri           0 |  erro       0  | drpo       0  |
NET |  eth1    ---- |  pcki  22 |  pcko      26  | si    3 Kbps  |  so    5 Kbps |  erri       0 |  erro       0  | drpo       0  |

  PID                   RDDSK                    WRDSK                   WCANCL                    DSK                   CMD        1/1
 9862                      0K                   53124K                       0K                    98%                   java
  358                      0K                     636K                       0K                     1%                   jbd2/dm-0-8
13893                      0K                     192K                      72K                     0%                   java
 1699                      0K                      60K                       0K                     0%                   syslogd
 4668                      0K                      24K                       0K                     0%                   zabbix_agentd

This clearly shows java pid 9862 is the culprit.

Visually managing MongoDB documents and collections

Here are some popular MongoDB GUI administration tools:

Open source

  • dbKoda - cross-platform, tabbed editor with auto-complete, syntax highlighting and code formatting (plus auto-save, something Studio 3T doesn't support), visual tools (explain plan, real-time performance dashboard, query and aggregation pipeline builder), profiling manager, storage analyzer, index advisor, convert MongoDB commands to Node.js syntax etc. Lacks in-place document editing and the ability to switch themes.

    dbKoda screenshot

  • Nosqlclient - multiple shell output tabs, autocomplete, schema analyzer, index management, user/role management, live monitoring, and other features. Electron/Meteor.js-based, actively developed on GitHub.

  • adminMongo - web-based or Electron app. Supports server monitoring and document editing.

Closed source

  • NoSQLBoosterfull-featured shell-centric cross-platform GUI tool for MongoDB v2.2-4. Free, Personal, and Commercial editions (feature comparison matrix).
  • MongoDB Compass – provides a graphical user interface that allows you to visualize your schema and perform ad-hoc find queries against the database – all with zero knowledge of MongoDB's query language. Developed by MongoDB, Inc. No update queries or access to the shell.
  • Studio 3T, formerly MongoChef – a multi-platform in-place data browser and editor desktop GUI for MongoDB (Core version is free for personal and non-commercial use). Last commit: 2017-Jul-24
  • Robo 3T – acquired by Studio 3T. A shell-centric cross-platform open source MongoDB management tool. Shell-related features only, e.g. multiple shells and results, autocomplete. No export/ import or other features are mentioned. Last commit: 2017-Jul-04

  • HumongouS.io – web-based interface with CRUD features, a chart builder and some collaboration capabilities. 14-day trial.

  • Database Master – a Windows based MongoDB Management Studio, supports also RDBMS. (not free)
  • SlamData - an open source web-based user-interface that allows you to upload and download data, run queries, build charts, explore data.

Abandoned projects

  • RockMongo – a MongoDB administration tool, written in PHP5. Allegedly the best in the PHP world. Similar to PHPMyAdmin. Last version: 2015-Sept-19
  • Fang of Mongo – a web-based UI built with Django and jQuery. Last commit: 2012-Jan-26, in a forked project.
  • Opricot – a browser-based MongoDB shell written in PHP. Latest version: 2010-Sep-21
  • Futon4Mongo – a clone of the CouchDB Futon web interface for MongoDB. Last commit: 2010-Oct-09
  • MongoVUE – an elegant GUI desktop application for Windows. Free and non-free versions. Latest version: 2014-Jan-20
  • UMongo – a full-featured open-source MongoDB server administration tool for Linux, Windows, Mac; written in Java. Last commit 2014-June
  • Mongo3 – a Ruby/Sinatra-based interface for cluster management. Last commit: Apr 16, 2013

return results from a function (javascript, nodejs)

function routeToRoom(userId, passw, cb) {
    var roomId = 0;
    var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
    var users = nStore.new('data/users.db', function() {
        users.find({
            user: userId,
            pass: passw
        }, function(err, results) {
            if (err) {
                roomId = -1;
            } else {
                roomId = results.creationix.room;
            }
            cb(roomId);
        });
    });
}
routeToRoom("alex", "123", function(id) {
    console.log(id);    
});

You need to use callbacks. That's how asynchronous IO works. Btw sys.puts is deprecated

How do I test if a variable does not equal either of two values?

This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).

switch(test) {
    case A:
    case B:
        do other stuff;
        break;
    default:
        do stuff;
}

Where does Jenkins store configuration files for the jobs it runs?

Jenkins 1.627, OS X 10.10.5 /Users/Shared/Jenkins/Home/jobs/{project_name}/config.xml

H2 in-memory database. Table not found

I came to this post because I had the same error.

In my case the database evolutions weren't been executed, so the table wasn't there at all.

My problem was that the folder structure for the evolution scripts was wrong.

from: https://www.playframework.com/documentation/2.0/Evolutions

Play tracks your database evolutions using several evolutions script. These scripts are written in plain old SQL and should be located in the conf/evolutions/{database name} directory of your application. If the evolutions apply to your default database, this path is conf/evolutions/default.

I had a folder called conf/evolutions.default created by eclipse. The issue disappeared after I corrected the folder structure to conf/evolutions/default

Max size of an iOS application

150MB is the constraint for over-the-air downloads via the cellular network. Anything above that and users will be suggested Wi-Fi or iTunes sync to actually get your app.

This will not prevent a purchase though, at point of sale.

hide/show a image in jquery

Use the .css() jQuery manipulators, or better yet just call .show()/.hide() on the image once you've obtained a handle to it (e.g. $('#img' + id)).

BTW, you should not write javascript handlers with the "javascript:" prefix.

How to easily consume a web service from PHP

In PHP 5 you can use SoapClient on the WSDL to call the web service functions. For example:

$client = new SoapClient("some.wsdl");

and $client is now an object which has class methods as defined in some.wsdl. So if there was a method called getTime in the WSDL then you would just call:

$result = $client->getTime();

And the result of that would (obviously) be in the $result variable. You can use the __getFunctions method to return a list of all the available methods.

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Shouldn't you have:

DELETE FROM tableA WHERE entitynum IN (...your select...)

Now you just have a WHERE with no comparison:

DELETE FROM tableA WHERE (...your select...)

So your final query would look like this;

DELETE FROM tableA WHERE entitynum IN (
    SELECT tableA.entitynum FROM tableA q
      INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
    WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
      AND (u.FldFormat = 'Date')
)

How to remove the underline for anchors(links)?

Use css property,

text-decoration:none;

To remove underline from the link.

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

In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict()
Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

Speed comparion (using Wouter's method)

In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB'))

In [7]: %timeit dict(zip(df.A,df.B))
1000 loops, best of 3: 1.27 ms per loop

In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict()
1000 loops, best of 3: 987 us per loop

How do you add an action to a button programmatically in xcode

CGRect buttonFrame = CGRectMake( 10, 80, 100, 30 );
        UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
        [button setTitle: @"My Button" forState: UIControlStateNormal];
        [button addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor: [UIColor redColor] forState: UIControlStateNormal];
[view addSubview:button];

Styling multi-line conditions in 'if' statements?

I usually use:

if ((cond1 == 'val1' and cond2 == 'val2' and
     cond3 == 'val3' and cond4 == 'val4')):
    do_something()

How can I get enum possible values in a MySQL database?

A more up to date way of doing it, this worked for me:

function enum_to_array($table, $field) {    
    $query = "SHOW FIELDS FROM `{$table}` LIKE '{$field}'";
    $result = $db->query($sql);
    $row = $result->fetchRow();
    preg_match('#^enum\((.*?)\)$#ism', $row['Type'], $matches);
    $enum = str_getcsv($matches[1], ",", "'");
    return $enum;
}

Ultimately, the enum values when separated from "enum()" is just a CSV string, so parse it as such!

Get full query string in C# ASP.NET

just a moment ago, i came across with the same issue. and i resolve it in the following manner.

Response.Redirect("../index.aspx?Name="+this.textName.Text+"&LastName="+this.textlName.Text);

with reference to the this

How to prevent ENTER keypress to submit a web form?

Simply add this attribute to your FORM tag:

onsubmit="return gbCanSubmit;"

Then, in your SCRIPT tag, add this:

var gbCanSubmit = false;

Then, when you make a button or for any other reason (like in a function) you finally permit a submit, simply flip the global boolean and do a .submit() call, similar to this example:

function submitClick(){

  // error handler code goes here and return false if bad data

  // okay, proceed...
  gbCanSubmit = true;
  $('#myform').submit(); // jQuery example

}

'foo' was not declared in this scope c++

In C++, your source files are usually parsed from top to bottom in a single pass, so any variable or function must be declared before they can be used. There are some exceptions to this, like when defining functions inline in a class definition, but that's not the case for your code.

Either move the definition of integrate above the one for getSkewNormal, or add a forward declaration above getSkewNormal:

double integrate (double start, double stop, int numSteps, Evaluatable evalObj);

The same applies for sum.

u'\ufeff' in Python string

That character is the BOM or "Byte Order Mark". It is usually received as the first few bytes of a file, telling you how to interpret the encoding of the rest of the data. You can simply remove the character to continue. Although, since the error says you were trying to convert to 'ascii', you should probably pick another encoding for whatever you were trying to do.

How to detect a textbox's content has changed

I'd like to ask why you are trying to detect when the content of the textbox changed in real time?

An alternative would be to set a timer (via setIntval?) and compare last saved value to the current one and then reset a timer. This would guarantee catching ANY change, whether caused by keys, mouse, some other input device you didn't consider, or even JavaScript changing the value (another possiblity nobody mentioned) from a different part of the app.

What is the format specifier for unsigned short int?

For scanf, you need to use %hu since you're passing a pointer to an unsigned short. For printf, it's impossible to pass an unsigned short due to default promotions (it will be promoted to int or unsigned int depending on whether int has at least as many value bits as unsigned short or not) so %d or %u is fine. You're free to use %hu if you prefer, though.

OTP (token) should be automatically read from the message

I will recommend you not to use any third party libraries for auto fetch OTP from SMS Inbox. This can be done easily if you have basic understanding of Broadcast Receiver and how it works. Just Try following approach :

Step 1) Create single interface i.e SmsListner

package com.wnrcorp.reba;
public interface SmsListener{
public void messageReceived(String messageText);}

Step 2) Create single Broadcast Receiver i.e SmsReceiver

package com.wnrcorp.reba;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
Boolean b;
String abcd,xyz;
@Override
public void onReceive(Context context, Intent intent) {
Bundle data  = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
    for(int i=0;i<pdus.length;i++){
        SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String sender = smsMessage.getDisplayOriginatingAddress();
       // b=sender.endsWith("WNRCRP");  //Just to fetch otp sent from WNRCRP
        String messageBody = smsMessage.getMessageBody();
       abcd=messageBody.replaceAll("[^0-9]","");   // here abcd contains otp 
        which is in number format
        //Pass on the text to our listener.
        if(b==true) {
            mListener.messageReceived(abcd);  // attach value to interface 
  object
        }
        else
        {
        }
    }
}
public static void bindListener(SmsListener listener) {
    mListener = listener;
}
}

Step 3) Add Listener i.e broadcast receiver in android manifest file

<receiver android:name=".SmsReceiver">    
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
</receiver>

and add permission

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

Final Step 4) The activity where you going to auto fetch otp when it is received in inbox. In my case I'm fetching otp and setting on edittext field.

public class OtpVerificationActivity extends AppCompatActivity {
EditText ed;
TextView tv;
String otp_generated,contactNo,id1;
GlobalData gd = new GlobalData();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_otp_verification);
    ed=(EditText)findViewById(R.id.otp);
    tv=(TextView) findViewById(R.id.verify_otp); 
    /*This is important because this will be called every time you receive 
     any sms */            
 SmsReceiver.bindListener(new SmsListener() {
        @Override
        public void messageReceived(String messageText) {
            ed.setText(messageText);     
        }
    });
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try
            {
                InputMethodManager imm=
  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);                    
  imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
            }
            catch(Exception e)
            {}           
            if (ed.getText().toString().equals(otp_generated))
            {
                Toast.makeText(OtpVerificationActivity.this, "OTP Verified 
       Successfully !", Toast.LENGTH_SHORT).show();           
             }
    });
   }
}

Layout File for OtpVerificationActivity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_otp_verification"
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"
tools:context="com.wnrcorp.reba.OtpVerificationActivity">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/firstcard"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardCornerRadius="10dp"
    >
   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@android:color/white">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OTP Confirmation"
            android:textSize="18sp"
            android:textStyle="bold"
            android:id="@+id/dialogTitle"
            android:layout_margin="5dp"
            android:layout_gravity="center"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/otp"
            android:layout_margin="5dp"
            android:hint="OTP Here"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Verify"
            android:textSize="18sp"
            android:id="@+id/verify_otp"
            android:gravity="center"
            android:padding="10dp"
            android:layout_gravity="center"
            android:visibility="visible"
            android:layout_margin="5dp"
            android:background="@color/colorPrimary"
            android:textColor="#ffffff"
            />
        </LinearLayout>
        </android.support.v7.widget.CardView>
        </RelativeLayout>

Screenshots for OTP Verification Activity where you fetch OTP as soons as messages received enter image description here

trigger body click with jQuery

You should have something like this:

$('body').click(function() {
   // do something here
});

The callback function will be called when the user clicks somewhere on the web page. You can trigger the callback programmatically with:

$('body').trigger('click');

Get distance between two points in canvas

http://en.wikipedia.org/wiki/Euclidean_distance

If you have the coordinates, use the formula to calculate the distance:

var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );

If your platform supports the ** operator, you can instead use that:

const dist = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);

jQuery checkbox onChange

$('input[type=checkbox]').change(function () {
    alert('changed');
});

How to use multiprocessing queue in Python?

My main problem is that I really don't know how to implement multiprocessing.queue correctly, you cannot really instantiate the object for each process since they will be separate queues, how do you make sure that all processes relate to a shared queue (or in this case, queues)

This is a simple example of a reader and writer sharing a single queue... The writer sends a bunch of integers to the reader; when the writer runs out of numbers, it sends 'DONE', which lets the reader know to break out of the read loop.

from multiprocessing import Process, Queue
import time
import sys

def reader_proc(queue):
    ## Read from the queue; this will be spawned as a separate Process
    while True:
        msg = queue.get()         # Read from the queue and do nothing
        if (msg == 'DONE'):
            break

def writer(count, queue):
    ## Write to the queue
    for ii in range(0, count):
        queue.put(ii)             # Write 'count' numbers into the queue
    queue.put('DONE')

if __name__=='__main__':
    pqueue = Queue() # writer() writes to pqueue from _this_ process
    for count in [10**4, 10**5, 10**6]:             
        ### reader_proc() reads from pqueue as a separate process
        reader_p = Process(target=reader_proc, args=((pqueue),))
        reader_p.daemon = True
        reader_p.start()        # Launch reader_proc() as a separate python process

        _start = time.time()
        writer(count, pqueue)    # Send a lot of stuff to reader()
        reader_p.join()         # Wait for the reader to finish
        print("Sending {0} numbers to Queue() took {1} seconds".format(count, 
            (time.time() - _start)))

How to insert values into the database table using VBA in MS access

since you mentioned you are quite new to access, i had to invite you to first remove the errors in the code (the incomplete for loop and the SQL statement). Otherwise, you surely need the for loop to insert dates in a certain range.

Now, please use the code below to insert the date values into your table. I have tested the code and it works. You can try it too. After that, add your for loop to suit your scenario

Dim StrSQL As String
Dim InDate As Date
Dim DatDiff As Integer

InDate = Me.FromDateTxt

StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"

DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True

How to concatenate text from multiple rows into a single text string in SQL server?

In SQL Server 2005 and later, use the query below to concatenate the rows.

DECLARE @t table
(
    Id int,
    Name varchar(10)
)
INSERT INTO @t
SELECT 1,'a' UNION ALL
SELECT 1,'b' UNION ALL
SELECT 2,'c' UNION ALL
SELECT 2,'d' 

SELECT ID,
stuff(
(
    SELECT ','+ [Name] FROM @t WHERE Id = t.Id FOR XML PATH('')
),1,1,'') 
FROM (SELECT DISTINCT ID FROM @t ) t

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

Slightly different option usually works for me:

  1. "mvn eclipse:eclipse" for this project in the command line.
  2. "Refresh/F5" this project in eclipse.

That's all, no need to re-import but need to have the terminal window handy.

Two-dimensional array in Swift

You should be careful when you're using Array(repeating: Array(repeating: {value}, count: 80), count: 24).

If the value is an object, which is initialized by MyClass(), then they will use the same reference.

Array(repeating: Array(repeating: MyClass(), count: 80), count: 24) doesn't create a new instance of MyClass in each array element. This method only creates MyClass once and puts it into the array.

Here's a safe way to initialize a multidimensional array.

private var matrix: [[MyClass]] = MyClass.newMatrix()

private static func newMatrix() -> [[MyClass]] {
    var matrix: [[MyClass]] = []

    for i in 0...23 {
        matrix.append( [] )

        for _ in 0...79 {
            matrix[i].append( MyClass() )
        }
    }

    return matrix
}

Project with path ':mypath' could not be found in root project 'myproject'

Remove all the texts in android/settings.gradle and paste the below code

rootProject.name = '****Your Project Name****'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

This issue will usually happen when you migrate from react-native < 0.60 to react-native >0.60. If you create a new project in react-native >0.60 you will see the same settings as above mentioned

rsync copy over only certain types of files using include option

Wrote this handy function and put in my bash scripts or ~/.bash_aliases. Tested sync'ing locally on Linux with bash and awk installed. It works

selrsync(){
# selective rsync to sync only certain filetypes;
# based on: https://stackoverflow.com/a/11111793/588867
# Example: selrsync 'tsv,csv' ./source ./target --dry-run
types="$1"; shift; #accepts comma separated list of types. Must be the first argument.
includes=$(echo $types| awk  -F',' \
    'BEGIN{OFS=" ";}
    {
    for (i = 1; i <= NF; i++ ) { if (length($i) > 0) $i="--include=*."$i; } print
    }')
restargs="$@"

echo Command: rsync -avz --prune-empty-dirs --include="*/" $includes --exclude="*" "$restargs"
eval rsync -avz --prune-empty-dirs --include="*/" "$includes" --exclude="*" $restargs
}

Avantages:

short handy and extensible when one wants to add more arguments (i.e. --dry-run).

Example:

selrsync 'tsv,csv' ./source ./target --dry-run

How can I get customer details from an order in WooCommerce?

Get the customer id from the order object:

$order = new WC_Order($order_id);

// Here the customer data
$customer = get_userdata($order->customer_user);
echo $customer->display_name;

How to execute an Oracle stored procedure via a database link

for me, this worked

exec utl_mail.send@myotherdb(
  sender => '[email protected]',recipients => '[email protected], 
  cc => null, subject => 'my subject', message => 'my message'
); 

SecurityError: The operation is insecure - window.history.pushState()

You should try not open the file with a folder-explorer method (i.e. file://), but open that file from http:// (i.e. http://yoursite.com/ from http://localhost/)

Argument Exception "Item with Same Key has already been added"

Clear the dictionary before adding any items to it. I don't know how a dictionary of one object affects another's during assignment but I got the error after creating another object with the same key,value pairs.

NB: If you are going to add items in a loop just make sure you clear the dictionary before entering the loop.

Hyphen, underscore, or camelCase as word delimiter in URIs?

here's the best of both worlds.

I also "like" underscores, besides all your positive points about them, there is also a certain old-school style to them.

So what I do is use underscores and simply add a small rewrite rule to your Apache's .htaccess file to re-write all underscores to hyphens.

https://yoast.com/apache-rewrite-dash-underscore/

How to customize the back button on ActionBar

Changing back navigation icon differs for ActionBar and Toolbar.

For ActionBar override homeAsUpIndicator attribute:

<style name="CustomThemeActionBar" parent="android:Theme.Holo">
    <item name="homeAsUpIndicator">@drawable/ic_nav_back</item>
</style>

For Toolbar override navigationIcon attribute:

<style name="CustomThemeToolbar" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="navigationIcon">@drawable/ic_nav_back</item>
</style>

An Authentication object was not found in the SecurityContext - Spring 3.2.2

As pointed already by @Arun P Johny the root cause of the problem is that at the moment when AuthenticationSuccessEvent is processed SecurityContextHolder is not populated by Authentication object. So any declarative authorization checks (that must get user rights from SecurityContextHolder) will not work. I give you another idea how to solve this problem. There are two ways how you can run your custom code immidiately after successful authentication:

  1. Listen to AuthenticationSuccessEvent
  2. Provide your custom AuthenticationSuccessHandler implementation.

AuthenticationSuccessHandler has one important advantage over first way: SecurityContextHolder will be already populated. So just move your stateService.rowCount() call into loginsuccesshandler.LoginSuccessHandler#onAuthenticationSuccess(...) method and the problem will go away.

How to use new PasswordEncoder from Spring Security

Here is the implementation of BCrypt which is working for me.

in spring-security.xml

<authentication-manager >
    <authentication-provider ref="authProvider"></authentication-provider>  
    </authentication-manager>
<beans:bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
  <beans:property name="userDetailsService" ref="userDetailsServiceImpl" />
  <beans:property name="passwordEncoder" ref="encoder" />
</beans:bean>
<!-- For hashing and salting user passwords -->
    <beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

In java class

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(yourpassword);

For more detailed example of spring security Click Here

Hope this will help.

Thanks

INSERT VALUES WHERE NOT EXISTS

This isn't an answer. I just want to show that IF NOT EXISTS(...) INSERT method isn't safe. You have to execute first Session #1 and then Session #2. After v #2 you will see that without an UNIQUE index you could get duplicate pairs (SoftwareName,SoftwareSystemType). Delay from session #1 is used to give you enough time to execute the second script (session #2). You could reduce this delay.

Session #1 (SSMS > New Query > F5 (Execute))

CREATE DATABASE DemoEXISTS;
GO
USE DemoEXISTS;
GO
CREATE TABLE dbo.Software(
    SoftwareID INT PRIMARY KEY,
    SoftwareName NCHAR(400) NOT NULL,  
    SoftwareSystemType NVARCHAR(50) NOT NULL
);
GO

INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
VALUES (1,'Dynamics AX 2009','ERP');
INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
VALUES (2,'Dynamics NAV 2009','SCM');
INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
VALUES (3,'Dynamics CRM 2011','CRM');
INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
VALUES (4,'Dynamics CRM 2013','CRM');
INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
VALUES (5,'Dynamics CRM 2015','CRM');
GO
/*
CREATE UNIQUE INDEX IUN_Software_SoftwareName_SoftareSystemType
ON dbo.Software(SoftwareName,SoftwareSystemType);
GO
*/

-- Session #1
BEGIN TRANSACTION;
    UPDATE  dbo.Software
    SET     SoftwareName='Dynamics CRM',
            SoftwareSystemType='CRM'    
    WHERE   SoftwareID=5;

    WAITFOR DELAY '00:00:15' -- 15 seconds delay; you have less than 15 seconds to switch SSMS window to session #2

    UPDATE  dbo.Software
    SET     SoftwareName='Dynamics AX',
            SoftwareSystemType='ERP'
    WHERE   SoftwareID=1;
COMMIT
--ROLLBACK
PRINT 'Session #1 results:';
SELECT *
FROM dbo.Software;

Session #2 (SSMS > New Query > F5 (Execute))

USE DemoEXISTS;
GO
-- Session #2
DECLARE 
    @SoftwareName NVARCHAR(100),  
    @SoftwareSystemType NVARCHAR(50);
SELECT
    @SoftwareName=N'Dynamics AX',
    @SoftwareSystemType=N'ERP';

PRINT 'Session #2 results:';
IF NOT EXISTS(SELECT *
    FROM dbo.Software s
    WHERE s.SoftwareName=@SoftwareName 
    AND s.SoftwareSystemType=@SoftwareSystemType)
BEGIN
    PRINT 'Session #2: INSERT';

    INSERT INTO dbo.Software(SoftwareID,SoftwareName,SoftwareSystemType)
    VALUES (6,@SoftwareName,@SoftwareSystemType);
END 
PRINT 'Session #2: FINISH';
SELECT  * 
FROM    dbo.Software;

Results:

Session #1 results:
SoftwareID  SoftwareName      SoftwareSystemType
----------- ----------------- ------------------
1           Dynamics AX       ERP
2           Dynamics NAV 2009 SCM
3           Dynamics CRM 2011 CRM
4           Dynamics CRM 2013 CRM
5           Dynamics CRM      CRM

Session #2 results:
Session #2: INSERT
Session #2: FINISH
SoftwareID  SoftwareName      SoftwareSystemType
----------- ----------------- ------------------
1           Dynamics AX       ERP <-- duplicate (row updated by session #1)
2           Dynamics NAV 2009 SCM
3           Dynamics CRM 2011 CRM
4           Dynamics CRM 2013 CRM
5           Dynamics CRM      CRM
6           Dynamics AX       ERP <-- duplicate (row inserted by session #2)

How to kill MySQL connections

No, there is no built-in MySQL command for that. There are various tools and scripts that support it, you can kill some connections manually or restart the server (but that will be slower).

Use SHOW PROCESSLIST to view all connections, and KILL the process ID's you want to kill.

You could edit the timeout setting to have the MySQL daemon kill the inactive processes itself, or raise the connection count. You can even limit the amount of connections per username, so that if the process keeps misbehaving, the only affected process is the process itself and no other clients on your database get locked out.

If you can't connect yourself anymore to the server, you should know that MySQL always reserves 1 extra connection for a user with the SUPER privilege. Unless your offending process is for some reason using a username with that privilege...

Then after you can access your database again, you should fix the process (website) that's spawning that many connections.

How can I get (query string) parameters from the URL in Next.js?

If you need to retrieve a URL query from outside a component:

import router from 'next/router'

console.log(router.query)

Create a button programmatically and set a background image

To set background we can no longer use forState, so we have to use for to set the UIControlState:

let zoomInImage = UIImage(named: "Icon - plus") as UIImage?
let zoomInButton = UIButton(frame: CGRect(x: 10), y: 10, width: 45, height: 45))
zoomInButton.setBackgroundImage(zoomInImage, for: UIControlState.normal)
zoomInButton.addTarget(self, action: #selector(self.mapZoomInAction), for: .touchUpInside)
self.view.addSubview(zoomInButton)

Where is shared_ptr?

There are at least three places where you may find shared_ptr:

  1. If your C++ implementation supports C++11 (or at least the C++11 shared_ptr), then std::shared_ptr will be defined in <memory>.

  2. If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Microsoft Visual C++) or <tr1/memory> (g++'s libstdc++). Boost also provides a TR1 implementation that you can use.

  3. Otherwise, you can obtain the Boost libraries and use boost::shared_ptr, which can be found in <boost/shared_ptr.hpp>.

The simplest possible JavaScript countdown timer?

If you want a real timer you need to use the date object.

Calculate the difference.

Format your string.

window.onload=function(){
      var start=Date.now(),r=document.getElementById('r');
      (function f(){
      var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
      r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
      if(diff>3e5){
         start=Date.now()
      }
      setTimeout(f,1e3);
      })();
}

Example

Jsfiddle

not so precise timer

var time=5*60,r=document.getElementById('r'),tmp=time;

setInterval(function(){
    var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
    r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
    tmp!=0||(tmp=time);
},1000);

JsFiddle

How to use HTML Agility pack

I don't know if this will be of any help to you, but I have written a couple of articles which introduce the basics.

The next article is 95% complete, I just have to write up explanations of the last few parts of the code I have written. If you are interested then I will try to remember to post here when I publish it.

Import pandas dataframe column as string not int

Just want to reiterate this will work in pandas >= 0.9.1:

In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]: 
                           ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

I'm creating an issue about detecting integer overflows also.

EDIT: See resolution here: https://github.com/pydata/pandas/issues/2247

Update as it helps others:

To have all columns as str, one can do this (from the comment):

pd.read_csv('sample.csv', dtype = str)

To have most or selective columns as str, one can do this:

# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str'  for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)

Setting CSS pseudo-class rules from JavaScript

There is another alternative. Instead of manipulating the pseudo-classes directly, create real classes that model the same things, like a "hover" class or a "visited" class. Style the classes with the usual "." syntax and then you can use JavaScript to add or remove classes from an element when the appropriate event fires.

Overflow:hidden dots at the end

You can use text-overflow: ellipsis; which according to caniuse is supported by all the major browsers.

Here's a demo on jsbin.

_x000D_
_x000D_
.cut-text { 
  text-overflow: ellipsis;
  overflow: hidden; 
  width: 160px; 
  height: 1.2em; 
  white-space: nowrap;
}
_x000D_
<div class="cut-text">
I like big butts and I can not lie.
</div>
_x000D_
_x000D_
_x000D_

Group by with union mysql select query

select sum(qty), name
from (
    select count(m.owner_id) as qty, o.name
    from transport t,owner o,motorbike m
    where t.type='motobike' and o.owner_id=m.owner_id
        and t.type_id=m.motorbike_id
    group by m.owner_id

    union all

    select count(c.owner_id) as qty, o.name,
    from transport t,owner o,car c
    where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
    group by c.owner_id
) t
group by name

On linux SUSE or RedHat, how do I load Python 2.7

To install Python 2.7.2 use this script - https://github.com/bngsudheer/bangadmin/blob/master/linux/centos/6/x86_64/build-python-27.sh

It also makes sure you get sqlite and readline support.

jQuery ID starts with

try:

$("td[id^=" + value + "]")

What do I do when my program crashes with exception 0xc0000005 at address 0?

I was getting the same issue with a different application,

Faulting application name: javaw.exe, version: 8.0.51.16, time stamp: 0x55763d32
Faulting module name: mscorwks.dll, version: 2.0.50727.5485, time stamp: 0x53a11d6c
Exception code: 0xc0000005
Fault offset: 0x0000000000501090
Faulting process id: 0x2960
Faulting application start time: 0x01d0c39a93c695f2
Faulting application path: C:\Program Files\Java\jre1.8.0_51\bin\javaw.exe
Faulting module path:C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll

I was using the The Enhanced Mitigation Experience Toolkit (EMET) from Microsoft and I found by disabling the EMET features on javaw.exe in my case as this was the faulting application, it enabled my application to run successfully. Make sure you don't have any similar software with security protections on memory.

How to hide app title in android?

use

<activity android:name=".ActivityName" 
          android:theme="@android:style/Theme.NoTitleBar">

Convert object to JSON in Android

Might be better choice:

@Override
public String toString() {
    return new GsonBuilder().create().toJson(this, Producto.class);
}

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

I was facing the same issue. After many tries below solution worked for me.

Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.

After that you can follow the below steps.

@ABHI KUMAR

Download the Visual C++ Redistributable 2015

Visual C++ Redistributable for Visual Studio 2015 (64-bit)

Visual C++ Redistributable for Visual Studio 2015 (32-bit)

(Reinstal if already installed) then restart your computer or use windows updates for download auto.

For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.

How do you set a default value for a MySQL Datetime column?

this is indeed terrible news.here is a long pending bug/feature request for this. that discussion also talks about the limitations of timestamp data type.

I am seriously wondering what is the issue with getting this thing implemented.

"SyntaxError: Unexpected token < in JSON at position 0"

If anyone else is using fetch from the "Using Fetch" documentation on Web API's in Mozilla: (This is really useful: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

  fetch(api_url + '/database', {
    method: 'POST', // or 'PUT'
    headers: {
     'Content-Type': 'application/json'
    },
    body: qrdata //notice that it is not qr but qrdata
  })
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data);
  })  
  .catch((error) => {
  console.error('Error:', error);  });

This was inside the function:

async function postQRData(qr) {

  let qrdata = qr; //this was added to fix it!
  //then fetch was here
}

I was passing into my function qr what I believed to be an object because qr looked like this: {"name": "Jade", "lname": "Bet", "pet":"cat"} but I kept getting syntax errors. When I assigned it to something else: let qrdata = qr; it worked.

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

An alternative to adding LINQ would be to use this code instead:

List<Pax_Detail> paxList = new List<Pax_Detail>(pax);

Increase max execution time for php

Add these lines of code in your htaccess file. I hope it will solve your problem.

<IfModule mod_php5.c>
php_value max_execution_time 259200
</IfModule>

Single Result from Database by using mySQLi

If you assume just one result you could do this as in Edwin suggested by using specific users id.

$someUserId = 'abc123';

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);

$stmt->execute();

$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.

OR as "Your Common Sense" which selects just one user.

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");

$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

Nothing really different from the above except for PHP v.5

How can I use custom fonts on a website?

You can use CSS3 font-face or webfonts

@font-face usage

@font-face {
   font-family: Delicious; 
   src: url('Delicious-Roman.otf');
} 

webfonts

take a look at Google Webfonts, http://www.google.com/webfonts

How to remove origin from git repository

Fairly straightforward:

git remote rm origin

As for the filter-branch question - just add --prune-empty to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:

git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD

Convert integer to hex and hex to integer

To convert Hex strings to INT, I have used this in the past. It can be modified to convert any base to INT in fact (Octal, Binary, whatever)

Declare @Str varchar(200)
Set @str = 'F000BE1A'

Declare @ndx int
Set @ndx = Len(@str)
Declare @RunningTotal  BigInt
Set @RunningTotal = 0

While @ndx > 0
Begin
    Declare @Exponent BigInt
    Set @Exponent = Len(@Str) - @ndx

    Set @RunningTotal = @RunningTotal + 

    Power(16 * 1.0, @Exponent) *
    Case Substring(@str, @ndx, 1)
        When '0' then 0
        When '1' then 1
        When '2' then 2 
        When '3' then 3
        When '4' then 4
        When '5' then 5
        When '6' then 6
        When '7' then 7
        When '8' then 8
        When '9' then 9
        When 'A' then 10
        When 'B' then 11
        When 'C' then 12
        When 'D' then 13
        When 'E' then 14
        When 'F' then 15
    End
    Set @ndx = @ndx - 1
End

Print @RunningTotal

How do I create a simple 'Hello World' module in Magento?

First and foremost, I highly recommend you buy the PDF/E-Book from PHP Architect. It's US$20, but is the only straightforward "Here's how Magento works" resource I've been able to find. I've also started writing Magento tutorials at my own website.

Second, if you have a choice, and aren't an experienced programmer or don't have access to an experienced programmer (ideally in PHP and Java), pick another cart. Magento is well engineered, but it was engineered to be a shopping cart solution that other programmers can build modules on top of. It was not engineered to be easily understood by people who are smart, but aren't programmers.

Third, Magento MVC is very different from the Ruby on Rails, Django, CodeIgniter, CakePHP, etc. MVC model that's popular with PHP developers these days. I think it's based on the Zend model, and the whole thing is very Java OOP-like. There's two controllers you need to be concerned about. The module/frontName controller, and then the MVC controller.

Fourth, the Magento application itself is built using the same module system you'll be using, so poking around the core code is a useful learning tactic. Also, a lot of what you'll be doing with Magento is overriding existing classes. What I'm covering here is creating new functionality, not overriding. Keep this in mind when you're looking at the code samples out there.

I'm going to start with your first question, showing you how to setup a controller/router to respond to a specific URL. This will be a small novel. I might have time later for the model/template related topics, but for now, I don't. I will, however, briefly speak to your SQL question.

Magento uses an EAV database architecture. Whenever possible, try to use the model objects the system provides to get the information you need. I know it's all there in the SQL tables, but it's best not to think of grabbing data using raw SQL queries, or you'll go mad.

Final disclaimer. I've been using Magento for about two or three weeks, so caveat emptor. This is an exercise to get this straight in my head as much as it is to help Stack Overflow.

Create a module

All additions and customizations to Magento are done through modules. So, the first thing you'll need to do is create a new module. Create an XML file in app/modules named as follows

cd /path/to/store/app
touch etc/modules/MyCompanyName_HelloWorld.xml
<?xml version="1.0"?>
<config>
     <modules>
        <MyCompanyName_HelloWorld>
            <active>true</active>
            <codePool>local</codePool>
        </MyCompanyName_HelloWorld>
     </modules>
</config>

MyCompanyName is a unique namespace for your modifications, it doesn't have to be your company's name, but that the recommended convention my magento. HelloWorld is the name of your module.

Clear the application cache

Now that the module file is in place, we'll need to let Magento know about it (and check our work). In the admin application

  1. Go to System->Cache Management
  2. Select Refresh from the All Cache menu
  3. Click Save Cache settings

Now, we make sure that Magento knows about the module

  1. Go to System->Configuration
  2. Click Advanced
  3. In the "Disable modules output" setting box, look for your new module named "MyCompanyName_HelloWorld"

If you can live with the performance slow down, you might want to turn off the application cache while developing/learning. Nothing is more frustrating then forgetting the clear out the cache and wondering why your changes aren't showing up.

Setup the directory structure

Next, we'll need to setup a directory structure for the module. You won't need all these directories, but there's no harm in setting them all up now.

mkdir -p app/code/local/MyCompanyName/HelloWorld/Block
mkdir -p app/code/local/MyCompanyName/HelloWorld/controllers
mkdir -p app/code/local/MyCompanyName/HelloWorld/Model
mkdir -p app/code/local/MyCompanyName/HelloWorld/Helper
mkdir -p app/code/local/MyCompanyName/HelloWorld/etc
mkdir -p app/code/local/MyCompanyName/HelloWorld/sql

And add a configuration file

touch app/code/local/MyCompanyName/HelloWorld/etc/config.xml

and inside the configuration file, add the following, which is essentially a "blank" configuration.

<?xml version="1.0"?>
<config>
    <modules>
        <MyCompanyName_HelloWorld>
            <version>0.1.0</version>
        </MyCompanyName_HelloWorld>
    </modules>
</config>

Oversimplifying things, this configuration file will let you tell Magento what code you want to run.

Setting up the router

Next, we need to setup the module's routers. This will let the system know that we're handling any URLs in the form of

http://example.com/magento/index.php/helloworld

So, in your configuration file, add the following section.

<config>
<!-- ... -->
    <frontend>
        <routers>
            <!-- the <helloworld> tagname appears to be arbitrary, but by
            convention is should match the frontName tag below-->
            <helloworld>
                <use>standard</use>
                <args>
                    <module>MyCompanyName_HelloWorld</module>
                    <frontName>helloworld</frontName>
                </args>
            </helloworld>
        </routers>
    </frontend>
<!-- ... -->
</config>

What you're saying here is "any URL with the frontName of helloworld ...

http://example.com/magento/index.php/helloworld

should use the frontName controller MyCompanyName_HelloWorld".

So, with the above configuration in place, when you load the helloworld page above, you'll get a 404 page. That's because we haven't created a file for our controller. Let's do that now.

touch app/code/local/MyCompanyName/HelloWorld/controllers/IndexController.php

Now try loading the page. Progress! Instead of a 404, you'll get a PHP/Magento exception

Controller file was loaded but class does not exist

So, open the file we just created, and paste in the following code. The name of the class needs to be based on the name you provided in your router.

<?php
class MyCompanyName_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action{
    public function indexAction(){
        echo "We're echoing just to show that this is what's called, normally you'd have some kind of redirect going on here";
    }
}

What we've just setup is the module/frontName controller. This is the default controller and the default action of the module. If you want to add controllers or actions, you have to remember that the tree first part of a Magento URL are immutable they will always go this way http://example.com/magento/index.php/frontName/controllerName/actionName

So if you want to match this url

http://example.com/magento/index.php/helloworld/foo

You will have to have a FooController, which you can do this way :

touch app/code/local/MyCompanyName/HelloWorld/controllers/FooController.php
<?php
class MyCompanyName_HelloWorld_FooController extends Mage_Core_Controller_Front_Action{
    public function indexAction(){
        echo 'Foo Index Action';
    }

    public function addAction(){
        echo 'Foo add Action';
    }

    public function deleteAction(){
        echo 'Foo delete Action';
    }
}

Please note that the default controller IndexController and the default action indexAction can by implicit but have to be explicit if something come after it. So http://example.com/magento/index.php/helloworld/foo will match the controller FooController and the action indexAction and NOT the action fooAction of the IndexController. If you want to have a fooAction, in the controller IndexController you then have to call this controller explicitly like this way : http://example.com/magento/index.php/helloworld/index/foo because the second part of the url is and will always be the controllerName. This behaviour is an inheritance of the Zend Framework bundled in Magento.

You should now be able to hit the following URLs and see the results of your echo statements

http://example.com/magento/index.php/helloworld/foo
http://example.com/magento/index.php/helloworld/foo/add
http://example.com/magento/index.php/helloworld/foo/delete

So, that should give you a basic idea on how Magento dispatches to a controller. From here I'd recommended poking at the existing Magento controller classes to see how models and the template/layout system should be used.

Build a simple HTTP server in C

Use platform specific socket functions to encapsulate the HTTP protocol, just like guys behind Apache did.

how do I check in bash whether a file was created more than x time ago?

Only for modification time

if test `find "text.txt" -mmin +120`
then
    echo old enough
fi

You can use -cmin for change or -amin for access time. As others pointed I don’t think you can track creation time.

Chrome ignores autocomplete="off"

Modern Approach

Simply make your input readonly, and on focus, remove it. This is a very simple approach and browsers will not populate readonly inputs. Therefore, this method is accepted and will never be overwritten by future browser updates.

<input type="text" onfocus="this.removeAttribute('readonly');" readonly />

The next part is optional. Style your input accordingly so that it does not look like a readonly input.

input[readonly] {
     cursor: text;
     background-color: #fff;
}

WORKING EXAMPLE

CSS horizontal scroll

Use this code to generate horizontal scrolling blocks contents. I got this from here http://www.htmlexplorer.com/2014/02/horizontal-scrolling-webpage-content.html

<html>
<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<head>
<style type="text/css">
#outer_wrapper {  
    overflow: scroll;  
    width:100%;
}
#outer_wrapper #inner_wrapper {
    width:6000px; /* If you have more elements, increase the width accordingly */
}
#outer_wrapper #inner_wrapper div.box { /* Define the properties of inner block */
    width: 250px;
    height:300px;
    float: left;
    margin: 0 4px 0 0;
    border:1px grey solid;
}
</style>
</head>
<body>

<div id="outer_wrapper">
    <div id="inner_wrapper">
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
             <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
             <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <!-- more boxes here -->
    </div>
</div>
</body>
</html>

How to get Url Hash (#) from server side

RFC 2396 section 4.1:

When a URI reference is used to perform a retrieval action on the identified resource, the optional fragment identifier, separated from the URI by a crosshatch ("#") character, consists of additional reference information to be interpreted by the user agent after the retrieval action has been successfully completed. As such, it is not part of a URI, but is often used in conjunction with a URI.

(emphasis added)

Excel Define a range based on a cell value

Based on answer by @Cici I give here a more generic solution:

=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))

In Italian version of Excel:

=SOMMA(INDIRETTO(CONCATENA(B1;C1)):INDIRETTO(CONCATENA(B2;C2)))

Where B1-C2 cells hold these values:

  • A, 1
  • A, 5

You can change these valuese to change the final range at wish.


Splitting the formula in parts:

  • SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
  • CONCATENATE(B1,C1) - result is A1
  • INDIRECT(CONCATENATE(B1,C1)) - result is reference to A1

Hence:

=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))

results in

=SUM(A1:A5)


I'll write down here a couple of SEO keywords for Italian users:

  • come creare dinamicamente l'indirizzo di un intervallo in excel
  • formula per definire un intervallo di celle in excel.

Con la formula indicata qui sopra basta scrivere nelle caselle da B1 a C2 gli estremi dell'intervallo per vedelo cambiare dentro la formula stessa.

Why do Sublime Text 3 Themes not affect the sidebar?

I first thought I was using SBT 3, then realized I was using version 2 still....


I finally got the sidebar to be dark on Windows!

I noticed that when I had my user settings theme set to "Soda Dark 3.sublime-theme" it would half-way work but you could not see the folder structure. So I decided to try the other option in the Theme - Soda folder without the "3" and it worked right away. This should work below in your Preferences > Settings - User file.

{   
    "theme": "Soda Dark.sublime-theme",
    "color_scheme": "Packages/Color Scheme - Default/Monokai.tmTheme"
}

What are the undocumented features and limitations of the Windows FINDSTR command?

The findstr command sets the ErrorLevel (or exit code) to one of the following values, given that there are no invalid or incompatible switches and no search string exceeds the applicable length limit:

  • 0 when at least a single match is encountered in one line throughout all specified files;
  • 1 otherwise;

A line is considered to contain a match when:

  • no /V option is given and the search expression occurs at least once;
  • the /V option is given and the search expression does not occur;

This means that the /V option also changes the returned ErrorLevel, but it does not just revert it!

For example, when you have got a file test.txt with two lines, one of which contains the string text but the other one does not, both findstr "text" "test.txt" and findstr /V "text" "test.txt" return an ErrorLevel of 0.

Basically you can say: if findstr returns at least a line, ErrorLevel is set to 0, else to 1.

Note that the /M option does not affect the ErrorLevel value, it just alters the output.

(Just for the sake of completeness: the find command behaves exactly the same way with respect to the /V option and ErrorLevel; the /C option does not affect ErrorLevel.)

Is there a function to copy an array in C/C++?

in C++11 you may use Copy() that works for std containers

template <typename Container1, typename Container2>
auto Copy(Container1& c1, Container2& c2)
    -> decltype(c2.begin())
{
    auto it1 = std::begin(c1);
    auto it2 = std::begin(c2);

    while (it1 != std::end(c1)) {
        *it2++ = *it1++;
    }
    return it2;
}

How do you declare an interface in C++?

The whole reason you have a special Interface type-category in addition to abstract base classes in C#/Java is because C#/Java do not support multiple inheritance.

C++ supports multiple inheritance, and so a special type isn't needed. An abstract base class with no non-abstract (pure virtual) methods is functionally equivalent to a C#/Java interface.

Send form data using ajax

The code you've posted has two problems:

First: <input type="buttom" should be <input type="button".... This probably is just a typo but without button your input will be treated as type="text" as the default input type is text.

Second: In your function f() definition, you are using the form parameter thinking it's already a jQuery object by using form.attr("action"). Then similarly in the $.post method call, you're passing fname and lname which are HTMLInputElements. I believe what you want is form's action url and input element's values.

Try with the following changes:

HTML

<form action="/echo/json/" method="post">
    <input type="text" name="lname" />
    <input type="text" name="fname" />

    <!-- change "buttom" to "button" -->
    <input type="button" name="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " />
</form>

JavaScript

function f(form, fname, lname) {
    att = form.action; // Use form.action
    $.post(att, {
        fname: fname.value, // Use fname.value
        lname: lname.value // Use lname.value
    }).done(function (data) {
        alert(data);
    });
    return true;
}

Here is the fiddle.