Programs & Examples On #Numerical stability

How to upload a file to directory in S3 bucket using boto

This is a three liner. Just follow the instructions on the boto3 documentation.

import boto3
s3 = boto3.resource(service_name = 's3')
s3.meta.client.upload_file(Filename = 'C:/foo/bar/baz.filetype', Bucket = 'yourbucketname', Key = 'baz.filetype')

Some important arguments are:

Parameters:

  • Filename (str) -- The path to the file to upload.
  • Bucket (str) -- The name of the bucket to upload to.
  • Key (str) -- The name of the that you want to assign to your file in your s3 bucket. This could be the same as the name of the file or a different name of your choice but the filetype should remain the same.

    Note: I assume that you have saved your credentials in a ~\.aws folder as suggested in the best configuration practices in the boto3 documentation.

  • Difference between except: and except Exception as e: in Python

    In the second you can access the attributes of the exception object:

    >>> def catch():
    ...     try:
    ...         asd()
    ...     except Exception as e:
    ...         print e.message, e.args
    ... 
    >>> catch()
    global name 'asd' is not defined ("global name 'asd' is not defined",)
    

    But it doesn't catch BaseException or the system-exiting exceptions SystemExit, KeyboardInterrupt and GeneratorExit:

    >>> def catch():
    ...     try:
    ...         raise BaseException()
    ...     except Exception as e:
    ...         print e.message, e.args
    ... 
    >>> catch()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in catch
    BaseException
    

    Which a bare except does:

    >>> def catch():
    ...     try:
    ...         raise BaseException()
    ...     except:
    ...         pass
    ... 
    >>> catch()
    >>> 
    

    See the Built-in Exceptions section of the docs and the Errors and Exceptions section of the tutorial for more info.

    Get the value of bootstrap Datetimepicker in JavaScript

    Or try:

    $("#datetimepicker").data().date;
    

    Counting null and non-null values in a single query

    usually i use this trick

    select sum(case when a is null then 0 else 1 end) as count_notnull,
           sum(case when a is null then 1 else 0 end) as count_null
    from tab
    group by a
    

    How does the enhanced for statement work for arrays, and how to get an iterator for an array?

    Google Guava Libraries collection provides such function:

    Iterator<String> it = Iterators.forArray(array);
    

    One should prefere Guava over the Apache Collection (which seems to be abandoned).

    How do I print a list of "Build Settings" in Xcode project?

    This has been answered above, but I wanted to suggest an alternative.

    When in the Build Settings for you project or target, you can go to the Editor menu and select Show Setting Names from the menu. This will change all of the options in the Build Settings pane to the build variable names. The option in the menu changes to Show Setting Titles, select this to change back to the original view.

    This can be handy when you know what build setting you want to use in a script, toggle the setting names in the menu and you can see the variable name.

    Blocking device rotation on mobile web pages

    _x000D_
    _x000D_
    #rotate-device {_x000D_
        width: 100%;_x000D_
        height: 100%;_x000D_
        position: fixed;_x000D_
        z-index: 9999;_x000D_
        top: 0;_x000D_
        left: 0;_x000D_
        background-color: #000;_x000D_
        background-image: url(/path to img/rotate.png);_x000D_
        background-size: 100px 100px;_x000D_
        background-position: center;_x000D_
        background-repeat: no-repeat;_x000D_
        display: none;_x000D_
    }_x000D_
    _x000D_
    @media only screen and (max-device-width: 667px) and (min-device-width: 320px) and (orientation: landscape){_x000D_
     #rotate-device {_x000D_
      display: block;_x000D_
     }_x000D_
    }
    _x000D_
    <div id="rotate-device"></div>
    _x000D_
    _x000D_
    _x000D_

    How to Use slideDown (or show) function on a table row?

    I liked the plugin that Vinny's written and have been using. But in case of tables inside sliding row (tr/td), the rows of nested table are always hidden even after slid up. So I did a quick and simple hack in the plugin not to hide the rows of nested table. Just change the following line

    var $cells = $(this).find('td');
    

    to

    var $cells = $(this).find('> td');
    

    which finds only immediate tds not nested ones. Hope this helps someone using the plugin and have nested tables.

    Ruby: How to post a file via HTTP as multipart/form-data?

    I like RestClient. It encapsulates net/http with cool features like multipart form data:

    require 'rest_client'
    RestClient.post('http://localhost:3000/foo', 
      :name_of_file_param => File.new('/path/to/file'))
    

    It also supports streaming.

    gem install rest-client will get you started.

    IF a == true OR b == true statement

    Comparison expressions should each be in their own brackets:

    {% if (a == 'foo') or (b == 'bar') %}
        ...
    {% endif %}
    

    Alternative if you are inspecting a single variable and a number of possible values:

    {% if a in ['foo', 'bar', 'qux'] %}
        ...
    {% endif %}
    

    setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

    Edit: isMounted is deprecated and will probably be removed in later versions of React. See this and this, isMounted is an Antipattern.


    As the warning states, you are calling this.setState on an a component that was mounted but since then has been unmounted.

    To make sure your code is safe, you can wrap it in

    if (this.isMounted()) {
        this.setState({'time': remainTimeInfo});
    }
    

    to ensure that the component is still mounted.

    Put content in HttpResponseMessage object?

    Inspired by Simon Mattes' answer, I needed to satisfy IHttpActionResult required return type of ResponseMessageResult. Also using nashawn's JsonContent, I ended up with...

            return new System.Web.Http.Results.ResponseMessageResult(
                new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
                {
                    Content = new JsonContent(JsonConvert.SerializeObject(contact, Formatting.Indented))
                });
    

    See nashawn's answer for JsonContent.

    iOS change navigation bar title font and color

    Working in swift 3.0 For changing the title color you need to add titleTextAttributes like this

            let textAttributes = [NSForegroundColorAttributeName:UIColor.white]
            self.navigationController.navigationBar.titleTextAttributes = textAttributes
    
    For changing navigationBar background color you can use this
            self.navigationController.navigationBar.barTintColor = UIColor.white
    
    For changing navigationBar back title and back arrow color you can use this
           self.navigationController.navigationBar.tintColor = UIColor.white
    

    Using Python to execute a command on every file in a folder

    Use os.walk to iterate recursively over directory content:

    import os
    
    root_dir = '.'
    
    for directory, subdirectories, files in os.walk(root_dir):
        for file in files:
            print os.path.join(directory, file)
    

    No real difference between os.system and subprocess.call here - unless you have to deal with strangely named files (filenames including spaces, quotation marks and so on). If this is the case, subprocess.call is definitely better, because you don't need to do any shell-quoting on file names. os.system is better when you need to accept any valid shell command, e.g. received from user in the configuration file.

    Get Max value from List<myType>

    thelist.Max(e => e.age);
    

    how to realize countifs function (excel) in R

    Given a dataset

    df <- data.frame( sex = c('M', 'M', 'F', 'F', 'M'), 
                      occupation = c('analyst', 'dentist', 'dentist', 'analyst', 'cook') )
    

    you can subset rows

    df[df$sex == 'M',] # To get all males
    df[df$occupation == 'analyst',] # All analysts
    

    etc.

    If you want to get number of rows, just call the function nrow such as

    nrow(df[df$sex == 'M',])
    

    Doctrine and LIKE query

    This is not possible with the magic methods, however you can achieve this using DQL (Doctrine Query Language). In your example, assuming you have entity named Orders with Product property, just go ahead and do the following:

    $dql_query = $em->createQuery("
        SELECT o FROM AcmeCodeBundle:Orders o
        WHERE 
          o.OrderEmail = '[email protected]' AND
          o.Product LIKE 'My Products%'
    ");
    $orders = $dql_query->getResult();
    

    Should do exactly what you need.

    python pandas dataframe to dictionary

    Simplest solution:

    df.set_index('id').T.to_dict('records')
    

    Example:

    df= pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id','value'])
    df.set_index('id').T.to_dict('records')
    

    If you have multiple values, like val1, val2, val3,etc and u want them as lists, then use the below code:

    df.set_index('id').T.to_dict('list')
    

    Importing variables from another file?

    Import file1 inside file2:

    To import all variables from file1 without flooding file2's namespace, use:

    import file1
    
    #now use file1.x1, file2.x2, ... to access those variables
    

    To import all variables from file1 to file2's namespace( not recommended):

    from file1 import *
    #now use x1, x2..
    

    From the docs:

    While it is valid to use from module import * at module level it is usually a bad idea. For one, this loses an important property Python otherwise has — you can know where each toplevel name is defined by a simple “search” function in your favourite editor. You also open yourself to trouble in the future, if some module grows additional functions or classes.

    Java 8 Iterable.forEach() vs foreach loop

    One of most upleasing functional forEach's limitations is lack of checked exceptions support.

    One possible workaround is to replace terminal forEach with plain old foreach loop:

        Stream<String> stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());
        Iterable<String> iterable = stream::iterator;
        for (String s : iterable) {
            fileWriter.append(s);
        }
    

    Here is list of most popular questions with other workarounds on checked exception handling within lambdas and streams:

    Java 8 Lambda function that throws exception?

    Java 8: Lambda-Streams, Filter by Method with Exception

    How can I throw CHECKED exceptions from inside Java 8 streams?

    Java 8: Mandatory checked exceptions handling in lambda expressions. Why mandatory, not optional?

    Deny direct access to all .php files except index.php

    URL rewriting could be used to map a URL to .php files. The following rules can identify whether a .php request was made directly or it was re-written. It forbids the request in the first case:

    RewriteEngine On
    RewriteCond %{THE_REQUEST} ^.+?\ [^?]+\.php[?\ ]
    RewriteRule \.php$ - [F]
    RewriteRule test index.php
    

    These rules will forbid all requests that end with .php. However, URLs such as / (which fires index.php), /test (which rewrites to index.php) and /test?f=index.php (which contains index.php in querystring) are still allowed.

    THE_REQUEST contains the full HTTP request line sent by the browser to the server (e.g., GET /index.php?foo=bar HTTP/1.1)

    SQL error "ORA-01722: invalid number"

    Well it also can be :

    SELECT t.col1, t.col2, ('test' + t.col3) as test_col3 
    FROM table t;
    

    where for concatenation in oracle is used the operator || not +.

    In this case you get : ORA-01722: invalid number ...

    Smooth GPS data

    As for least squares fit, here are a couple other things to experiment with:

    1. Just because it's least squares fit doesn't mean that it has to be linear. You can least-squares-fit a quadratic curve to the data, then this would fit a scenario in which the user is accelerating. (Note that by least squares fit I mean using the coordinates as the dependent variable and time as the independent variable.)

    2. You could also try weighting the data points based on reported accuracy. When the accuracy is low weight those data points lower.

    3. Another thing you might want to try is rather than display a single point, if the accuracy is low display a circle or something indicating the range in which the user could be based on the reported accuracy. (This is what the iPhone's built-in Google Maps application does.)

    Get the current language in device

    You can use this code to find out keyboard current

    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    InputMethodSubtype ims = imm.getCurrentInputMethodSubtype();
    String locale = ims.getLocale();
    

    Angular CLI - Please add a @NgModule annotation when using latest

    In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

    So register the ChildComponent in Shared Module manually.

    SQL get the last date time record

    SELECT TOP 1 * FROM foo ORDER BY Dates DESC
    

    Will return one result with the latest date.

    SELECT * FROM foo WHERE foo.Dates = (SELECT MAX(Dates) FROM foo)
    

    Will return all results that have the same maximum date, to the milissecond.

    This is for SQL Server. I'll leave it up to you to use the DATEPART function if you want to use dates but not times.

    What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

    Instead of explicitly defining the path to the interpreter as in /usr/bin/bash/, by using the env command, the interpreter is searched for and launched from wherever it is first found. This has both upsides and downsides

    C split a char array into different variables

    Look at strtok(). strtok() is not a re-entrant function.

    strtok_r() is the re-entrant version of strtok(). Here's an example program from the manual:

       #include <stdio.h>
       #include <stdlib.h>
       #include <string.h>
    
       int main(int argc, char *argv[])
       {
           char *str1, *str2, *token, *subtoken;
           char *saveptr1, *saveptr2;
           int j;
    
           if (argc != 4) {
               fprintf(stderr, "Usage: %s string delim subdelim\n",argv[0]);
               exit(EXIT_FAILURE);
           }
    
           for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
               token = strtok_r(str1, argv[2], &saveptr1);
               if (token == NULL)
                   break;
               printf("%d: %s\n", j, token);
    
               for (str2 = token; ; str2 = NULL) {
                   subtoken = strtok_r(str2, argv[3], &saveptr2);
                   if (subtoken == NULL)
                       break;
                   printf(" --> %s\n", subtoken);
               }
           }
    
           exit(EXIT_SUCCESS);
       }
    

    Sample run which operates on subtokens which was obtained from the previous token based on a different delimiter:

    $ ./a.out hello:word:bye=abc:def:ghi = :
    
    1: hello:word:bye
     --> hello
     --> word
     --> bye
    2: abc:def:ghi
     --> abc
     --> def
     --> ghi
    

    Use mysql_fetch_array() with foreach() instead of while()

    There's not a good way to convert it to foreach, because mysql_fetch_array() just fetches the next result from $result_select. If you really wanted to foreach, you could do pull all the results into an array first, doing something like the following:

    $result_list = array();
    while($row = mysql_fetch_array($result_select)) {
       result_list[] = $row;
    }
    
    foreach($result_list as $row) {
       ...
    }
    

    But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array() works. Why is it so important to use a foreach()?

    EDIT: If this is just for learning purposes: you can't convert this to a foreach. You have to have a pre-existing array to use a foreach() instead of a while(), and mysql_fetch_array() fetches one result per call - there's no pre-existing array for foreach() to iterate through.

    SSH configuration: override the default username

    There is a Ruby gem that interfaces your ssh configuration file which is called sshez.

    All you have to do is sshez <alias> [email protected] -p <port-number>, and then you can connect using ssh <alias>. It is also useful since you can list your aliases using sshez list and can easily remove them using sshez remove alias.

    Change values of select box of "show 10 entries" of jquery datatable

    $(document).ready(function() {
        $('#example').dataTable( {
        "aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]],
        "pageLength": 25
        } );
    } );
    

    aLengthMenu : This parameter allows you to readily specify the entries in the length drop down menu that DataTables shows when pagination is enabled. It can be either a 1D array of options which will be used for both the displayed option and the value, or a 2D array which will use the array in the first position as the value, and the array in the second position as the displayed options (useful for language strings such as 'All').

    Update

    Since DataTables v1.10, the options you are looking for are pageLength and lengthMenu

    Access-control-allow-origin with multiple domains

    I managed to solve this in the Request handling code following advice from 'monsur'.

    string origin = WebOperationContext.Current.IncomingRequest.Headers.Get("Origin");
    
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", origin);
    

    Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

    I solved the issue by adding https binding in my IIS websites and adding 443 SSL port and selecting a self signed certificate in binding.

    enter image description here

    What is the easiest way to parse an INI file in Java?

    Or with standard Java API you can use java.util.Properties:

    Properties props = new Properties();
    try (FileInputStream in = new FileInputStream(path)) {
        props.load(in);
    }
    

    DLL and LIB files - what and why?

    A DLL is a library of functions that are shared among other executable programs. Just look in your windows/system32 directory and you will find dozens of them. When your program creates a DLL it also normally creates a lib file so that the application *.exe program can resolve symbols that are declared in the DLL.

    A .lib is a library of functions that are statically linked to a program -- they are NOT shared by other programs. Each program that links with a *.lib file has all the code in that file. If you have two programs A.exe and B.exe that link with C.lib then each A and B will both contain the code in C.lib.

    How you create DLLs and libs depend on the compiler you use. Each compiler does it differently.

    MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

    sometimes when data grow bigger mysql WHERE IN's could be pretty slow because of query optimization. Try using STRAIGHT_JOIN to tell mysql to execute query as is, e.g.

    SELECT STRAIGHT_JOIN table.field FROM table WHERE table.id IN (...)
    

    but beware: in most cases mysql optimizer works pretty well, so I would recommend to use it only when you have this kind of problem

    Create random list of integers in Python

    Firstly, you should use randrange(0,1000) or randint(0,999), not randint(0,1000). The upper limit of randint is inclusive.

    For efficiently, randint is simply a wrapper of randrange which calls random, so you should just use random. Also, use xrange as the argument to sample, not range.

    You could use

    [a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]
    

    to generate 10,000 numbers in the range using sample 10 times.

    (Of course this won't beat NumPy.)

    $ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
    10 loops, best of 3: 26.1 msec per loop
    
    $ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
    100 loops, best of 3: 18.4 msec per loop
    
    $ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]' 
    100 loops, best of 3: 9.24 msec per loop
    
    $ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
    100 loops, best of 3: 3.79 msec per loop
    
    $ python2.7 -m timeit -s 'from random import shuffle
    > def samplefull(x):
    >   a = range(x)
    >   shuffle(a)
    >   return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
    100 loops, best of 3: 3.16 msec per loop
    
    $ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
    1000 loops, best of 3: 363 usec per loop
    

    But since you don't care about the distribution of numbers, why not just use:

    range(1000)*(10000/1000)
    

    ?

    Javascript "Uncaught TypeError: object is not a function" associativity question

    JavaScript does require semicolons, it's just that the interpreter will insert them for you on line breaks where possible*.

    Unfortunately, the code

    var a = new B(args)(stuff)()
    

    does not result in a syntax error, so no ; will be inserted. (An example which can run is

    var answer = new Function("x", "return x")(function(){return 42;})();
    

    To avoid surprises like this, train yourself to always end a statement with ;.


    * This is just a rule of thumb and not always true. The insertion rule is much more complicated. This blog page about semicolon insertion has more detail.

    JavaScript get clipboard data on paste event (Cross browser)

    Based on l2aelba anwser. This was tested on FF, Safari, Chrome, IE (8,9,10 and 11)

        $("#editText").on("paste", function (e) {
            e.preventDefault();
    
            var text;
            var clp = (e.originalEvent || e).clipboardData;
            if (clp === undefined || clp === null) {
                text = window.clipboardData.getData("text") || "";
                if (text !== "") {
                    if (window.getSelection) {
                        var newNode = document.createElement("span");
                        newNode.innerHTML = text;
                        window.getSelection().getRangeAt(0).insertNode(newNode);
                    } else {
                        document.selection.createRange().pasteHTML(text);
                    }
                }
            } else {
                text = clp.getData('text/plain') || "";
                if (text !== "") {
                    document.execCommand('insertText', false, text);
                }
            }
        });
    

    Where is GACUTIL for .net Framework 4.0 in windows 7?

    There actually is now a GAC Utility for .NET 4.0. It is found in the Microsoft Windows 7 and .NET 4.0 SDK (the SDK supports multiple OSs -- not just Windows 7 -- so if you are using a later OS from Microsoft the odds are good that it's supported).

    This is the SDK. You can download the ISO or do a Web install. Kind-of overkill to download the entire thing if all you want is the GAC Util; however, it does work.

    Multiple separate IF conditions in SQL Server

    IF you are checking one variable against multiple condition then you would use something like this Here the block of code where the condition is true will be executed and other blocks will be ignored.

    IF(@Var1 Condition1)
         BEGIN
          /*Your Code Goes here*/
         END
    
    ELSE IF(@Var1 Condition2)
          BEGIN
            /*Your Code Goes here*/ 
          END 
    
        ELSE      --<--- Default Task if none of the above is true
         BEGIN
           /*Your Code Goes here*/
         END
    

    If you are checking conditions against multiple variables then you would have to go for multiple IF Statements, Each block of code will be executed independently from other blocks.

    IF(@Var1 Condition1)
     BEGIN
       /*Your Code Goes here*/
     END
    
    
    IF(@Var2 Condition1)
     BEGIN
       /*Your Code Goes here*/
     END
    
    
    IF(@Var3 Condition1)
     BEGIN
       /*Your Code Goes here*/
     END
    

    After every IF statement if there are more than one statement being executed you MUST put them in BEGIN..END Block. Anyway it is always best practice to use BEGIN..END blocks

    Update

    Found something in your code some BEGIN END you are missing

    ELSE IF(@ID IS NOT NULL AND @ID in (SELECT ID FROM Places))   -- Outer Most Block ELSE IF
    BEGIN   
         SELECT @MyName = Name ...  
        ...Some stuff....                       
        IF(SOMETHNG_1)         -- IF
                     --BEGIN
            BEGIN TRY               
                UPDATE ....                                                                 
            END TRY
    
            BEGIN CATCH
                SELECT ERROR_MESSAGE() AS 'Message' 
                RETURN -1
            END CATCH
                    -- END
        ELSE IF(SOMETHNG_2)    -- ELSE IF
                     -- BEGIN
            BEGIN TRY
                UPDATE ...                                                      
            END TRY
            BEGIN CATCH
                SELECT ERROR_MESSAGE() AS 'Message' 
                RETURN -1
            END CATCH   
                   -- END
        ELSE                  -- ELSE
            BEGIN
                BEGIN TRY
                    UPDATE ...                                                              
                END TRY
                BEGIN CATCH
                    SELECT ERROR_MESSAGE() AS 'Message' 
                    RETURN -1
                END CATCH   
             END             
          --The above works I then insert this below and these if statement become nested----
              IF(@A!= @SA)
                BEGIN
                 exec Store procedure 
                        @FIELD = 15,
                        ... more params...
                END                 
            IF(@S!= @SS)
              BEGIN
                 exec Store procedure 
                        @FIELD = 10,
                        ... more params...
    

    Sorting arrays in NumPy by column

    You can sort on multiple columns as per Steve Tjoa's method by using a stable sort like mergesort and sorting the indices from the least significant to the most significant columns:

    a = a[a[:,2].argsort()] # First sort doesn't need to be stable.
    a = a[a[:,1].argsort(kind='mergesort')]
    a = a[a[:,0].argsort(kind='mergesort')]
    

    This sorts by column 0, then 1, then 2.

    What is useState() in React?

    useState is one of the hooks available in React v16.8.0. It basically lets you turn your otherwise non-stateful/functional components to one that can have its own state.

    At the very basic level, it's used this way:

    const [isLoading, setLoading] = useState(true);
    

    This then lets you call setLoading passing a boolean value. It's a cool way of having "stateful" functional component.

    Is it possible to clone html element objects in JavaScript / JQuery?

    In one line:

    $('#selector').clone().attr('id','newid').appendTo('#newPlace');
    

    Instant run in Android Studio 2.0 (how to turn off)

    Using Android Studio newest version and update Android Plugin to 'newest alpha version`, I can disable Instant Run: Android studio Instant Run view with Version highlighted Android studio Project view with Android Plugin Version highlighted

    Try to update Android Studio.

    Android Pop-up message

    sample code show custom dialog in kotlin:

    fun showDlgFurtherDetails(context: Context,title: String?, details: String?) {
    
        val dialog = Dialog(context)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setCancelable(false)
        dialog.setContentView(R.layout.dlg_further_details)
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        val lblService = dialog.findViewById(R.id.lblService) as TextView
        val lblDetails = dialog.findViewById(R.id.lblDetails) as TextView
        val imgCloseDlg = dialog.findViewById(R.id.imgCloseDlg) as ImageView
    
        lblService.text = title
        lblDetails.text = details
        lblDetails.movementMethod = ScrollingMovementMethod()
        lblDetails.isScrollbarFadingEnabled = false
        imgCloseDlg.setOnClickListener {
            dialog.dismiss()
        }
        dialog.show()
    }
    

    Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

    For array type Please try this one.

     List<MyStok> myDeserializedObjList = (List<MyStok>)Newtonsoft.Json.JsonConvert.DeserializeObject(sc), typeof(List<MyStok>));
    

    Please See here for details to deserialise Json

    What's the purpose of git-mv?

    As @Charles says, git mv is a shorthand.

    The real question here is "Other version control systems (eg. Subversion and Perforce) treat file renames specially. Why doesn't Git?"

    Linus explains at http://permalink.gmane.org/gmane.comp.version-control.git/217 with characteristic tact:

    Please stop this "track files" crap. Git tracks exactly what matters, namely "collections of files". Nothing else is relevant, and even thinking that it is relevant only limits your world-view. Notice how the notion of CVS "annotate" always inevitably ends up limiting how people use it. I think it's a totally useless piece of crap, and I've described something that I think is a million times more useful, and it all fell out exactly because I'm not limiting my thinking to the wrong model of the world.

    What is the most efficient/elegant way to parse a flat table into a tree?

    This was written quickly, and is neither pretty nor efficient (plus it autoboxes alot, converting between int and Integer is annoying!), but it works.

    It probably breaks the rules since I'm creating my own objects but hey I'm doing this as a diversion from real work :)

    This also assumes that the resultSet/table is completely read into some sort of structure before you start building Nodes, which wouldn't be the best solution if you have hundreds of thousands of rows.

    public class Node {
    
        private Node parent = null;
    
        private List<Node> children;
    
        private String name;
    
        private int id = -1;
    
        public Node(Node parent, int id, String name) {
            this.parent = parent;
            this.children = new ArrayList<Node>();
            this.name = name;
            this.id = id;
        }
    
        public int getId() {
            return this.id;
        }
    
        public String getName() {
            return this.name;
        }
    
        public void addChild(Node child) {
            children.add(child);
        }
    
        public List<Node> getChildren() {
            return children;
        }
    
        public boolean isRoot() {
            return (this.parent == null);
        }
    
        @Override
        public String toString() {
            return "id=" + id + ", name=" + name + ", parent=" + parent;
        }
    }
    
    public class NodeBuilder {
    
        public static Node build(List<Map<String, String>> input) {
    
            // maps id of a node to it's Node object
            Map<Integer, Node> nodeMap = new HashMap<Integer, Node>();
    
            // maps id of a node to the id of it's parent
            Map<Integer, Integer> childParentMap = new HashMap<Integer, Integer>();
    
            // create special 'root' Node with id=0
            Node root = new Node(null, 0, "root");
            nodeMap.put(root.getId(), root);
    
            // iterate thru the input
            for (Map<String, String> map : input) {
    
                // expect each Map to have keys for "id", "name", "parent" ... a
                // real implementation would read from a SQL object or resultset
                int id = Integer.parseInt(map.get("id"));
                String name = map.get("name");
                int parent = Integer.parseInt(map.get("parent"));
    
                Node node = new Node(null, id, name);
                nodeMap.put(id, node);
    
                childParentMap.put(id, parent);
            }
    
            // now that each Node is created, setup the child-parent relationships
            for (Map.Entry<Integer, Integer> entry : childParentMap.entrySet()) {
                int nodeId = entry.getKey();
                int parentId = entry.getValue();
    
                Node child = nodeMap.get(nodeId);
                Node parent = nodeMap.get(parentId);
                parent.addChild(child);
            }
    
            return root;
        }
    }
    
    public class NodePrinter {
    
        static void printRootNode(Node root) {
            printNodes(root, 0);
        }
    
        static void printNodes(Node node, int indentLevel) {
    
            printNode(node, indentLevel);
            // recurse
            for (Node child : node.getChildren()) {
                printNodes(child, indentLevel + 1);
            }
        }
    
        static void printNode(Node node, int indentLevel) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < indentLevel; i++) {
                sb.append("\t");
            }
            sb.append(node);
    
            System.out.println(sb.toString());
        }
    
        public static void main(String[] args) {
    
            // setup dummy data
            List<Map<String, String>> resultSet = new ArrayList<Map<String, String>>();
            resultSet.add(newMap("1", "Node 1", "0"));
            resultSet.add(newMap("2", "Node 1.1", "1"));
            resultSet.add(newMap("3", "Node 2", "0"));
            resultSet.add(newMap("4", "Node 1.1.1", "2"));
            resultSet.add(newMap("5", "Node 2.1", "3"));
            resultSet.add(newMap("6", "Node 1.2", "1"));
    
            Node root = NodeBuilder.build(resultSet);
            printRootNode(root);
    
        }
    
        //convenience method for creating our dummy data
        private static Map<String, String> newMap(String id, String name, String parentId) {
            Map<String, String> row = new HashMap<String, String>();
            row.put("id", id);
            row.put("name", name);
            row.put("parent", parentId);
            return row;
        }
    }
    

    Bootstrap 3 Collapse show state with Chevron icon

    Improvement on Bludream's answer:

    You can definitely use FontAwesome!

    Make sure to include "collapsed" along with "panel-heading" class. The "collapsed" class is not included until you click on the panel so you want to include the "collapsed" class in order to display the correct chevron (i.e., chevron-right is displayed when collapsed and chevron-down when open).

    HTML

    <div class="panel panel-default">
        <div class="panel-heading collapsed" data-toggle="collapse" data-target="#collapseOrderItems1">Products 1 <i class="chevron fa fa-fw" ></i></div>
        <div class="collapse" id="collapseOrderItems1">
            <p>Lorem ipsum...</p>
        </div>
    </div>
    

    CSS

    .panel-heading .chevron:after {
        content: "\f078";   
    }
    .panel-heading.collapsed .chevron:after {
        content: "\f054";   
    }   
    

    Also, it is a good practice to create a new class instead of using an existing class.

    See Codepen for example: http://codepen.io/anon/pen/PPxOJX

    Opening PDF String in new window with javascript

    window.open("data:application/pdf," + escape(pdfString)); 
    

    The above one pasting the encoded content in URL. That makes restriction of the content length in URL and hence PDF file loading failed (because of incomplete content).

    Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

    Depends on the Keymap selected.

    Keymap: Mac OS X ? + Left Right Arrow Keys
    Keymap: Mac OS X 10.5+ ? + [ / ]

    I was facing similar problems in Pycharm. To resolve change your Keymap in Preferences.

    Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

    I was having the same problem too. In my case was caused when trying to reproduce videos with a poor codification (demanded too much memory). This helped me to catch the error and request another version of the same video. https://stackoverflow.com/a/11986400/2508527

    SQL Server: Extract Table Meta-Data (description, fields and their data types)

    select Col.name Columnname,prop.Value Description, tbl.name Tablename, sch.name schemaname
        from sys.columns col  left outer join  sys.extended_properties prop
                        on prop.major_id =  col.object_id and prop.minor_id = col.column_id
                        inner join sys.tables tbl on col.object_id =  tbl.object_id
                        Left outer join sys.schemas sch on sch.schema_id = tbl.schema_id
    

    How to read an external local JSON file in JavaScript?

    Very simple.
    Rename your json file to ".js" instead ".json".

    <script type="text/javascript" src="my_json.js"></script>
    

    So follow your code normally.

    <script type="text/javascript">
    var obj = JSON.parse(contacts);
    

    However, just for information, the content my json it's looks like the snip below.

    contacts='[{"name":"bla bla", "email":bla bla, "address":"bla bla"}]';
    

    How to prevent Browser cache for php site

    You can try this:

        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        header("Connection: close");
    

    Hopefully it will help prevent Cache, if any!

    Get the latest date from grouped MySQL data

    Are you looking for the max date for each model?

    SELECT model, max(date) FROM doc
    GROUP BY model
    

    If you're looking for all models matching the max date of the entire table...

    SELECT model, date FROM doc
    WHERE date IN (SELECT max(date) FROM doc)
    

    [--- Added ---]

    For those who want to display details from every record matching the latest date within each model group (not summary data, as asked for in the OP):

    SELECT d.model, d.date, d.color, d.etc FROM doc d
    WHERE d.date IN (SELECT max(d2.date) FROM doc d2 WHERE d2.model=d.model)
    

    MySQL 8.0 and newer supports the OVER clause, producing the same results a bit faster for larger data sets.

    SELECT model, date, color, etc FROM (SELECT model, date, color, etc, 
      max(date) OVER (PARTITION BY model) max_date FROM doc) predoc 
    WHERE date=max_date;
    

    plot a circle with pyplot

    Similarly to scatter plot you can also use normal plot with circle line style. Using markersize parameter you can adjust radius of a circle:

    import matplotlib.pyplot as plt
    
    plt.plot(200, 2, 'o', markersize=7)
    

    How do I convert array of Objects into one Object in JavaScript?

    Using Object.fromEntries:

    _x000D_
    _x000D_
    const array = [_x000D_
        { key: "key1", value: "value1" },_x000D_
        { key: "key2", value: "value2" },_x000D_
    ];_x000D_
    _x000D_
    const obj = Object.fromEntries(array.map(item => [item.key, item.value]));_x000D_
    _x000D_
    console.log(obj);
    _x000D_
    _x000D_
    _x000D_

    How do I do top 1 in Oracle?

    SELECT *
      FROM (SELECT * FROM MyTbl ORDER BY Fname )
     WHERE ROWNUM = 1;
    

    Paging UICollectionView by cells, not screen

    The original answer of ????? ???????? had an issue, so on the last cell collection view was scrolling to the beginning

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        targetContentOffset.pointee = scrollView.contentOffset
        var indexes = yourCollectionView.indexPathsForVisibleItems
        indexes.sort()
        var index = indexes.first!
        // if velocity.x > 0 && (Get the number of items from your data) > index.row + 1 {
        if velocity.x > 0 && yourCollectionView.numberOfItems(inSection: 0) > index.row + 1 {
           index.row += 1
        } else if velocity.x == 0 {
            let cell = yourCollectionView.cellForItem(at: index)!
            let position = yourCollectionView.contentOffset.x - cell.frame.origin.x
            if position > cell.frame.size.width / 2 {
               index.row += 1
            }
        }
        
        yourCollectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true )
    }
    

    How to fix "Incorrect string value" errors?

    MySQL’s utf-8 types are not actually proper utf-8 – it only uses up to three bytes per character and supports only the Basic Multilingual Plane (i.e. no Emoji, no astral plane, etc.).

    If you need to store values from higher Unicode planes, you need the utf8mb4 encodings.

    How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

    This should do it for you.

    <div id="nav-wrap">
        <ul id="nav">
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
        </ul>
    </div>
    
    #nav-wrap {
        float: left;
        height: 87px;
        width: 900px;
    }
    
    #nav {
        display: inline;
        height: 87px;
        width: 100%;
    }
    
    .nav-item {
        float: left;
        height: 87px;
        line-height: 87px;
        text-align: center;
        text-decoration: none;
        width: 150px;
    
    }
    

    How to vertical align an inline-block in a line of text?

    display: inline-block is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:

    Working Example

    (it looks like your picture anyway ;))

    CSS:

    p, div {
      display: inline-block; 
      vertical-align: middle;
    }
    p, div {
      display: inline !ie7; /* hack for IE7 and below */
    }
    
    table {
      background: #000; 
      color: #fff; 
      font-size: 16px; 
      font-weight: bold; margin: 0 10px;
    }
    
    td {
      padding: 5px; 
      text-align: center;
    }
    

    HTML:

    <p>some text</p> 
    <div>
      <table summary="">
      <tr><td>A</td></tr>
      <tr><td>B</td></tr>
      <tr><td>C</td></tr>
      <tr><td>D</td></tr>
      </table>
    </div> 
    <p>continues afterwards</p>
    

    Deleting objects from an ArrayList in Java

    Whilst this is counter intuitive this is the way that i sped up this operation by a huge amount.

    Exactly what i was doing:

    ArrayList < HashMap < String , String >> results; // This has been filled with a whole bunch of results
    

    ArrayList < HashMap < String , String > > discard = findResultsToDiscard(results);

    results.removeall(discard);

    However the remove all method was taking upwards of 6 seconds (NOT including the method to get the discard results) to remove approximately 800 results from an array of 2000 (ish).

    I tried the iterator method suggested by gustafc and others on this post.

    This did speed up the operation slightly (down to about 4 seconds) however this was still not good enough. So i tried something risky...

     ArrayList < HashMap < String, String>> results;
    
      List < Integer > noIndex = getTheDiscardedIndexs(results);
    
    for (int j = noIndex.size()-1; j >= 0; j-- ){
        results.remove(noIndex.get(j).intValue());
    }
    

    whilst the getTheDiscardedIndexs save an array of index's rather then an array of HashMaps. This it turns out sped up removing objects much quicker ( about 0.1 of a second now) and will be more memory efficient as we dont need to create a large array of results to remove.

    Hope this helps someone.

    How to use log levels in java

    Generally, you don't need all those levels, SEVERE, WARNING, INFO, FINE might be enough. We're using Log4J (not java.util.logging directly) and the following levels (which might differ in name from other logging frameworks):

    • ERROR: Any error/exception that is or might be critical. Our Logger automatically sends an email for each such message on our servers (usage: logger.error("message"); )

    • WARN: Any message that might warn us of potential problems, e.g. when a user tried to log in with wrong credentials - which might indicate an attack if that happens often or in short periods of time (usage: logger.warn("message"); )

    • INFO: Anything that we want to know when looking at the log files, e.g. when a scheduled job started/ended (usage: logger.info("message"); )

    • DEBUG: As the name says, debug messages that we only rarely turn on. (usage: logger.debug("message"); )

    The beauty of this is that if you set the log level to WARN, info and debug messages have next to no performance impact. If you need to get additional information from a production system you just can lower the level to INFO or DEBUG for a short period of time (since you'd get much more log entries which make your log files bigger and harder to read). Adjusting log levels etc. can normally be done at runtime (our JBoss instance checks for changes in that config every minute or so).

    How to map a composite key with JPA and Hibernate?

    Another option is to map is as a Map of composite elements in the ConfPath table.

    This mapping would benefit from an index on (ConfPathID,levelStation) though.

    public class ConfPath {
        private Map<Long,Time> timeForLevelStation = new HashMap<Long,Time>();
    
        public Time getTime(long levelStation) {
            return timeForLevelStation.get(levelStation);
        }
    
        public void putTime(long levelStation, Time newValue) {
            timeForLevelStation.put(levelStation, newValue);
        }
    }
    
    public class Time {
        String src;
        String dst;
        long distance;
        long price;
    
        public long getDistance() {
            return distance;
        }
    
        public void setDistance(long distance) {
            this.distance = distance;
        }
    
        public String getDst() {
            return dst;
        }
    
        public void setDst(String dst) {
            this.dst = dst;
        }
    
        public long getPrice() {
            return price;
        }
    
        public void setPrice(long price) {
            this.price = price;
        }
    
        public String getSrc() {
            return src;
        }
    
        public void setSrc(String src) {
            this.src = src;
        }
    }
    

    Mapping:

    <class name="ConfPath" table="ConfPath">
        <id column="ID" name="id">
            <generator class="native"/>
        </id>
        <map cascade="all-delete-orphan" name="values" table="example"
                lazy="extra">
            <key column="ConfPathID"/>
            <map-key type="long" column="levelStation"/>
            <composite-element class="Time">
                <property name="src" column="src" type="string" length="100"/>
                <property name="dst" column="dst" type="string" length="100"/>
                <property name="distance" column="distance"/>
                <property name="price" column="price"/>
            </composite-element>
        </map>
    </class>
    

    '\r': command not found - .bashrc / .bash_profile

    SUBLIME TEXT

    With sublime you just go to

    View - > Line Endings -> (select)Unix

    Then save the file. Will fix this issue.

    Easy as that!

    How can I clear the terminal in Visual Studio Code?

    workbench.action.terminal.clear no longer works (at least for VS Code Insiders 1.54 on Mac)

    The following is the way to now map CTRL+L yo the default console functionality.

    {
        "key": "ctrl+l",
        "command": "workbench.action.terminal.sendSequence",
        "args": {"text": "\u000c"},
        "when": "terminalFocus"
    }
    

    In C# check that filename is *possibly* valid (not that it exists)

    Thought I would post a solution I cobbled together from bits of answers I found after searching for a robust solution to the same problem. Hopefully it helps someone else.

    using System;
    using System.IO;
    //..
    
    public static bool ValidateFilePath(string path, bool RequireDirectory, bool IncludeFileName, bool RequireFileName = false)
    {
        if (string.IsNullOrEmpty(path)) { return false; }
        string root = null;
        string directory = null;
        string filename = null;
        try
        {
            // throw ArgumentException - The path parameter contains invalid characters, is empty, or contains only white spaces.
            root = Path.GetPathRoot(path);
    
            // throw ArgumentException - path contains one or more of the invalid characters defined in GetInvalidPathChars.
            // -or- String.Empty was passed to path.
            directory = Path.GetDirectoryName(path);
    
            // path contains one or more of the invalid characters defined in GetInvalidPathChars
            if (IncludeFileName) { filename = Path.GetFileName(path); }
        }
        catch (ArgumentException)
        {
            return false;
        }
    
        // null if path is null, or an empty string if path does not contain root directory information
        if (String.IsNullOrEmpty(root)) { return false; }
    
        // null if path denotes a root directory or is null. Returns String.Empty if path does not contain directory information
        if (String.IsNullOrEmpty(directory)) { return false; }
    
        if (RequireFileName)
        {
            // if the last character of path is a directory or volume separator character, this method returns String.Empty
            if (String.IsNullOrEmpty(filename)) { return false; }
    
            // check for illegal chars in filename
            if (filename.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { return false; }
        }
        return true;
    }
    

    Import Script from a Parent Directory

    If you want to run the script directly, you can:

    1. Add the FolderA's path to the environment variable (PYTHONPATH).
    2. Add the path to sys.path in the your script.

    Then:

    import module_you_wanted
    

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

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

        private File createFile(String path, String fileName) throws IOException {
           ClassLoader classLoader = getClass().getClassLoader();
           File file = new File(classLoader.getResource(".").getFile() + path + fileName);
    
           // Lets create the directory
           try {
              file.getParentFile().mkdir();
           } catch (Exception err){
               System.out.println("ERROR (Directory Create)" + err.getMessage());
           }
    
           // Lets create the file if we have credential
           try {
               file.createNewFile();
           } catch (Exception err){
               System.out.println("ERROR (File Create)" + err.getMessage());
           }
           return  file;
       }
    

    Vertical Align text in a Label

    You don't have to add any padding or edit the line-height!

    Instead, just make sure that when you have an HTML like this :

    <label><input type="checkbox" name=""><span>Checkbox Text</span></label>
    

    Just make sure that the input height and width are the same, and the the text has the same font size.

    Then, it will look perfectly fine and looks centered.

    How to check in Javascript if one element is contained within another

    I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .contains element method. Hope this will help others as well.

    Below is the function:

    function isChildOf(childObject, containerObject) {
      var returnValue = false;
      var currentObject;
    
      if (typeof containerObject === 'string') {
        containerObject = document.getElementById(containerObject);
      }
      if (typeof childObject === 'string') {
        childObject = document.getElementById(childObject);
      }
    
      currentObject = childObject.parentNode;
    
      while (currentObject !== undefined) {
        if (currentObject === document.body) {
          break;
        }
    
        if (currentObject.id == containerObject.id) {
          returnValue = true;
          break;
        }
    
        // Move up the hierarchy
        currentObject = currentObject.parentNode;
      }
    
      return returnValue;
    }
    

    Find max and second max salary for a employee table MySQL

    without nested query

    select max(e.salary) as max_salary, max(e1.salary) as 2nd_max_salary 
    from employee as e
    left join employee as e1 on e.salary != e1.salary
    group by e.salary desc limit 1;
    

    error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

    If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them

    Google Maps: How to create a custom InfoWindow?

    I found InfoBox perfect for advanced styling.

    An InfoBox behaves like a google.maps.InfoWindow, but it supports several additional properties for advanced styling. An InfoBox can also be used as a map label. An InfoBox also fires the same events as a google.maps.InfoWindow.

    Include http://code.google.com/p/google-maps-utility-library-v3/source/browse/trunk/infobox/src/infobox.js in your page

    Java Object Null Check for method

    If array of Books is null, return zero as it looks that method count total price of all Books provided - if no Book is provided, zero is correct value:

    public static double calculateInventoryTotal(Book[] books)
    {
    if(books == null) return 0;
        double total = 0;
        for (int i = 0; i < books.length; i++)
        {
            total += books[i].getPrice();
        }
        return total;
    }
    

    It's upon to you to decide if it's correct that you can input null input value (shoul not be correct, but...).

    How to open mail app from Swift

    @IBAction func launchEmail(sender: AnyObject) {
     if if MFMailComposeViewController.canSendMail() {
       var emailTitle = "Feedback"
       var messageBody = "Feature request or bug report?"
       var toRecipents = ["[email protected]"]
       var mc: MFMailComposeViewController = MFMailComposeViewController()
       mc.mailComposeDelegate = self
       mc.setSubject(emailTitle)
       mc.setMessageBody(messageBody, isHTML: false)
       mc.setToRecipients(toRecipents)
    
       self.present(mc, animated: true, completion: nil)
     } else {
       // show failure alert
     }
    }
    
    func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
        switch result {
        case .cancelled:
            print("Mail cancelled")
        case .saved:
            print("Mail saved")
        case .sent:
            print("Mail sent")
        case .failed:
            print("Mail sent failure: \(error?.localizedDescription)")
        default:
            break
        }
        self.dismiss(animated: true, completion: nil)
    }
    

    Note that not all users have their device configure to send emails, which is why we need to check the result of canSendMail() before trying to send. Note also that you need to catch the didFinishWith callback in order to dismiss the mail window.

    Open new popup window without address bars in firefox & IE

    I know this is a very old question, yes, I agree we can not hide address bar in modern browsers, but we can hide the url in address bar (e.g show url about:blank), following is my work around solution.

    var iframe = '<html><head><style>body, html {width: 100%; height: 100%; margin: 0; padding: 0}</style></head><body><iframe src="https://www.w3schools.com" style="height:calc(100% - 4px);width:calc(100% - 4px)"></iframe></html></body>';
    
    var win = window.open("","","width=600,height=480,toolbar=no,menubar=no,resizable=yes");
    win.document.write(iframe);
    

    Razor View throwing "The name 'model' does not exist in the current context"

    Changing following line in web.config of view folder solved the same error.

    From

     <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    

    To

    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    

    Why doesn't calling a Python string method do anything unless you assign its output?

    This is because strings are immutable in Python.

    Which means that X.replace("hello","goodbye") returns a copy of X with replacements made. Because of that you need replace this line:

    X.replace("hello", "goodbye")
    

    with this line:

    X = X.replace("hello", "goodbye")
    

    More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace,strip,translate,lower/upper,join,...

    You must assign their output to something if you want to use it and not throw it away, e.g.

    X  = X.strip(' \t')
    X2 = X.translate(...)
    Y  = X.lower()
    Z  = X.upper()
    A  = X.join(':')
    B  = X.capitalize()
    C  = X.casefold()
    

    and so on.

    How to configure PHP to send e-mail?

    You won't be able to send a message through other people mail servers. Check with your host provider how to send emails. Try to send an email from your server without PHP, you can use any email client like Outook. Just after it works, try to configure PHP.ini with your email client SMTP (sending e-mail) configuration.

    Sort arrays of primitive types in descending order

    There's been some confusion about Arrays.asList in the other answers. If you say

    double[] arr = new double[]{6.0, 5.0, 11.0, 7.0};
    List xs = Arrays.asList(arr);
    System.out.println(xs.size());  // prints 1
    

    then you'll have a List with 1 element. The resulting List has the double[] array as its own element. What you want is to have a List<Double> whose elements are the elements of the double[].

    Unfortunately, no solution involving Comparators will work for a primitive array. Arrays.sort only accepts a Comparator when being passed an Object[]. And for the reasons describe above, Arrays.asList won't let you make a List out of the elements of your array.

    So despite my earlier answer which the comments below reference, there's no better way than manually reversing the array after sorting. Any other approach (such as copying the elements into a Double[] and reverse-sorting and copying them back) would be more code and slower.

    How to make JQuery-AJAX request synchronous

    Instead of adding onSubmit event, you can prevent the default action for submit button.

    So, in the following html:

    <form name="form" action="insert.php" method="post">
        <input type='submit' />
    </form>?
    

    first, prevent submit button action. Then make the ajax call asynchronously, and submit the form when the password is correct.

    $('input[type=submit]').click(function(e) {
        e.preventDefault(); //prevent form submit when button is clicked
    
        var password = $.trim($('#employee_password').val());
    
         $.ajax({
            type: "POST",
            url: "checkpass.php",
            data: "password="+password,
            success: function(html) {
                var arr=$.parseJSON(html);
                var $form = $('form');
                if(arr == "Successful")
                {    
                    $form.submit(); //submit the form if the password is correct
                }
            }
        });
    });????????????????????????????????
    

    How to redirect single url in nginx?

    location ~ /issue([0-9]+) {
        return 301 http://example.com/shop/issues/custom_isse_name$1;
    }
    

    Does Java SE 8 have Pairs or Tuples?

    UPDATE: This answer is in response to the original question, Does Java SE 8 have Pairs or Tuples? (And implicitly, if not, why not?) The OP has updated the question with a more complete example, but it seems like it can be solved without using any kind of Pair structure. [Note from OP: here is the other correct answer.]


    The short answer is no. You either have to roll your own or bring in one of the several libraries that implements it.

    Having a Pair class in Java SE was proposed and rejected at least once. See this discussion thread on one of the OpenJDK mailing lists. The tradeoffs are not obvious. On the one hand, there are many Pair implementations in other libraries and in application code. That demonstrates a need, and adding such a class to Java SE will increase reuse and sharing. On the other hand, having a Pair class adds to the temptation of creating complicated data structures out of Pairs and collections without creating the necessary types and abstractions. (That's a paraphrase of Kevin Bourillion's message from that thread.)

    I recommend everybody read that entire email thread. It's remarkably insightful and has no flamage. It's quite convincing. When it started I thought, "Yeah, there should be a Pair class in Java SE" but by the time the thread reached its end I had changed my mind.

    Note however that JavaFX has the javafx.util.Pair class. JavaFX's APIs evolved separately from the Java SE APIs.

    As one can see from the linked question What is the equivalent of the C++ Pair in Java? there is quite a large design space surrounding what is apparently such a simple API. Should the objects be immutable? Should they be serializable? Should they be comparable? Should the class be final or not? Should the two elements be ordered? Should it be an interface or a class? Why stop at pairs? Why not triples, quads, or N-tuples?

    And of course there is the inevitable naming bikeshed for the elements:

    • (a, b)
    • (first, second)
    • (left, right)
    • (car, cdr)
    • (foo, bar)
    • etc.

    One big issue that has hardly been mentioned is the relationship of Pairs to primitives. If you have an (int x, int y) datum that represents a point in 2D space, representing this as Pair<Integer, Integer> consumes three objects instead of two 32-bit words. Furthermore, these objects must reside on the heap and will incur GC overhead.

    It would seem clear that, like Streams, it would be essential for there to be primitive specializations for Pairs. Do we want to see:

    Pair
    ObjIntPair
    ObjLongPair
    ObjDoublePair
    IntObjPair
    IntIntPair
    IntLongPair
    IntDoublePair
    LongObjPair
    LongIntPair
    LongLongPair
    LongDoublePair
    DoubleObjPair
    DoubleIntPair
    DoubleLongPair
    DoubleDoublePair
    

    Even an IntIntPair would still require one object on the heap.

    These are, of course, reminiscent of the proliferation of functional interfaces in the java.util.function package in Java SE 8. If you don't want a bloated API, which ones would you leave out? You could also argue that this isn't enough, and that specializations for, say, Boolean should be added as well.

    My feeling is that if Java had added a Pair class long ago, it would have been simple, or even simplistic, and it wouldn't have satisfied many of the use cases we are envisioning now. Consider that if Pair had been added in the JDK 1.0 time frame, it probably would have been mutable! (Look at java.util.Date.) Would people have been happy with that? My guess is that if there were a Pair class in Java, it would be kinda-sort-not-really-useful and everybody will still be rolling their own to satisfy their needs, there would be various Pair and Tuple implementations in external libraries, and people would still be arguing/discussing about how to fix Java's Pair class. In other words, kind of in the same place we're at today.

    Meanwhile, some work is going on to address the fundamental issue, which is better support in the JVM (and eventually the Java language) for value types. See this State of the Values document. This is preliminary, speculative work, and it covers only issues from the JVM perspective, but it already has a fair amount of thought behind it. Of course there are no guarantees that this will get into Java 9, or ever get in anywhere, but it does show the current direction of thinking on this topic.

    How to open select file dialog via js?

    With jquery library

    <button onclick="$('.inputFile').click();">Select File ...</button>
    <input class="inputFile" type="file" style="display: none;">
    

    how to change background image of button when clicked/focused?

    1. Create a file in drawable play_pause.xml
    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:state_selected="true"
              android:drawable="@drawable/pause" />
    
        <item android:state_selected="false"
              android:drawable="@drawable/play" />
        <!-- default -->
    </selector>
    
    1. In xml file add this below code
     <ImageView
                    android:id="@+id/iv_play"
                    android:layout_width="@dimen/_50sdp"
                    android:layout_height="@dimen/_50sdp"
                    android:layout_centerInParent="true"
                    android:layout_centerHorizontal="true"
                    android:background="@drawable/pause_button"
                    android:gravity="center"
                    android:scaleType="fitXY" />
    
    1. In java file add this below code
    iv_play = (ImageView) findViewById(R.id.iv_play);
    iv_play.setSelected(false);
    

    and also add this

    iv_play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    iv_play.setSelected(!iv_play.isSelected());
                    if (iv_play.isSelected()) {
                        ((GifDrawable) gif_1.getDrawable()).start();
                        ((GifDrawable) gif_2.getDrawable()).start();
                    } else {
                        iv_play.setSelected(false);
                        ((GifDrawable) gif_1.getDrawable()).stop();
                        ((GifDrawable) gif_2.getDrawable()).stop();
                    }
                }
            });
    

    bootstrap 3 tabs not working properly

    In my case we were setting the div id as a number and setting the href="#123", this did not work.. adding a prefix to the id helped.

    Example: This did not work-

    <li> <a data-toggle="tab" href="#@i"> <li/>
    ...
    <div class="tab-pane" id="#@i">
    

    This worked:

    <li><a data-toggle="tab" href="#prefix@i"><li/>
    ...
    <div class="tab-pane" id="#prefix@i">
    

    Show div #id on click with jQuery

    The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready() then it should work perfectly well:

    $(document).ready(
        function(){
            $("#music").click(function () {
                $("#musicinfo").show("slow");
            });
    
        });
    

    An alternative is to place the <script></script> at the foot of the page, so it's encountered after the DOM has been loaded and ready.

    To make the div hide again, once the #music element is clicked, simply use toggle():

    $(document).ready(
        function(){
            $("#music").click(function () {
                $("#musicinfo").toggle();
            });
        });
    

    JS Fiddle demo.

    And for fading:

    $(document).ready(
        function(){
            $("#music").click(function () {
                $("#musicinfo").fadeToggle();
            });
        });
    

    JS Fiddle demo.

    how to set the default value to the drop down list control?

    lstDepartment.DataTextField = "DepartmentName";
    lstDepartment.DataValueField = "DepartmentID";
    lstDepartment.DataSource = dtDept;
    lstDepartment.DataBind();
    'Set the initial value:
    lstDepartment.SelectedValue = depID;
    lstDepartment.Attributes.Remove("InitialValue");
    lstDepartment.Attributes.Add("InitialValue", depID);
    

    And in your cancel method:

    lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue");
    

    And in your update method:

    lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue;
    

    Xamarin.Forms ListView: Set the highlight color of a tapped item

    Here is the purely cross platform and neat way:

    1) Define a trigger action

    namespace CustomTriggers {
       public class DeselectListViewItemAction:TriggerAction<ListView> {
           protected override void Invoke(ListView sender) {
                    sender.SelectedItem = null;
           }
       }
    }
    

    2) Apply the above class instance as an EventTrigger action in XAML as below

     <ListView x:Name="YourListView" ItemsSource="{Binding ViewModelItems}">
        <ListView.Triggers>
            <EventTrigger Event="ItemSelected">
                <customTriggers:DeselectListViewItemAction></customTriggers:DeselectListViewItemAction>
            </EventTrigger>
        </ListView.Triggers>
    </ListView>
    

    Don't forget to add xmlns:customTriggers="clr-namespace:CustomTriggers;assembly=ProjectAssembly"

    Note: Because none of your items are in selected mode, selection styling will not get applied on either of the platforms.

    How does the "final" keyword in Java work? (I can still modify an object.)

    This is a very good interview question. Sometimes they might even ask you what is the difference between a final object and immutable object.

    1) When someone mentions a final object, it means that the reference cannot be changed, but its state(instance variables) can be changed.

    2) An immutable object is one whose state can not be changed, but its reference can be changed. Ex:

        String x = new String("abc"); 
        x = "BCG";
    

    ref variable x can be changed to point a different string, but value of "abc" cannot be changed.

    3) Instance variables(non static fields) are initialized when a constructor is called. So you can initialize values to you variables inside a constructor.

    4) "But i see that you can change the value in the constructor/methods of the class". -- You cannot change it inside a method.

    5) A static variable is initialized during class loading. So you cannot initialize inside a constructor, it has to be done even before it. So you need to assign values to a static variable during declaration itself.

    How can I get the values of data attributes in JavaScript code?

    You could also grab the attributes with the getAttribute() method which will return the value of a specific HTML attribute.

    _x000D_
    _x000D_
    var elem = document.getElementById('the-span');_x000D_
    _x000D_
    var typeId = elem.getAttribute('data-typeId');_x000D_
    var type   = elem.getAttribute('data-type');_x000D_
    var points = elem.getAttribute('data-points');_x000D_
    var important = elem.getAttribute('data-important');_x000D_
    _x000D_
    console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`_x000D_
    );
    _x000D_
    <span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>
    _x000D_
    _x000D_
    _x000D_

    How to know user has clicked "X" or the "Close" button?

    Assuming you're asking for WinForms, you may use the FormClosing() event. The event FormClosing() is triggered any time a form is to get closed.

    To detect if the user clicked either X or your CloseButton, you may get it through the sender object. Try to cast sender as a Button control, and verify perhaps for its name "CloseButton", for instance.

    private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
        if (string.Equals((sender as Button).Name, @"CloseButton"))
            // Do something proper to CloseButton.
        else
            // Then assume that X has been clicked and act accordingly.
    }
    

    Otherwise, I have never ever needed to differentiate whether X or CloseButton was clicked, as I wanted to perform something specific on the FormClosing event, like closing all MdiChildren before closing the MDIContainerForm, or event checking for unsaved changes. Under these circumstances, we don't need, according to me, to differentiate from either buttons.

    Closing by ALT+F4 will also trigger the FormClosing() event, as it sends a message to the Form that says to close. You may cancel the event by setting the

    FormClosingEventArgs.Cancel = true. 
    

    In our example, this would translate to be

    e.Cancel = true.
    

    Notice the difference between the FormClosing() and the FormClosed() events.

    FormClosing occurs when the form received the message to be closed, and verify whether it has something to do before it is closed.

    FormClosed occurs when the form is actually closed, so after it is closed.

    Does this help?

    Printing HashMap In Java

    You can use Entry class to read HashMap easily.

    for(Map.Entry<TypeKey, TypeKey> temp : example.entrySet()){
        System.out.println(temp.getValue()); // Or something as per temp defination. can be used
    }
    

    Creating Unicode character from its number

    String st="2202";
    int cp=Integer.parseInt(st,16);// it convert st into hex number.
    char c[]=Character.toChars(cp);
    System.out.println(c);// its display the character corresponding to '\u2202'.
    

    Make a Bash alias that takes a parameter?

    To give specific answer to the Question posed about creating the alias to move the files to Trash folder instead of deleting them:

    alias rm="mv "$1" -t ~/.Trash/"
    

    Offcourse you have to create dir ~/.Trash first.

    Then just give following command:

    $rm <filename>
    $rm <dirname>
    

    Convert a number into a Roman Numeral in javaScript

    function convertToRoman (num) {
        var v = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
        var r = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
        var s = "";
        for(i = 0; i < v.length; i++) {
            value = parseInt(num/v[i]);
            for(j = 0; j < value; j++) {
                s += r[i];
            }
            num = num%v[i];
        }
        return s;
    }
    

    Sort a list of lists with a custom compare function

    You need to slightly modify your compare function and use functools.cmp_to_key to pass it to sorted. Example code:

    import functools
    
    lst = [list(range(i, i+5)) for i in range(5, 1, -1)]
    
    def fitness(item):
        return item[0]+item[1]+item[2]+item[3]+item[4]
    def compare(item1, item2):
        return fitness(item1) - fitness(item2)
    
    sorted(lst, key=functools.cmp_to_key(compare))
    

    Output:

    [[2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9]]
    

    Works :)

    Mongoose delete array element in document and save

    The checked answer does work but officially in MongooseJS latest, you should use pull.

    doc.subdocs.push({ _id: 4815162342 }) // added
    doc.subdocs.pull({ _id: 4815162342 }) // removed
    

    https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull

    I was just looking that up too.

    See Daniel's answer for the correct answer. Much better.

    Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

    TensorFlow 2.3.0 works fine with CUDA 11. But you have to install tf-nightly-gpu (after you installed tensorflow and CUDA 11): https://pypi.org/project/tf-nightly-gpu/

    Try:

    pip install tf-nightly-gpu
    

    Afterwards you'll get the message in your console:

    I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudart64_110.dll
    

    How to change line color in EditText

    You can do it dynamically if you have custom class for edittext.

    First of all you have declare state and color of edittext given below.

    int[][] states = new int[][]{
                    new int[]{-android.R.attr.state_focused}, // enabled
                    new int[]{android.R.attr.state_focused}, // disabled
            };
            int[] colors = new int[]{
                    secondaryColor,
                    primaryColor,
            };
    

    Then Create ColorStateList variable with that

    ColorStateList myList = new ColorStateList(states, colors);
    

    Then last step is to assign it to edittext.

    editText.setBackgroundTintList(myList);
    

    After this you have to written on focused change event.

    this.setOnFocusChangeListener(new OnFocusChangeListener() {
                        @Override
                        public void onFocusChange(View view, boolean b) {
                            setUnderlineColor(selectionColor,deselectionColor);
                        }
                    });
    

    And you can make above code inside setUnderlineClor() Method,

    private void setUnderlineColor(int primaryColor, int secondaryColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int[][] states = new int[][]{
                    new int[]{-android.R.attr.state_focused}, // enabled
                    new int[]{android.R.attr.state_focused}, // disabled
            };
            int[] colors = new int[]{
                    secondaryColor,
                    primaryColor,
            };
            ColorStateList myList = new ColorStateList(states, colors);
            setBackgroundTintList(myList);
        }
    }
    

    default web page width - 1024px or 980px?

    If it isn't I could see things heading that way.

    I'm working on redoing the website for the company I work for and the designer they hired used a 960px width layout. There is also a 960px grid system that seems to be getting quite popular (http://960.gs/).

    I've been out of web stuff for a few years but from what I've read catching up on things it seems 960/980 is about right. For mobile ~320px sticks in my mind, by which 960 is divisible. 960 is also evenly divisible by 2, 3, 4, 5, and 6.

    How to bind event listener for rendered elements in Angular 2?

    HostListener should be the proper way to bind event into your component:

    @Component({
      selector: 'your-element'
    })
    
    export class YourElement {
      @HostListener('click', ['$event']) onClick(event) {
         console.log('component is clicked');
         console.log(event);
      }
    }
    

    Send text to specific contact programmatically (whatsapp)

    _x000D_
    _x000D_
     public void shareWhatsup(String text) {_x000D_
    _x000D_
    _x000D_
            String smsNumber = "91+" + "9879098469"; // E164 format without '+' sign_x000D_
    _x000D_
            Intent intent = new Intent(Intent.ACTION_VIEW);_x000D_
    _x000D_
            try {_x000D_
                String url = "https://api.whatsapp.com/send?phone=" + smsNumber + "&text=" + URLEncoder.encode(text, "UTF-8");_x000D_
                intent.setPackage("com.whatsapp");_x000D_
                intent.setData(Uri.parse(url));_x000D_
            } catch (Exception e) {_x000D_
                e.printStackTrace();_x000D_
            }_x000D_
    _x000D_
            //    intent.setAction(Intent.ACTION_SEND);_x000D_
            //   intent.setType("image/jpeg");_x000D_
            //   intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUriArray);_x000D_
            startActivity(intent);_x000D_
    _x000D_
    _x000D_
        }
    _x000D_
    _x000D_
    _x000D_

    Find if variable is divisible by 2

    var x = 2;
    x % 2 ? oddFunction() : evenFunction();
    

    ListBox vs. ListView - how to choose for data binding

    A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

    If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

    How to write a Unit Test?

    This is a very generic question and there is a lot of ways it can be answered.

    If you want to use JUnit to create the tests, you need to create your testcase class, then create individual test methods that test specific functionality of your class/module under tests (single testcase classes are usually associated with a single "production" class that is being tested) and inside these methods execute various operations and compare the results with what would be correct. It is especially important to try and cover as many corner cases as possible.

    In your specific example, you could for example test the following:

    1. A simple addition between two positive numbers. Add them, then verify the result is what you would expect.
    2. An addition between a positive and a negative number (which returns a result with the sign of the first argument).
    3. An addition between a positive and a negative number (which returns a result with the sign of the second argument).
    4. An addition between two negative numbers.
    5. An addition that results in an overflow.

    To verify the results, you can use various assertXXX methods from the org.junit.Assert class (for convenience, you can do 'import static org.junit.Assert.*'). These methods test a particular condition and fail the test if it does not validate (with a specific message, optionally).

    Example testcase class in your case (without the methods contents defined):

    import static org.junit.Assert.*;
    
    public class AdditionTests {
        @Test
        public void testSimpleAddition() { ... }
    
    
        @Test
        public void testPositiveNegativeAddition() { ... }
    
    
        @Test
        public void testNegativePositiveAddition() { ... }
    
    
        @Test
        public void testNegativeAddition() { ... }
    
    
        @Test
        public void testOverflow() { ... }
    }
    

    If you are not used to writing unit tests but instead test your code by writing ad-hoc tests that you then validate "visually" (for example, you write a simple main method that accepts arguments entered using the keyboard and then prints out the results - and then you keep entering values and validating yourself if the results are correct), then you can start by writing such tests in the format above and validating the results with the correct assertXXX method instead of doing it manually. This way, you can re-run the test much easier then if you had to do manual tests.

    Convert List into Comma-Separated String

    Using String.Join

    string.Join<string>(",", lst );
    

    Using Linq Aggregation

    lst .Aggregate((a, x) => a + "," + x);
    

    ssh_exchange_identification: Connection closed by remote host under Git bash

    Got the same error too when connecting to GitHub with ssh as I move from one workplace to another. according to my situation, it seems that dns servers of different networks may get various ip address of github and the known_hosts file not identify it when changes happened. So change dns or switch back original network may work.

    Password must have at least one non-alpha character

    Run it through a fairly simple regex: [^a-zA-Z]

    And then check it's length separately:

    if(string.Length > 7)
    

    How to read response headers in angularjs?

    According the MDN custom headers are not exposed by default. The server admin need to expose them using "Access-Control-Expose-Headers" in the same fashion they deal with "access-control-allow-origin"

    See this MDN link for confirmation [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers]

    What's the difference between process.cwd() vs __dirname?

    $ find proj

    proj
    proj/src
    proj/src/index.js
    

    $ cat proj/src/index.js

    console.log("process.cwd() = " + process.cwd());
    console.log("__dirname = " + __dirname);
    

    $ cd proj; node src/index.js

    process.cwd() = /tmp/proj
    __dirname = /tmp/proj/src
    

    How does #include <bits/stdc++.h> work in C++?

    Unfortunately that approach is not portable C++ (so far).

    All standard names are in namespace std and moreover you cannot know which names are NOT defined by including and header (in other words it's perfectly legal for an implementation to declare the name std::string directly or indirectly when using #include <vector>).

    Despite this however you are required by the language to know and tell the compiler which standard header includes which part of the standard library. This is a source of portability bugs because if you forget for example #include <map> but use std::map it's possible that the program compiles anyway silently and without warnings on a specific version of a specific compiler, and you may get errors only later when porting to another compiler or version.

    In my opinion there are no valid technical excuses because this is necessary for the general user: the compiler binary could have all standard namespace built in and this could actually increase the performance even more than precompiled headers (e.g. using perfect hashing for lookups, removing standard headers parsing or loading/demarshalling and so on).

    The use of standard headers simplifies the life of who builds compilers or standard libraries and that's all. It's not something to help users.

    However this is the way the language is defined and you need to know which header defines which names so plan for some extra neurons to be burnt in pointless configurations to remember that (or try to find and IDE that automatically adds the standard headers you use and removes the ones you don't... a reasonable alternative).

    Using ping in c#

    Imports System.Net.NetworkInformation
    
    
    Public Function PingHost(ByVal nameOrAddress As String) As Boolean
        Dim pingable As Boolean = False
        Dim pinger As Ping
        Dim lPingReply As PingReply
    
        Try
            pinger = New Ping()
            lPingReply = pinger.Send(nameOrAddress)
            MessageBox.Show(lPingReply.Status)
            If lPingReply.Status = IPStatus.Success Then
    
                pingable = True
            Else
                pingable = False
            End If
    
    
        Catch PingException As Exception
            pingable = False
        End Try
        Return pingable
    End Function
    

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

    In Windows: Right click on "Git Bash" icon -> Run as Administrator. it helped me.

    Git tries to create a config file on disk C:/ but it has no permission to do that.

    APR based Apache Tomcat Native library was not found on the java.library.path?

    I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.

    What are Covering Indexes and Covered Queries in SQL Server?

    Here's an article in devx.com that says:

    Creating a non-clustered index that contains all the columns used in a SQL query, a technique called index covering

    I can only suppose that a covered query is a query that has an index that covers all the columns in its returned recordset. One caveat - the index and query would have to be built as to allow the SQL server to actually infer from the query that the index is useful.

    For example, a join of a table on itself might not benefit from such an index (depending on the intelligence of the SQL query execution planner):

    PersonID ParentID Name
    1        NULL     Abe
    2        NULL     Bob
    3        1        Carl
    4        2        Dave
    

    Let's assume there's an index on PersonID,ParentID,Name - this would be a covering index for a query like:

    SELECT PersonID, ParentID, Name FROM MyTable
    

    But a query like this:

    SELECT PersonID, Name FROM MyTable LEFT JOIN MyTable T ON T.PersonID=MyTable.ParentID
    

    Probably wouldn't benifit so much, even though all of the columns are in the index. Why? Because you're not really telling it that you want to use the triple index of PersonID,ParentID,Name.

    Instead, you're building a condition based on two columns - PersonID and ParentID (which leaves out Name) and then you're asking for all the records, with the columns PersonID, Name. Actually, depending on implementation, the index might help the latter part. But for the first part, you're better off having other indexes.

    Removing all line breaks and adding them after certain text

    I have achieved this with following
    Edit > Blank Operations > Remove Unnecessary Blank and EOL

    Rails: FATAL - Peer authentication failed for user (PG::Error)

    If you installed postresql on your server then just host: localhost to database.yml, I usually throw it in around where it says pool: 5. Otherwise if it's not localhost definitely tell that app where to find its database.

    development:
      adapter: postgresql
      encoding: unicode
      database: kickrstack_development
      host: localhost
      pool: 5
      username: kickrstack
      password: secret
    

    Make sure your user credentials are set correctly by creating a database and assigning ownership to your app's user to establish the connection. To create a new user in postgresql 9 run:

    sudo -u postgres psql
    

    set the postgresql user password if you haven't, it's just backslash password.

    postgres=# \password
    

    Create a new user and password and the user's new database:

    postgres=# create user "guy_on_stackoverflow" with password 'keepitonthedl';
    postgres=# create database "dcaclab_development" owner "guy_on_stackoverflow"; 
    

    Now update your database.yml file after you've confirmed creating the database, user, password and set these privileges. Don't forget host: localhost.

    Optional query string parameters in ASP.NET Web API

    Default values cannot be supplied for parameters that are not declared 'optional'

     Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)
    

    In your WebApiConfig

     config.Routes.MapHttpRoute( _
              name:="books", _
              routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
              defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
          )
    

    How to close a thread from within?

    How about sys.exit() from the module sys.

    If sys.exit() is executed from within a thread it will close that thread only.

    This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?

    Git Commit Messages: 50/72 Formatting

    Separation of presentation and data drives my commit messages here.

    Your commit message should not be hard-wrapped at any character count and instead line breaks should be used to separate thoughts, paragraphs, etc. as part of the data, not the presentation. In this case, the "data" is the message you are trying to get across and the "presentation" is how the user sees that.

    I use a single summary line at the top and I try to keep it short but I don't limit myself to an arbitrary number. It would be far better if Git actually provided a way to store summary messages as a separate entity from the message but since it doesn't I have to hack one in and I use the first line break as the delimiter (luckily, many tools support this means of breaking apart the data).

    For the message itself newlines indicate something meaningful in the data. A single newline indicates a start/break in a list and a double newline indicates a new thought/idea.

    This is a summary line, try to keep it short and end with a line break.
    This is a thought, perhaps an explanation of what I have done in human readable format.  It may be complex and long consisting of several sentences that describe my work in essay format.  It is not up to me to decide now (at author time) how the user is going to consume this data.
    
    Two line breaks separate these two thoughts.  The user may be reading this on a phone or a wide screen monitor.  Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across?  It is a truly painful experience.  Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph.  Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.
    
    Just as an example, here is a list of points:
    * Point 1.
    * Point 2.
    * Point 3.
    

    Here's what it looks like in a viewer that soft wraps the text.

    This is a summary line, try to keep it short and end with a line break.

    This is a thought, perhaps an explanation of what I have done in human readable format. It may be complex and long consisting of several sentences that describe my work in essay format. It is not up to me to decide now (at author time) how the user is going to consume this data.

    Two line breaks separate these two thoughts. The user may be reading this on a phone or a wide screen monitor. Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across? It is a truly painful experience. Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph. Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

    Just as an example, here is a list of points:
    * Point 1.
    * Point 2.
    * Point 3.

    My suspicion is that the author of Git commit message recommendation you linked has never written software that will be consumed by a wide array of end-users on different devices before (i.e., a website) since at this point in the evolution of software/computing it is well known that storing your data with hard-coded presentation information is a bad idea as far as user experience goes.

    React Native Responsive Font Size

    Take a look at the library I wrote: https://github.com/tachyons-css/react-native-style-tachyons

    It allows you to specify a root-fontSize (rem) upon start, which you can make dependent of your PixelRatio or other device-characteristics.

    Then you get styles relative to your rem, not only fontSize, but paddings etc. as well:

    <Text style={[s.f5, s.pa2, s.tc]}>
         Something
    </Text>
    

    Expanation:

    • f5is always your base-fontsize
    • pa2 gives you padding relative to your base-fontsize.

    Why does Node.js' fs.readFile() return a buffer instead of string?

    The data variable contains a Buffer object. Convert it into ASCII encoding using the following syntax:

    data.toString('ascii', 0, data.length)
    

    Asynchronously:

    fs.readFile('test.txt', 'utf8', function (error, data) {
        if (error) throw error;
        console.log(data.toString());
    });
    

    Deserializing JSON data to C# using JSON.NET

    You can try checking some of the class generators online for further information. However, I believe some of the answers have been useful. Here's my approach that may be useful.

    The following code was made with a dynamic method in mind.

    dynObj = (JArray) JsonConvert.DeserializeObject(nvm);
    
    foreach(JObject item in dynObj) {
     foreach(JObject trend in item["trends"]) {
      Console.WriteLine("{0}-{1}-{2}", trend["query"], trend["name"], trend["url"]);
     }
    }
    

    This code basically allows you to access members contained in the Json string. Just a different way without the need of the classes. query, trend and url are the objects contained in the Json string.

    You can also use this website. Don't trust the classes a 100% but you get the idea.

    Check if one date is between two dates

    I did the same thing that @Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone

    e.g (the same code to example with array of dates)

    _x000D_
    _x000D_
    var dateFrom = "02/06/2013";_x000D_
    var dateTo = "02/09/2013";_x000D_
    _x000D_
    var d1 = dateFrom.split("/");_x000D_
    var d2 = dateTo.split("/");_x000D_
    _x000D_
    var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11_x000D_
    var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]); _x000D_
    _x000D_
    _x000D_
    _x000D_
    var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];_x000D_
    _x000D_
    dates.forEach(element => {_x000D_
       let parts = element.split("/");_x000D_
       let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);_x000D_
            if (date >= from && date < to) {_x000D_
               console.log('dates in range', date);_x000D_
            }_x000D_
    })
    _x000D_
    _x000D_
    _x000D_

    how to change directory using Windows command line

    cd /driveName driveName:\pathNamw
    

    Get the selected value in a dropdown using jQuery.

    $("#availability option:selected").text();
    

    This will give you the text value of your dropdown list. You can also use .val() instead of .text() depending on what you're looking to get. Follow the link to the jQuery documentation and examples.

    calculating execution time in c++

    With C++11 for measuring the execution time of a piece of code, we can use the now() function:

    auto start = chrono::steady_clock::now();
    
    //  Insert the code that will be timed
    
    auto end = chrono::steady_clock::now();
    
    // Store the time difference between start and end
    auto diff = end - start;
    

    If you want to print the time difference between start and end in the above code, you could use:

    cout << chrono::duration <double, milli> (diff).count() << " ms" << endl;
    

    If you prefer to use nanoseconds, you will use:

    cout << chrono::duration <double, nano> (diff).count() << " ns" << endl;
    

    The value of the diff variable can be also truncated to an integer value, for example, if you want the result expressed as:

    diff_sec = chrono::duration_cast<chrono::nanoseconds>(diff);
    cout << diff_sec.count() << endl;
    

    For more info click here

    How can we draw a vertical line in the webpage?

    <hr> is not from struts. It is just an HTML tag.

    So, take a look here: http://www.microbion.co.uk/web/vertline.htm This link will give you a couple of tips.

    How to set URL query params in Vue with Vue-Router

    To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this points to vue component):

        setQuery(query){
            let obj = Object.assign({}, this.$route.query);
    
            Object.keys(query).forEach(key => {
                let value = query[key];
                if(value){
                    obj[key] = value
                } else {
                    delete obj[key]
                }
            })
            this.$router.replace({
                ...this.$router.currentRoute,
                query: obj
            })
        },
    
        removeQuery(queryNameArray){
            let obj = {}
            queryNameArray.forEach(key => {
                obj[key] = null
            })
            this.setQuery(obj)
        },
    

    How to move screen without moving cursor in Vim?

    To leave the cursor in the same column when you use Ctrl+D, Ctrl+F, Ctrl+B, Ctrl+U, G, H, M, L, gg

    you should define the following option:

    :set nostartofline
    

    Facebook Open Graph not clearing cache

    One thing to add, the url is case sensitive. Note that:

    apps.facebook.com/HELLO

    is different in the linter's eyes then

    apps.facebook.com/hello

    Be sure to use the exact site url that was entered in the developer settings for the app. The linter will return the properties otherwise but will not refresh the cache.

    How to move files from one git repo to another (not a clone), preserving history

    The below method to migrate my GIT Stash to GitLab by maintaining all branches and preserving history.

    Clone the old repository to local.

    git clone --bare <STASH-URL>
    

    Create an empty repository in GitLab.

    git push --mirror <GitLab-URL>
    

    The above I performed when we migrated our code from stash to GitLab and it worked very well.

    How do you run a script on login in *nix?

    Launchd is a the preferred way in OS X.

    If you want it to run on your login put it in ~/Library/LaunchAgents

    Start launchd item

    launchctl load /Library/LaunchDaemons/com.bob.plist
    

    Stop item

    launchctl unload /Library/LaunchDaemons/com.bob.plist
    

    Example com.bob.plist

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    <key>Label</key>
    <string>com.bob</string>
    <key>RunAtLoad</key>
    <true/>
    <key>ProgramArguments</key>
    <array>
    <string>/usr/bin/java</string>
    <string>-jar</string>
    <string>/Users/user/program.jar</string>
    </array>
    </dict>
    </plist>
    

    Uncaught ReferenceError: jQuery is not defined

    jQuery needs to be the first script you import. The first script on your page

    <script type="text/javascript" src="/test/wp-content/themes/child/script/jquery.jcarousel.min.js"></script>
    

    appears to be a jQuery plugin, which is likely generating an error since jQuery hasn't been loaded on the page yet.

    PackagesNotFoundError: The following packages are not available from current channels:

    Try adding the conda-forge channel to your list of channels with this command:
    conda config --append channels conda-forge. It tells conda to also look on the conda-forge channel when you search for packages. You can then simply install the two packages with conda install slycot control.

    Channels are basically servers for people to host packages on and the community-driven conda-forge is usually a good place to start when packages are not available via the standard channels. I checked and both slycot and control seem to be available there.

    Keep values selected after form submission

    If you are using WordPress (as is the case with the OP), you can use the selected function.

    <form method="get" action="">
      <select name="name">
        <option value="a" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'a' ); ?>>a</option>
        <option value="b" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'b' ); ?>>b</option>
      </select>
      <select name="location">
        <option value="x" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'x' ); ?>>x</option>
        <option value="y" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'y' ); ?>>y</option>
      </select>
      <input type="submit" value="Submit" class="submit" />
    </form>
    

    check if a number already exist in a list in python

    If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.

    s = set()
    if number1 not in s:
      s.add(number1)
    if number2 not in s:
      s.add(number2)
    ...
    s = sorted(s)  #Now a list in ascending order
    

    Options for initializing a string array

    You have several options:

    string[] items = { "Item1", "Item2", "Item3", "Item4" };
    
    string[] items = new string[]
    {
      "Item1", "Item2", "Item3", "Item4"
    };
    
    string[] items = new string[10];
    items[0] = "Item1";
    items[1] = "Item2"; // ...
    

    Default interface methods are only supported starting with Android N

    This also happened to me but using Dynamic Features. I already had Java 8 compatibility enabled in the app module but I had to add this compatibility lines to the Dynamic Feature module and then it worked.

    How do I compile a .c file on my Mac?

    Ondrasej is the "most right" here, IMO.
    There are also gui-er ways to do it, without resorting to Xcode. I like TryC.

    Mac OS X includes Developer Tools, a developing environment for making Macintosh applications. However, if someone wants to study programming using C, Xcode is too big and too complicated for beginners, to write a small sample program. TryC is very suitable for beginners.

    enter image description here

    You don't need to launch a huge Xcode application, or type unfamiliar commands in Terminal. Using TryC, you can write, compile and run a C, C++ and Ruby program just like TextEdit. It's only available to compile one source code file but it's enough for trying sample programs.

    HTML "overlay" which allows clicks to fall through to elements behind it

    For the record an alternative approach might be to make the clickable layer the overlay: you make it semi-transparent and then place the "overlay" image behind it (somewhat counterintuitively, the "overlay" image could then be opaque). Depending on what you're trying to do, you might well be able to get the exact same visual effect (of an image and a clickable layer semi-transparently superimposed on top of each other), while avoiding clickability problems (because the "overlay" is in fact in the background).

    How can I add some small utility functions to my AngularJS application?

    Do I understand correctly that you just want to define some utility methods and make them available in templates?

    You don't have to add them to every controller. Just define a single controller for all the utility methods and attach that controller to <html> or <body> (using the ngController directive). Any other controllers you attach anywhere under <html> (meaning anywhere, period) or <body> (anywhere but <head>) will inherit that $scope and will have access to those methods.

    Is there a difference between using a dict literal and a dict constructor?

    Also consider the fact that tokens that match for operators can't be used in the constructor syntax, i.e. dasherized keys.

    >>> dict(foo-bar=1)
    File "<stdin>", line 1
    SyntaxError: keyword can't be an expression
    
    >>> {'foo-bar': 1}
    {'foo-bar': 1}
    

    C# : Passing a Generic Object

    You cannot access var with the generic.

    Try something like

    Console.WriteLine("Generic : {0}", test);
    

    And override ToString method [1]

    [1] http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

    DropDownList's SelectedIndexChanged event not firing

    try setting AutoPostBack="True" on the DropDownList.

    Write to rails console

    In addition to already suggested p and puts — well, actually in most cases you do can write logger.info "blah" just as you suggested yourself. It works in console too, not only in server mode.

    But if all you want is console debugging, puts and p are much shorter to write, anyway.

    Submit HTML form, perform javascript function (alert then redirect)

    Looks like your form is submitting which is the default behaviour, you can stop it with this:

    <form action="" method="post" onsubmit="completeAndRedirect();return false;">
    

    RegEx to parse or validate Base64 data

    From the RFC 4648:

    Base encoding of data is used in many situations to store or transfer data in environments that, perhaps for legacy reasons, are restricted to US-ASCII data.

    So it depends on the purpose of usage of the encoded data if the data should be considered as dangerous.

    But if you’re just looking for a regular expression to match Base64 encoded words, you can use the following:

    ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
    

    Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

    Due to PermGen removal some options were removed (like -XX:MaxPermSize), but options -Xms and -Xmx work in Java 8. It's possible that under Java 8 your application simply needs somewhat more memory. Try to increase -Xmx value. Alternatively you can try to switch to G1 garbage collector using -XX:+UseG1GC.

    Note that if you use any option which was removed in Java 8, you will see a warning upon application start:

    $ java -XX:MaxPermSize=128M -version
    Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128M; support was removed in 8.0
    java version "1.8.0_25"
    Java(TM) SE Runtime Environment (build 1.8.0_25-b18)
    Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
    

    Chrome not rendering SVG referenced via <img> tag

    I had a similar problem and the existing answers to this either weren't applicable, or worked but we couldn't use them for other reasons. So I had to figure out what Chrome disliked about our SVGs.

    In our case in turned out to be that the id attribute of the symbol tag in the SVG file had a : in it, which Chrome didn't like. Soon as I removed the : it worked fine.

    Bad:

    <svg
        xmlns="http://www.w3.org/2000/svg"
        xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 72 72">
        <defs>
            <symbol id="ThisIDHasAColon:AndChromeDoesNotLikeIt">
            ...
            </symbol>
        </defs>
        <use
            ....
            xlink:href="#ThisIDHasAColon:AndChromeDoesNotLikeIt"
        />
    </svg>
    

    Good:

    <svg
        xmlns="http://www.w3.org/2000/svg"
        xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 72 72">
        <defs>
            <symbol id="NoMoreColon">
            ...
            </symbol>
        </defs>
        <use
            ....
            xlink:href="#NoMoreColon"
        />
    </svg>
    

    How can I convert a series of images to a PDF from the command line on linux?

    Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

    What's the difference between ISO 8601 and RFC 3339 Date Formats?

    RFC 3339 is mostly a profile of ISO 8601, but is actually inconsistent with it in borrowing the "-00:00" timezone specification from RFC 2822. This is described in the Wikipedia article.

    Python regex to match dates

    I find the below RE working fine for Date in the following format;

    1. 14-11-2017
    2. 14.11.2017
    3. 14|11|2017

    It can accept year from 2000-2099

    Please do not forget to add $ at the end,if not it accept 14-11-201 or 20177

    date="13-11-2017"
    
    x=re.search("^([1-9] |1[0-9]| 2[0-9]|3[0-1])(.|-)([1-9] |1[0-2])(.|-|)20[0-9][0-9]$",date)
    
    x.group()
    

    output = '13-11-2017'

    Error in if/while (condition) {: missing Value where TRUE/FALSE needed

    The evaluation of condition resulted in an NA. The if conditional must have either a TRUE or FALSE result.

    if (NA) {}
    ## Error in if (NA) { : missing value where TRUE/FALSE needed
    

    This can happen accidentally as the results of calculations:

    if(TRUE && sqrt(-1)) {}
    ## Error in if (TRUE && sqrt(-1)) { : missing value where TRUE/FALSE needed
    

    To test whether an object is missing use is.na(x) rather than x == NA.


    See also the related errors:

    Error in if/while (condition) { : argument is of length zero

    Error in if/while (condition) : argument is not interpretable as logical

    if (NULL) {}
    ## Error in if (NULL) { : argument is of length zero
    
    if ("not logical") {}
    ## Error: argument is not interpretable as logical
    
    if (c(TRUE, FALSE)) {}
    ## Warning message:
    ## the condition has length > 1 and only the first element will be used
    

    How can I get Apache gzip compression to work?

    In my case append only this line worked

    SetOutputFilter DEFLATE

    I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

    You should install python 3.6 version because python 3.7 version doesn't support pyaudio 1 step : Then download the .whl file
    according to your python version and the configuration of your machine in your python folder which is newly installed. For me it is python 3.6 and 64 bit machine. Download the file from here (https://www.lfd.uci.edu/~gohlke/pythonlibs/) 2 step : run your cmd and type " pip install your downloaded file name here "

    What parameters should I use in a Google Maps URL to go to a lat-lon?

    yeah I had the same question for a long time and I found the perfect one. here are some parameters from it.

    https://maps.google.com?parameter = value
    



    q=

    is used to specify the search query in Google maps search.
    eg :

    https://maps.google.com?q=newyork or
    https://maps.google.com?q=51.03841,-114.01679
    

    near=

    is used to specify the location alternative to q=. Also has the added effect of allowing you to increase the AddressDetails Accuracy value by being more precise. Mostly only useful if query is a business or suchlike.

    z=

    Zoom level. Can be set 19 normally, but in certain cases can go up to 23.

    ll=

    Latitude and longitude of the map centre point. Must be in that order. Requires decimal format. Interestingly, you can use this without q, in which case it doesn’t show a marker.

    sll=

    Similar to ll, only this sets the lat/long of the centre point for a business search. Requires the same input criteria as ll.

    t=

    Sets the kind of map shown. Can be set to:

    m – normal  map,
    k – satellite,
    h – hybrid,
    p – terrain
    

    saddr=

    Sets the starting point for directions searches. You can also add text into this in brackets to bold it in the directions sidebar.

    daddr=

    Sets the end point for directions searches, and again will bold any text added in brackets.You can also add "+to:" which will set via points. These can be added multiple times.

    via=

    Allows you to insert via points in directions. Must be in CSV format. For example, via=1,5 addresses 1 and 5 will be via points without entries in the sidebar. The start point (which is set as 0), and 2, 3 and 4 will all show full addresses.

    doflg=

    Changes the units used to measure distance (will default to the standard unit in country of origin). Change to ptk for metric or ptm for imperial.

    msa=

    Does stuff with My Maps. Set to 0 show defined My Maps, b to turn the My Maps sidebar on, 1 to show the My Maps tab on its own, or 2 to go to the new My Map creator form.

    dirflg=

    can set miscellaneous values below:

    h - Avoid highway
    t - Avoid tolls
    

    reference http://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

    How to open my files in data_folder with pandas using relative path?

    With python or pandas when you use read_csv or pd.read_csv, both of them look into current working directory, by default where the python process have started. So you need to use os module to chdir() and take it from there.

    import pandas as pd 
    import os
    print(os.getcwd())
    os.chdir("D:/01Coding/Python/data_sets/myowndata")
    print(os.getcwd())
    df = pd.read_csv('data.csv',nrows=10)
    print(df.head())
    

    How to sort a list of strings numerically?

    You could pass a function to the key parameter to the .sort method. With this, the system will sort by key(x) instead of x.

    list1.sort(key=int)
    

    BTW, to convert the list to integers permanently, use the map function

    list1 = list(map(int, list1))   # you don't need to call list() in Python 2.x
    

    or list comprehension

    list1 = [int(x) for x in list1]
    

    Using moment.js to convert date to string "MM/dd/yyyy"

    Try this:

    var momentObj = $("#start_ts").datepicker("getDate");
    
    var yourDate = momentObj.format('L');
    

    Difference Between Cohesion and Coupling

    Cohesion is an indication of how related and focused the responsibilities of an software element are.

    Coupling refers to how strongly a software element is connected to other elements.

    The software element could be class, package, component, subsystem or a system. And while designing the systems it is recommended to have software elements that have High cohesion and support Low coupling.

    Low cohesion results in monolithic classes that are difficult to maintain, understand and reduces re-usablity. Similarly High Coupling results in classes that are tightly coupled and changes tend not be non-local, difficult to change and reduces the reuse.

    We can take a hypothetical scenario where we are designing an typical monitor-able ConnectionPool with the following requirements. Note that, it might look too much for a simple class like ConnectionPool but the basic intent is just to demonstrate low coupling and high cohesion with some simple example and I think should help.

    1. support getting a connection
    2. release a connection
    3. get stats about connection vs usage count
    4. get stats about connection vs time
    5. Store the connection retrieval and release information to a database for reporting later.

    With low cohesion we could design a ConnectionPool class by forcefully stuffing all this functionality/responsibilities into a single class as below. We can see that this single class is responsible for connection management, interacting with database as well maintaining connection stats.

    Low Cohesion Connection Pool

    With high cohesion we can assign these responsibility across the classes and make it more maintainable and reusable.

    High Cohesion Connection Pool

    To demonstrate Low coupling we will continue with the high cohesion ConnectionPool diagram above. If we look at the above diagram although it supports high cohesion, the ConnectionPool is tightly coupled with ConnectionStatistics class and PersistentStore it interacts with them directly. Instead to reduce the coupling we could introduce a ConnectionListener interface and let these two classes implement the interface and let them register with ConnectionPool class. And the ConnectionPool will iterate through these listeners and notify them of connection get and release events and allows less coupling.

    Low Coupling ConnectionPool

    Note/Word or Caution: For this simple scenario it may look like an overkill but if we imagine a real-time scenario where our application needs to interact with multiple third party services to complete a transaction: Directly coupling our code with the third party services would mean that any changes in the third party service could result in changes to our code at multiple places, instead we could have Facade that interacts with these multiple services internally and any changes to the services become local to the Facade and enforce low coupling with the third party services.

    List directory in Go

    We can get a list of files inside a folder on the file system using various golang standard library functions.

    1. filepath.Walk
    2. ioutil.ReadDir
    3. os.File.Readdir
    
    package main
    
    import (
        "fmt"
        "io/ioutil"
        "log"
        "os"
        "path/filepath"
    )
    
    func main() {
        var (
            root  string
            files []string
            err   error
        )
    
        root := "/home/manigandan/golang/samples"
        // filepath.Walk
        files, err = FilePathWalkDir(root)
        if err != nil {
            panic(err)
        }
        // ioutil.ReadDir
        files, err = IOReadDir(root)
        if err != nil {
            panic(err)
        }
        //os.File.Readdir
        files, err = OSReadDir(root)
        if err != nil {
            panic(err)
        }
    
        for _, file := range files {
            fmt.Println(file)
        }
    }
    
    1. Using filepath.Walk

    The path/filepath package provides a handy way to scan all the files in a directory, it will automatically scan each sub-directories in the directory.

    func FilePathWalkDir(root string) ([]string, error) {
        var files []string
        err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
            if !info.IsDir() {
                files = append(files, path)
            }
            return nil
        })
        return files, err
    }
    
    1. Using ioutil.ReadDir

    ioutil.ReadDir reads the directory named by dirname and returns a list of directory entries sorted by filename.

    func IOReadDir(root string) ([]string, error) {
        var files []string
        fileInfo, err := ioutil.ReadDir(root)
        if err != nil {
            return files, err
        }
    
        for _, file := range fileInfo {
            files = append(files, file.Name())
        }
        return files, nil
    }
    
    1. Using os.File.Readdir

    Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.

    func OSReadDir(root string) ([]string, error) {
        var files []string
        f, err := os.Open(root)
        if err != nil {
            return files, err
        }
        fileInfo, err := f.Readdir(-1)
        f.Close()
        if err != nil {
            return files, err
        }
    
        for _, file := range fileInfo {
            files = append(files, file.Name())
        }
        return files, nil
    }
    

    Benchmark results.

    benchmark score

    Get more details on this Blog Post

    Any way to limit border length?

    Another way of doing this is using border-image in combination with a linear-gradient.

    _x000D_
    _x000D_
    div {_x000D_
      width: 100px;_x000D_
      height: 75px;_x000D_
      background-color: green;_x000D_
      background-clip: content-box; /* so that the background color is not below the border */_x000D_
      _x000D_
      border-left: 5px solid black;_x000D_
      border-image: linear-gradient(to top, #000 50%, rgba(0,0,0,0) 50%); /* to top - at 50% transparent */_x000D_
      border-image-slice: 1;_x000D_
    }
    _x000D_
    <div></div>
    _x000D_
    _x000D_
    _x000D_

    jsfiddle: https://jsfiddle.net/u7zq0amc/1/


    Browser Support: IE: 11+

    Chrome: all

    Firefox: 15+

    For a better support also add vendor prefixes.

    caniuse border-image

    How to import jquery using ES6 syntax?

    webpack users, add the below to your plugins array.

    let plugins = [
      // expose $ and jQuery to global scope.
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
      })
    ];
    

    Compare two Timestamp in java

    java.util.Date mytime = null;
    if (mytime.after(now) && mytime.before(last_download_time) )
    

    Worked for me

    IntelliJ: Error:java: error: release version 5 not supported

    I've done most things you are proposing with Java compiler and bytecode and solved the problem in the past. It's been almost 1 month since I ran my Java code (and back then everything was fixed), but now the problem appeared again. Don't know why, pretty annoyed though!

    This time the solution was: Right click to project name -> Open module settings F4 -> Language level ...and there you can define the language level your project/pc is.

    No maven/pom configuration worked for me both in the past and now and I've already set the Java compiler and bytecode at 12.

    Strip out HTML and Special Characters

    Probably better here for a regex replace

    // Strip HTML Tags
    $clear = strip_tags($des);
    // Clean up things like &amp;
    $clear = html_entity_decode($clear);
    // Strip out any url-encoded stuff
    $clear = urldecode($clear);
    // Replace non-AlNum characters with space
    $clear = preg_replace('/[^A-Za-z0-9]/', ' ', $clear);
    // Replace Multiple spaces with single space
    $clear = preg_replace('/ +/', ' ', $clear);
    // Trim the string of leading/trailing space
    $clear = trim($clear);
    

    Or, in one go

    $clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($des))))));
    

    How do I write outputs to the Log in Android?

    Recently I found this approach to writing logs in android, which I think is super awesome.

    public static final boolean FORCED_LOGGING = true;
    private static final int CALLER_STACK_INDEX = 3;
    
    public static void showLogs(String message) {
            if (FORCED_LOGGING) {
                StackTraceElement caller = Thread.currentThread().getStackTrace()[CALLER_STACK_INDEX];
    
                String fullClassName = caller.getClassName();
                String className = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
                String methodName = caller.getMethodName();
                int lineNumber = caller.getLineNumber();
    
                Log.i("*** " + className + "." + methodName + "():" + lineNumber + "\n" , message);
            }
        }
    

    How to check if the docker engine and a docker container are running?

    on a Mac you might see the image:

    enter image description here

    if you right click on the docker icon then you see:

    enter image description here

    alternatively:

    docker ps

    and

    docker run hello-world

    How do I recognize "#VALUE!" in Excel spreadsheets?

    This will return TRUE for #VALUE! errors (ERROR.TYPE = 3) and FALSE for anything else.

    =IF(ISERROR(A1),ERROR.TYPE(A1)=3)
    

    Mod of negative number is melting my brain

    ShreevatsaR's answer won't work for all cases, even if you add "if(m<0) m=-m;", if you account for negative dividends/divisors.

    For example, -12 mod -10 will be 8, and it should be -2.

    The following implementation will work for both positive and negative dividends / divisors and complies with other implementations (namely, Java, Python, Ruby, Scala, Scheme, Javascript and Google's Calculator):

    internal static class IntExtensions
    {
        internal static int Mod(this int a, int n)
        {
            if (n == 0)
                throw new ArgumentOutOfRangeException("n", "(a mod 0) is undefined.");
    
            //puts a in the [-n+1, n-1] range using the remainder operator
            int remainder = a%n;
    
            //if the remainder is less than zero, add n to put it in the [0, n-1] range if n is positive
            //if the remainder is greater than zero, add n to put it in the [n-1, 0] range if n is negative
            if ((n > 0 && remainder < 0) ||
                (n < 0 && remainder > 0))
                return remainder + n;
            return remainder;
        }
    }
    

    Test suite using xUnit:

        [Theory]
        [PropertyData("GetTestData")]
        public void Mod_ReturnsCorrectModulo(int dividend, int divisor, int expectedMod)
        {
            Assert.Equal(expectedMod, dividend.Mod(divisor));
        }
    
        [Fact]
        public void Mod_ThrowsException_IfDivisorIsZero()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => 1.Mod(0));
        }
    
        public static IEnumerable<object[]> GetTestData
        {
            get
            {
                yield return new object[] {1, 1, 0};
                yield return new object[] {0, 1, 0};
                yield return new object[] {2, 10, 2};
                yield return new object[] {12, 10, 2};
                yield return new object[] {22, 10, 2};
                yield return new object[] {-2, 10, 8};
                yield return new object[] {-12, 10, 8};
                yield return new object[] {-22, 10, 8};
                yield return new object[] { 2, -10, -8 };
                yield return new object[] { 12, -10, -8 };
                yield return new object[] { 22, -10, -8 };
                yield return new object[] { -2, -10, -2 };
                yield return new object[] { -12, -10, -2 };
                yield return new object[] { -22, -10, -2 };
            }
        }
    

    Getting list of tables, and fields in each, in a database

    Your other inbuilt friend here is the system sproc SP_HELP.

    sample usage ::

    sp_help <MyTableName>
    

    It returns a lot more info than you will really need, but at least 90% of your possible requirements will be catered for.

    Creating a simple configuration file and parser in C++

    A naive approach could look like this:

    #include <map>
    #include <sstream>
    #include <stdexcept>
    #include <string>
    
    std::map<std::string, std::string> options; // global?
    
    void parse(std::istream & cfgfile)
    {
        for (std::string line; std::getline(cfgfile, line); )
        {
            std::istringstream iss(line);
            std::string id, eq, val;
    
            bool error = false;
    
            if (!(iss >> id))
            {
                error = true;
            }
            else if (id[0] == '#')
            {
                continue;
            }
            else if (!(iss >> eq >> val >> std::ws) || eq != "=" || iss.get() != EOF)
            {
                error = true;
            }
    
            if (error)
            {
                // do something appropriate: throw, skip, warn, etc.
            }
            else
            {
                options[id] = val;
            }
        }
    }
    

    Now you can access each option value from the global options map anywhere in your program. If you want castability, you could make the mapped type a boost::variant.

    Python: For each list element apply a function across the list

    >>> nums = [1, 2, 3, 4, 5]    
    >>> min(map((lambda t: ((float(t[0])/t[1]), t)), ((x, y) for x in nums for y in nums)))[1]
    (1, 5)
    

    Java - Check if input is a positive integer, negative integer, natural number and so on.

    What about using the following:

    int number = input.nextInt();
    if (number < 0) {
        // negative
    } else {
       // it's a positive
    }
    

    How To Make Circle Custom Progress Bar in Android

    A very useful lib for custom progress bar in android.

    In your layout file

    <com.lylc.widget.circularprogressbar.example.CircularProgressBar
    android:id="@+id/mycustom_progressbar"
    .
    .
    .
     />
    

    and Java file

    CircularProgressBar progressBar = (CircularProgressBar) findViewById(R.id.mycustom_progressbar);
    progressBar.setTitle("Circular Progress Bar");
    

    Disabling swap files creation in vim

    If you are using git, you can add *.swp to .gitignore.

    How to get error message when ifstream open fails

    Following on @Arne Mertz's answer, as of C++11 std::ios_base::failure inherits from system_error (see http://www.cplusplus.com/reference/ios/ios_base/failure/), which contains both the error code and message that strerror(errno) would return.

    std::ifstream f;
    
    // Set exceptions to be thrown on failure
    f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    
    try {
        f.open(fileName);
    } catch (std::system_error& e) {
        std::cerr << e.code().message() << std::endl;
    }
    

    This prints No such file or directory. if fileName doesn't exist.

    Flexbox not giving equal width to elements

    To create elements with equal width using Flex, you should set to your's child (flex elements):

    flex-basis: 25%;
    flex-grow: 0;
    

    It will give to all elements in row 25% width. They will not grow and go one by one.

    Arithmetic overflow error converting numeric to data type numeric

    I feel I need to clarify one very important thing, for others (like my co-worker) who came across this thread and got the wrong information.

    The answer given ("Try decimal(9,2) or decimal(10,2) or whatever.") is correct, but the reason ("increase the number of digits before the decimal") is wrong.

    decimal(p,s) and numeric(p,s) both specify a Precision and a Scale. The "precision" is not the number of digits to the left of the decimal, but instead is the total precision of the number.

    For example: decimal(2,1) covers 0.0 to 9.9, because the precision is 2 digits (00 to 99) and the scale is 1. decimal(4,1) covers 000.0 to 999.9 decimal(4,2) covers 00.00 to 99.99 decimal(4,3) covers 0.000 to 9.999

    How to connect to MySQL Database?

    you can use Package Manager to add it as package and it is the easiest way to do. You don't need anything else to work with mysql database.

    Or you can run below command in Package Manager Console

    PM> Install-Package MySql.Data
    

    NUGET Mysql.Data

    How to atomically delete keys matching a pattern using Redis

    I am using below command in redis 3.2.8

    redis-cli KEYS *YOUR_KEY_PREFIX* | xargs redis-cli DEL
    

    You can get more help related to keys pattern search from here :- https://redis.io/commands/keys. Use your convenient glob-style pattern as per your requirement like *YOUR_KEY_PREFIX* or YOUR_KEY_PREFIX?? or any other.

    And if any of you have integrated Redis PHP library than below function will help you.

    flushRedisMultipleHashKeyUsingPattern("*YOUR_KEY_PATTERN*"); //function call
    
    function flushRedisMultipleHashKeyUsingPattern($pattern='')
            {
                if($pattern==''){
                    return true;
                }
    
                $redisObj = $this->redis;
                $getHashes = $redisObj->keys($pattern);
                if(!empty($getHashes)){
                    $response = call_user_func_array(array(&$redisObj, 'del'), $getHashes); //setting all keys as parameter of "del" function. Using this we can achieve $redisObj->del("key1","key2);
                }
            }
    

    Thank you :)

    Where to put default parameter value in C++?

    Adding one more point. Function declarations with default argument should be ordered from right to left and from top to bottom.

    For example in the below function declaration if you change the declaration order then the compiler gives you a missing default parameter error. Reason the compiler allows you to separate the function declaration with default argument within the same scope but it should be in order from RIGHT to LEFT (default arguments) and from TOP to BOTTOM(order of function declaration default argument).

    //declaration
    void function(char const *msg, bool three, bool two, bool one = false);
    void function(char const *msg, bool three = true, bool two, bool one); // Error 
    void function(char const *msg, bool three, bool two = true, bool one); // OK
    //void function(char const *msg, bool three = true, bool two, bool one); // OK
    
    int main() {
        function("Using only one Default Argument", false, true);
        function("Using Two Default Arguments", false);
        function("Using Three Default Arguments");
        return 0;
    }
    
    //definition
    void function(char const *msg, bool three, bool two, bool one ) {
        std::cout<<msg<<" "<<three<<" "<<two<<" "<<one<<std::endl;
    }
    

    Django URL Redirect

    In Django 1.8, this is how I did mine.

    from django.views.generic.base import RedirectView
    
    url(r'^$', views.comingSoon, name='homepage'),
    # whatever urls you might have in here
    # make sure the 'catch-all' url is placed last
    url(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))
    

    Instead of using url, you can use the pattern_name, which is a bit un-DRY, and will ensure you change your url, you don't have to change the redirect too.

    Refresh certain row of UITableView based on Int in Swift

    How about:

    self.tableView.reloadRowsAtIndexPaths([NSIndexPath(rowNumber)], withRowAnimation: UITableViewRowAnimation.Top)
    

    What's the environment variable for the path to the desktop?

    you could also open a DOS command prompt and execute the set command.

    This will give you an idea what environment variables are available on your system.

    E.g. - since you where specifically asking for a non-english Windows - heres is an example of my own German Edition (Window7-64bit) :

    set > env.txt
    type env.txt
    
    ALLUSERSPROFILE=C:\ProgramData
    APPDATA=C:\Users\SOF\AppData\Roaming
    CommonProgramFiles=C:\Program Files\Common Files
    CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
    CommonProgramW6432=C:\Program Files\Common Files
    COMPUTERNAME=VMSOF
    ComSpec=C:\Windows\system32\cmd.exe
    FP_NO_HOST_CHECK=NO
    HOMEDRIVE=C:
    HOMEPATH=\Users\SOF
    LOCALAPPDATA=C:\Users\SOF\AppData\Local
    LOGONSERVER=\\VMSOF
    NUMBER_OF_PROCESSORS=2
    OS=Windows_NT
    Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files (x86)\CMake 2.8\bin;C:\Program Files (x86)\emacs-22.3\bin;C:\Program Files (x86)\GnuWin32\bin;
    PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
    PROCESSOR_ARCHITECTURE=AMD64
    PROCESSOR_IDENTIFIER=AMD64 Family 15 Model 67 Stepping 3, AuthenticAMD
    PROCESSOR_LEVEL=15
    PROCESSOR_REVISION=4303
    ProgramData=C:\ProgramData
    ProgramFiles=C:\Program Files
    ProgramFiles(x86)=C:\Program Files (x86)
    ProgramW6432=C:\Program Files
    PROMPT=$P$G
    PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
    PUBLIC=C:\Users\Public
    SESSIONNAME=Console
    SystemDrive=C:
    SystemRoot=C:\Windows
    TEMP=C:\Users\SOF\AppData\Local\Temp
    TMP=C:\Users\SOF\AppData\Local\Temp
    USERDOMAIN=VMSOF
    USERNAME=SOF
    USERPROFILE=C:\Users\SOF
    VBOX_INSTALL_PATH=C:\Program Files\Sun\VirtualBox\
    VS90COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\
    windir=C:\Windows
    
    

    How to check a string against null in java?

    This looks a bit strange, but...

    stringName == null || "".equals(stringName)
    

    Never had any issues doing it this way, plus it's a safer way to check while avoiding potential null point exceptions.

    How can I setup & run PhantomJS on Ubuntu?

    For Ubuntu, download the suitable file from http://phantomjs.org/download.html. CD to the downloaded folder. Then:

    sudo tar xvf phantomjs-1.9.0-linux-x86_64.tar.bz2
    sudo mv phantomjs-1.9.0-linux-x86_64 /usr/local/share/phantomjs
    sudo ln -s /usr/local/share/phantomjs/bin/phantomjs /usr/bin/phantomjs
    

    Make sure to replace the file name in these commands with the file you have downloaded.

    range() for floats

    I helped add the function numeric_range to the package more-itertools.

    more_itertools.numeric_range(start, stop, step) acts like the built in function range but can handle floats, Decimal, and Fraction types.

    >>> from more_itertools import numeric_range
    >>> tuple(numeric_range(.1, 5, 1))
    (0.1, 1.1, 2.1, 3.1, 4.1)
    

    Trigger change event <select> using jquery

    Use val() to change to the value (not the text) and trigger() to manually fire the event.

    The change event handler must be declared before the trigger.

    Here's a sample

    $('.check').change(function(){
      var data= $(this).val();
      alert(data);            
    });
    
    $('.check')
        .val('two')
        .trigger('change');
    

    phpmyadmin "no data received to import" error, how to fix?

    It’s a common error and it can be easily fixed. This error message is an indication of that the file you are trying to import is larger than your web host allows

    No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration. See FAQ 1.16.

    Solution:

    A solution is easy, Need to increase file size upload limit as per your requirement.

    First of all, stop the XAMPP/Wamp and then find the php.ini in the following locations. Windows: C:\xampp\php\php.ini

    Open the php.ini file. Find these lines in the php.ini file and replace it following numbers

    upload_max_filesize = 64M
    

    And then restart your XAMPP/Wamp


    NOTE: For Windows, you can find the file in the C:\xampp\php\php.ini-Folder (Windows) or in the etc-Folder (within the xampp-Folder)