Programs & Examples On #Isession

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

I had the same error by in SQL Server Management Studio.

I found that to look at the more specific error, look at the log file created by the SQL Server. When I opened the log file, I found this error

Could not connect because the maximum number of ’2' user connections has already been reached. The system administrator can use sp_configure to increase the maximum value. The connection has been closed

I spend quite some time figuring this out. Finally running the following code fixed my problem.

sp_configure 'show advanced options', 1;
go

reconfigure
go

sp_configure 'user connections', 0
go

reconfigure
go

More on here and here

Edit

To view logs search for "logs" on windows startup button, click "view events logs". From there go to Applications under "Windows Logs". You can also choose "System" logs to see system wise errors. You can use filter on current logs by clicking "Filter Current Logs" on right side and then select "Error checkbox".

NHibernate.MappingException: No persister for: XYZ

I had similar problem, and I solved it as folows:

I working on MS SQL 2008, but in the NH configuration I had bad dialect: NHibernate.Dialect.MsSql2005Dialect if I correct it to: NHibernate.Dialect.MsSql2008Dialect then everything's working fine without a exception "No persister for: ..." David.

Convert A String (like testing123) To Binary In Java

import java.lang.*;
import java.io.*;
class d2b
{
  public static void main(String args[]) throws IOException{
  BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the decimal value:");
  String h = b.readLine();
  int k = Integer.parseInt(h);  
  String out = Integer.toBinaryString(k);
  System.out.println("Binary: " + out);
  }
}   

How can I make the computer beep in C#?

Try this

Console.WriteLine("\a")

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

Adding my two cents, based on a performance issue I observed.

If simple queries are getting parellelized unnecessarily, it can bring more problems than solving one. However, before adding MAXDOP into the query as "knee-jerk" fix, there are some server settings to check.

In Jeremiah Peschka - Five SQL Server Settings to Change, MAXDOP and "COST THRESHOLD FOR PARALLELISM" (CTFP) are mentioned as important settings to check.

Note: Paul White mentioned max server memory aslo as a setting to check, in a response to Performance problem after migration from SQL Server 2005 to 2012. A good kb article to read is Using large amounts of memory can result in an inefficient plan in SQL Server

Jonathan Kehayias - Tuning ‘cost threshold for parallelism’ from the Plan Cache helps to find out good value for CTFP.

Why is cost threshold for parallelism ignored?

Aaron Bertrand - Six reasons you should be nervous about parallelism has a discussion about some scenario where MAXDOP is the solution.

Parallelism-Inhibiting Components are mentioned in Paul White - Forcing a Parallel Query Execution Plan

How to select all records from one table that do not exist in another table?

I don't have enough rep points to vote up froadie's answer. But I have to disagree with the comments on Kris's answer. The following answer:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT name 
     FROM table1)

Is FAR more efficient in practice. I don't know why, but I'm running it against 800k+ records and the difference is tremendous with the advantage given to the 2nd answer posted above. Just my $0.02.

What's the difference between an element and a node in XML?

Different W3C specifications define different sets of "Node" types.

Thus, the DOM spec defines the following types of nodes:

  • Document -- Element (maximum of one), ProcessingInstruction, Comment, DocumentType
  • DocumentFragment -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • DocumentType -- no children
  • EntityReference -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • Element -- Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
  • Attr -- Text, EntityReference
  • ProcessingInstruction -- no children
  • Comment -- no children
  • Text -- no children
  • CDATASection -- no children
  • Entity -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • Notation -- no children

The XML Infoset (used by XPath) has a smaller set of nodes:

  • The Document Information Item
  • Element Information Items
  • Attribute Information Items
  • Processing Instruction Information Items
  • Unexpanded Entity Reference Information Items
  • Character Information Items
  • Comment Information Items
  • The Document Type Declaration Information Item
  • Unparsed Entity Information Items
  • Notation Information Items
  • Namespace Information Items
  • XPath has the following Node types:

    • root nodes
    • element nodes
    • text nodes
    • attribute nodes
    • namespace nodes
    • processing instruction nodes
    • comment nodes

    The answer to your question "What is the difference between an element and a node" is:

    An element is a type of node. Many other types of nodes exist and serve different purposes.

    How to substring in jquery

    You don't need jquery in order to do that.

    var placeHolder="name";
    var res=name.substr(name.indexOf(placeHolder) + placeHolder.length);
    

    React hooks useState Array

    To expand on Ryan's answer:

    Whenever setStateValues is called, React re-renders your component, which means that the function body of the StateSelector component function gets re-executed.

    React docs:

    setState() will always lead to a re-render unless shouldComponentUpdate() returns false.

    Essentially, you're setting state with:

    setStateValues(allowedState);
    

    causing a re-render, which then causes the function to execute, and so on. Hence, the loop issue.

    To illustrate the point, if you set a timeout as like:

      setTimeout(
        () => setStateValues(allowedState),
        1000
      )
    

    Which ends the 'too many re-renders' issue.

    In your case, you're dealing with a side-effect, which is handled with UseEffectin your component functions. You can read more about it here.

    How to identify a strong vs weak relationship on ERD?

    In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.

    Format number to 2 decimal places

    This is how I used this is as an example:

    CAST(vAvgMaterialUnitCost.`avgUnitCost` AS DECIMAL(11,2)) * woMaterials.`qtyUsed` AS materialCost
    

    Fail to create Android virtual Device, "No system image installed for this Target"

    I had android sdk and android studio installed separately in my system. Android studio had installed its own sdk. After I deleted the stand-alone android sdk, the issue of "“No system image installed for this Target” was gone.

    How to dynamically create columns in datatable and assign values to it?

    If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

    • Create Data table object.
    • Add columns into that data table object.
    • Add Rows with values into the object.

    For eg.

    Dim dt As New DataTable
    
    dt.Columns.Add("Id", GetType(Integer))
    dt.Columns.Add("FirstName", GetType(String))
    dt.Columns.Add("LastName", GetType(String))
    
    dt.Rows.Add(1, "Test", "data")
    dt.Rows.Add(15, "Robert", "Wich")
    dt.Rows.Add(18, "Merry", "Cylon")
    dt.Rows.Add(30, "Tim", "Burst")
    

    how to do "press enter to exit" in batch

    pause
    

    will display:

    Press any key to continue . . .

    Javascript - User input through HTML input tag to set a Javascript variable?

    When your script is running, it blocks the page from doing anything. You can work around this with one of two ways:

    • Use var foo = prompt("Give me input");, which will give you the string that the user enters into a popup box (or null if they cancel it)
    • Split your code into two function - run one function to set up the user interface, then provide the second function as a callback that gets run when the user clicks the button.

    `getchar()` gives the same output as the input string

    In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.

    pass array to method Java

    class test
    {
        void passArr()
        {
            int arr1[]={1,2,3,4,5,6,7,8,9};
            printArr(arr1);
        }
    
        void printArr(int[] arr2)
        {
            for(int i=0;i<arr2.length;i++)
            {
                System.out.println(arr2[i]+"  ");
            }
        }
    
        public static void main(String[] args)
        {
            test ob=new test();
            ob.passArr();
        }
    }
    

    %Like% Query in spring JpaRepository

    when call funtion, I use: findByPlaceContaining("%" + place);

    or: findByPlaceContaining(place + "%");

    or: findByPlaceContaining("%" + place + "%");

    No provider for TemplateRef! (NgIf ->TemplateRef)

    You missed the * in front of NgIf (like we all have, dozens of times):

    <div *ngIf="answer.accepted">&#10004;</div>
    

    Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


    If you get this error with Angular v5:

    Error: StaticInjectorError[TemplateRef]:
      StaticInjectorError[TemplateRef]:
        NullInjectorError: No provider for TemplateRef!

    You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

    How do I create directory if it doesn't exist to create a file?

    var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));

    var file = new FileInfo(filePath);

    file.Directory.Create(); If the directory already exists, this method does nothing.

    var sw = new StreamWriter(filePath, true);

    sw.WriteLine(Enter your message here);

    sw.Close();

    Understanding dispatch_async

    The main reason you use the default queue over the main queue is to run tasks in the background.

    For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //Background Thread
        dispatch_async(dispatch_get_main_queue(), ^(void){
            //Run UI Updates
        });
    });
    

    How to load all the images from one of my folder into my web page, using Jquery/Javascript

    Based on the answer of Roko C. Buljan, I have created this method which gets images from a folder and its subfolders . This might need some error handling but works fine for a simple folder structure.

    var findImages = function(){
        var parentDir = "./Resource/materials/";
    
        var fileCrowler = function(data){
            var titlestr = $(data).filter('title').text();
            // "Directory listing for /Resource/materials/xxx"
            var thisDirectory = titlestr.slice(titlestr.indexOf('/'), titlestr.length)
    
            //List all image file names in the page
            $(data).find("a").attr("href", function (i, filename) {
                if( filename.match(/\.(jpe?g|png|gif)$/) ) { 
                    var fileNameWOExtension = filename.slice(0, filename.lastIndexOf('.'))
                    var img_html = "<img src='{0}' id='{1}' alt='{2}' width='75' height='75' hspace='2' vspace='2' onclick='onImageSelection(this);'>".format(thisDirectory + filename, fileNameWOExtension, fileNameWOExtension);
                    $("#image_pane").append(img_html);
                }
                else{ 
                    $.ajax({
                        url: thisDirectory + filename,
                        success: fileCrowler
                    });
                }
            });}
    
            $.ajax({
            url: parentDir,
            success: fileCrowler
        });
    }
    

    ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

    Explicitly specifying the max_iter resolves the warning as the default max_iter is 100. [For Logistic Regression].

     logreg = LogisticRegression(max_iter=1000)
    

    Convert JS Object to form data

    I had a scenario where nested JSON had to be serialised in a linear fashion while form data is constructed, since this is how server expects values. So, I wrote a small recursive function which translates the JSON which is like this:

    {
       "orderPrice":"11",
       "cardNumber":"************1234",
       "id":"8796191359018",
       "accountHolderName":"Raj Pawan",
       "expiryMonth":"02",
       "expiryYear":"2019",
       "issueNumber":null,
       "billingAddress":{
          "city":"Wonderland",
          "code":"8796682911767",
          "firstname":"Raj Pawan",
          "lastname":"Gumdal",
          "line1":"Addr Line 1",
          "line2":null,
          "state":"US-AS",
          "region":{
             "isocode":"US-AS"
          },
          "zip":"76767-6776"
       }
    }
    

    Into something like this:

    {
       "orderPrice":"11",
       "cardNumber":"************1234",
       "id":"8796191359018",
       "accountHolderName":"Raj Pawan",
       "expiryMonth":"02",
       "expiryYear":"2019",
       "issueNumber":null,
       "billingAddress.city":"Wonderland",
       "billingAddress.code":"8796682911767",
       "billingAddress.firstname":"Raj Pawan",
       "billingAddress.lastname":"Gumdal",
       "billingAddress.line1":"Addr Line 1",
       "billingAddress.line2":null,
       "billingAddress.state":"US-AS",
       "billingAddress.region.isocode":"US-AS",
       "billingAddress.zip":"76767-6776"
    }
    

    The server would accept form data which is in this converted format.

    Here is the function:

    function jsonToFormData (inJSON, inTestJSON, inFormData, parentKey) {
        // http://stackoverflow.com/a/22783314/260665
        // Raj: Converts any nested JSON to formData.
        var form_data = inFormData || new FormData();
        var testJSON = inTestJSON || {};
        for ( var key in inJSON ) {
            // 1. If it is a recursion, then key has to be constructed like "parent.child" where parent JSON contains a child JSON
            // 2. Perform append data only if the value for key is not a JSON, recurse otherwise!
            var constructedKey = key;
            if (parentKey) {
                constructedKey = parentKey + "." + key;
            }
    
            var value = inJSON[key];
            if (value && value.constructor === {}.constructor) {
                // This is a JSON, we now need to recurse!
                jsonToFormData (value, testJSON, form_data, constructedKey);
            } else {
                form_data.append(constructedKey, inJSON[key]);
                testJSON[constructedKey] = inJSON[key];
            }
        }
        return form_data;
    }
    

    Invocation:

            var testJSON = {};
            var form_data = jsonToFormData (jsonForPost, testJSON);
    

    I am using testJSON just to see the converted results since I would not be able to extract the contents of form_data. AJAX post call:

            $.ajax({
                type: "POST",
                url: somePostURL,
                data: form_data,
                processData : false,
                contentType : false,
                success: function (data) {
                },
                error: function (e) {
                }
            });
    

    Boolean vs boolean in Java

    Basically boolean represent a primitive data type where Boolean represent a reference data type. this story is started when Java want to become purely object oriented it's provided wrapper class concept to over come to use of primitive data type.

    boolean b1;
    Boolean b2;
    

    b1 and b2 are not same.

    Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

    From your python version output, looks like that you are using Anaconda python, in that case, there is a simple way to install tensorflow.

    conda install -c conda-forge tensorflow
    

    This command will take care of all dependencies like upgrade/downgrade etc.

    How to display an alert box from C# in ASP.NET?

    You can create a global method to show message(alert) in your web form application.

    public static class PageUtility
    {
        public static void MessageBox(System.Web.UI.Page page,string strMsg)
        {
            //+ character added after strMsg "')"
            ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "alertMessage", "alert('" + strMsg + "')", true);
    
        }
    }
    

    webform.aspx

    protected void btnSave_Click(object sender, EventArgs e)
    {
        PageUtility.MessageBox(this, "Success !");
    }
    

    What's the difference between a mock & stub?

    If you compare it to debugging:

    Stub is like making sure a method returns the correct value

    Mock is like actually stepping into the method and making sure everything inside is correct before returning the correct value.

    Why is AJAX returning HTTP status code 0?

    In my case, I was getting this but only on Safari Mobile. The problem is that I was using the full URL (http://example.com/whatever.php) instead of the relative one (whatever.php). This doesn't make any sense though, it can't be a XSS issue because my site is hosted at http://example.com. I guess Safari looks at the http part and automatically flags it as an insecure request without inspecting the rest of the URL.

    How to get query parameters from URL in Angular 5?

    Stumbled across this question when I was looking for a similar solution but I didn't need anything like full application level routing or more imported modules.

    The following code works great for my use and requires no additional modules or imports.

      GetParam(name){
        const results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
        if(!results){
          return 0;
        }
        return results[1] || 0;
      }
    
      PrintParams() {
        console.log('param1 = ' + this.GetParam('param1'));
        console.log('param2 = ' + this.GetParam('param2'));
      }
    

    http://localhost:4200/?param1=hello&param2=123 outputs:

    param1 = hello
    param2 = 123
    

    PHP Unset Array value effect on other indexes

    Test it yourself, but here's the output.

    php -r '$a=array("a","b","c"); print_r($a); unset($a[1]); print_r($a);'
    Array
    (
        [0] => a
        [1] => b
        [2] => c
    )
    Array
    (
        [0] => a
        [2] => c
    )
    

    Can I write into the console in a unit test? If yes, why doesn't the console window open?

    You can use

    Trace.WriteLine()
    

    to write to the Output window when debugging a unit test.

    What is the difference between document.location.href and document.location?

    document.location is deprecated in favor of window.location, which can be accessed by just location, since it's a global object.

    The location object has multiple properties and methods. If you try to use it as a string then it acts like location.href.

    android EditText - finished typing event

    A different approach ... here is an example: If the user has a delay of 600-1000ms when is typing you may consider he's stopped.

    _x000D_
    _x000D_
     myEditText.addTextChangedListener(new TextWatcher() {_x000D_
                 _x000D_
                private String s;_x000D_
                private long after;_x000D_
       private Thread t;_x000D_
                private Runnable runnable_EditTextWatcher = new Runnable() {_x000D_
                    @Override_x000D_
                    public void run() {_x000D_
                        while (true) {_x000D_
                            if ((System.currentTimeMillis() - after) > 600)_x000D_
                            {_x000D_
                                Log.d("Debug_EditTEXT_watcher", "(System.currentTimeMillis()-after)>600 ->  " + (System.currentTimeMillis() - after) + " > " + s);_x000D_
                                // Do your stuff_x000D_
                                t = null;_x000D_
                                break;_x000D_
                            }_x000D_
                        }_x000D_
                    }_x000D_
                };_x000D_
                _x000D_
                @Override_x000D_
                public void onTextChanged(CharSequence ss, int start, int before, int count) {_x000D_
                    s = ss.toString();_x000D_
                }_x000D_
                _x000D_
                @Override_x000D_
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {_x000D_
                }_x000D_
                _x000D_
                @Override_x000D_
                public void afterTextChanged(Editable ss) {_x000D_
                    after = System.currentTimeMillis();_x000D_
                    if (t == null)_x000D_
                    {_x000D_
                        t = new Thread(runnable_EditTextWatcher);_x000D_
                          t.start();_x000D_
                    }_x000D_
                }_x000D_
            });
    _x000D_
    _x000D_
    _x000D_

    C subscripted value is neither array nor pointer nor vector when assigning an array element value

    C lets you use the subscript operator [] on arrays and on pointers. When you use this operator on a pointer, the resultant type is the type to which the pointer points to. For example, if you apply [] to int*, the result would be an int.

    That is precisely what's going on: you are passing int*, which corresponds to a vector of integers. Using subscript on it once makes it int, so you cannot apply the second subscript to it.

    It appears from your code that arr should be a 2-D array. If it is implemented as a "jagged" array (i.e. an array of pointers) then the parameter type should be int **.

    Moreover, it appears that you are trying to return a local array. In order to do that legally, you need to allocate the array dynamically, and return a pointer. However, a better approach would be declaring a special struct for your 4x4 matrix, and using it to wrap your fixed-size array, like this:

    // This type wraps your 4x4 matrix
    typedef struct {
        int arr[4][4];
    } FourByFour;
    // Now rotate(m) can use FourByFour as a type
    FourByFour rotate(FourByFour m) {
        FourByFour D;
        for(int i = 0; i < 4; i ++ ){
            for(int n = 0; n < 4; n++){
                D.arr[i][n] = m.arr[n][3 - i];
            }
        }
        return D;
    }
    // Here is a demo of your rotate(m) in action:
    int main(void) {
        FourByFour S = {.arr = {
            { 1, 4, 10, 3 },
            { 0, 6, 3, 8 },
            { 7, 10 ,8, 5 },
            { 9, 5, 11, 2}
        } };
        FourByFour r = rotate(S);
        for(int i=0; i < 4; i ++ ){
            for(int n=0; n < 4; n++){
                printf("%d ", r.arr[i][n]);
            }
            printf("\n");
        }
        return 0;
    }
    

    This prints the following:

    3 8 5 2 
    10 3 8 11 
    4 6 10 5 
    1 0 7 9 
    

    How to insert an image in python

    Install PIL(Python Image Library) :

    then:

    from PIL import Image
    myImage = Image.open("your_image_here");
    myImage.show();
    

    How do I calculate the percentage of a number?

    $percentage = 50;
    $totalWidth = 350;
    
    $new_width = ($percentage / 100) * $totalWidth;
    

    #pragma once vs include guards?

    From a software tester's perspective

    #pragma once is shorter than an include guard, less error prone, supported by most compilers, and some say that it compiles faster (which is not true [any longer]).

    But I still suggest you go with standard #ifndef include guards.

    Why #ifndef?

    Consider a contrived class hierarchy like this where each of the classes A, B, and C lives inside its own file:

    a.h

    #ifndef A_H
    #define A_H
    
    class A {
    public:
      // some virtual functions
    };
    
    #endif
    

    b.h

    #ifndef B_H
    #define B_H
    
    #include "a.h"
    
    class B : public A {
    public:
      // some functions
    };
    
    #endif
    

    c.h

    #ifndef C_H
    #define C_H
    
    #include "b.h"
    
    class C : public B {
    public:
      // some functions
    };
    
    #endif
    

    Now let's assume you are writing tests for your classes and you need to simulate the behaviour of the really complex class B. One way to do this would be to write a mock class using for example google mock and put it inside a directory mocks/b.h. Note, that the class name hasn't changed but it's only stored inside a different directory. But what's most important is that the include guard is named exactly the same as in the original file b.h.

    mocks/b.h

    #ifndef B_H
    #define B_H
    
    #include "a.h"
    #include "gmock/gmock.h"
    
    class B : public A {
    public:
      // some mocks functions
      MOCK_METHOD0(SomeMethod, void());
    };
    
    #endif
    

    What's the benefit?

    With this approach you can mock the behaviour of class B without touching the original class or telling C about it. All you have to do is put the directory mocks/ in the include path of your complier.

    Why can't this be done with #pragma once?

    If you would have used #pragma once, you would get a name clash because it cannot protect you from defining the class B twice, once the original one and once the mocked version.

    How to get the first 2 letters of a string in Python?

    In general, you can the characters of a string from i until j with string[i:j]. string[:2] is shorthand for string[0:2]. This works for arrays as well.

    Learn about python's slice notation at the official tutorial

    PHP: Split string

    explode('.', $string)

    If you know your string has a fixed number of components you could use something like

    list($a, $b) = explode('.', 'object.attribute');
    echo $a;
    echo $b;
    

    Prints:

    object
    attribute
    

    Multiple inputs with same name through POST in php

    It can be:

    echo "Welcome".$_POST['firstname'].$_POST['lastname'];
    

    How can I use onItemSelected in Android?

    spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    
                   //check if spinner2 has a selected item and show the value in edittext
    
                }
    
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
    
                   // sometimes you need nothing here
                }
            });
    
    spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    
                   //check if spinner1 has a selected item and show the value in edittext
    
    
                }
    
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
    
                   // sometimes you need nothing here
                }
            });
    

    Percentage calculation

    Mathematically, to get percentage from two numbers:

    percentage = (yourNumber / totalNumber) * 100;
    

    And also, to calculate from a percentage :

    number = (percentage / 100) * totalNumber;
    

    cvc-elt.1: Cannot find the declaration of element 'MyElement'

    Your schema is for its target namespace http://www.example.org/Test so it defines an element with name MyElement in that target namespace http://www.example.org/Test. Your instance document however has an element with name MyElement in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.

    You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>.

    What are queues in jQuery?

    Function makeRed and makeBlack use queue and dequeue to execute each other. The effect is that, the '#wow' element blinks continuously.

    <html>
      <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script type="text/javascript">
          $(document).ready(function(){
              $('#wow').click(function(){
                $(this).delay(200).queue(makeRed);
                });
              });
    
          function makeRed(){
            $('#wow').css('color', 'red');
            $('#wow').delay(200).queue(makeBlack);
            $('#wow').dequeue();
          }
    
          function makeBlack(){
            $('#wow').css('color', 'black');
            $('#wow').delay(200).queue(makeRed);
            $('#wow').dequeue();
          }
        </script>
      </head>
      <body>
        <div id="wow"><p>wow</p></div>
      </body>
    </html>
    

    Jenkins: Failed to connect to repository

    I had the exact same problem. The way I solved it on Mac is this:

    1. Switch to jenkins user (sudo -iu jenkins)
    2. Run: ssh-keygen (Note - You are creating ssh key pairs for jenkins user now. You should see something like this : Enter file in which to save the key (/Users/Shared/Jenkins/.ssh/id_rsa):
    3. Keep pressing Enter for default value till end
    4. Run the command showing in the Jenkins error message, on your teminal (eg : "git ls-remote -h [email protected]:adolfosrs/jenkins-test.git HEAD")
    5. You will be asked if you want to continue. Say yes
    6. The Github repo will be added to your known_hosts file in : /Users/Shared/Jenkins/.ssh/
    7. Go back to Jenkins portal and try your Github SSH url
    8. It should work. Good Luck

    Eclipse Bug: Unhandled event loop exception No more handles

    I have the same problem. It is caused by a screen capture software hypersnap7. So I think the hotkey conflict is the reason. Reboot computer, don't start other software, start Android Development Tools and watch which software triger the bug.

    How to automatically generate getters and setters in Android Studio

    This answer deals with your question but is not exactly an answer to it. =) It's an interesting library I found out recently and I want to share with you.


    Project Lombok can generate common methods, such as getters, setters, equals() and hashCode(), toString(), for your classes automatically. It replaces them with annotations reducing boilerplate code. To see a good example of code written using Lombok watch a video on the main page or read this article.

    Android development with Lombok is easy and won't make your android application any 'heavier' because Lombok is a compile-time only library. It is important to configure your Android project properly.

    Another example:

    import lombok.Getter;
    import lombok.Setter;
    
    public class Profile {
    
      @Getter @Setter
      private String username;
    
      @Getter @Setter
      private String password;
    
    }
    

    Android development with Lombok is possible. Lombok should be a compile-time only dependency, as otherwise the entirety of Lombok will end up in your DEX files, wasting precious space. Gradle snippet:

    dependencies {
        compileOnly "org.projectlombok:lombok:1.16.18"
    }
    

    In addition you may want to add the Lombok IntelliJ plugin to support Lombok features in your IDE at development time. Also there is Hrisey library which is based on Lombok. Simply put, it's Lombok + Parcellable support.

    Convert a string date into datetime in Oracle

    Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

    What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

    As mentioned, you can use:

    =Format(Fields!Price.Value, "C")
    

    A digit after the "C" will specify precision:

    =Format(Fields!Price.Value, "C0")
    =Format(Fields!Price.Value, "C1")
    

    You can also use Excel-style masks like this:

    =Format(Fields!Price.Value, "#,##0.00")
    

    Haven't tested the last one, but there's the idea. Also works with dates:

    =Format(Fields!Date.Value, "yyyy-MM-dd")
    

    Remove innerHTML from div

    $('div').html('');
    

    But why are you clearing, divToUpdate.html(data); will completely replace the old HTML.

    How to convert JSONObjects to JSONArray?

    Your response should be something like this to be qualified as Json Array.

    {
      "songs":[
        {"2562862600": {"id":"2562862600", "pos":1}},  
        {"2562862620": {"id":"2562862620", "pos":1}},  
        {"2562862604": {"id":"2562862604", "pos":1}},  
        {"2573433638": {"id":"2573433638", "pos":1}}
      ]
    }
    

    You can parse your response as follows

    String resp = ...//String output from your source
    JSONObject ob = new JSONObject(resp);  
    JSONArray arr = ob.getJSONArray("songs");
    
    for(int i=0; i<arr.length(); i++){   
      JSONObject o = arr.getJSONObject(i);  
      System.out.println(o);  
    }
    

    Measuring execution time of a function in C++

    • It is a very easy to use method in C++11.
    • We can use std::chrono::high_resolution_clock from header
    • We can write a method to print the method execution time in a much readable form.

    For example, to find the all the prime numbers between 1 and 100 million, it takes approximately 1 minute and 40 seconds. So the execution time get printed as:

    Execution Time: 1 Minutes, 40 Seconds, 715 MicroSeconds, 715000 NanoSeconds
    

    The code is here:

    #include <iostream>
    #include <chrono>
    
    using namespace std;
    using namespace std::chrono;
    
    typedef high_resolution_clock Clock;
    typedef Clock::time_point ClockTime;
    
    void findPrime(long n, string file);
    void printExecutionTime(ClockTime start_time, ClockTime end_time);
    
    int main()
    {
        long n = long(1E+8);  // N = 100 million
    
        ClockTime start_time = Clock::now();
    
        // Write all the prime numbers from 1 to N to the file "prime.txt"
        findPrime(n, "C:\\prime.txt"); 
    
        ClockTime end_time = Clock::now();
    
        printExecutionTime(start_time, end_time);
    }
    
    void printExecutionTime(ClockTime start_time, ClockTime end_time)
    {
        auto execution_time_ns = duration_cast<nanoseconds>(end_time - start_time).count();
        auto execution_time_ms = duration_cast<microseconds>(end_time - start_time).count();
        auto execution_time_sec = duration_cast<seconds>(end_time - start_time).count();
        auto execution_time_min = duration_cast<minutes>(end_time - start_time).count();
        auto execution_time_hour = duration_cast<hours>(end_time - start_time).count();
    
        cout << "\nExecution Time: ";
        if(execution_time_hour > 0)
        cout << "" << execution_time_hour << " Hours, ";
        if(execution_time_min > 0)
        cout << "" << execution_time_min % 60 << " Minutes, ";
        if(execution_time_sec > 0)
        cout << "" << execution_time_sec % 60 << " Seconds, ";
        if(execution_time_ms > 0)
        cout << "" << execution_time_ms % long(1E+3) << " MicroSeconds, ";
        if(execution_time_ns > 0)
        cout << "" << execution_time_ns % long(1E+6) << " NanoSeconds, ";
    }
    

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

    Using the second form gives you a variable (named based upon the as clause, in your example e) in the except block scope with the exception object bound to it so you can use the infomration in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.

    PHP foreach with Nested Array?

    foreach ($tmpArray as $innerArray) {
        //  Check type
        if (is_array($innerArray)){
            //  Scan through inner loop
            foreach ($innerArray as $value) {
                echo $value;
            }
        }else{
            // one, two, three
            echo $innerArray;
        }
    }
    

    ALTER DATABASE failed because a lock could not be placed on database

    In my scenario, there was no process blocking the database under sp_who2. However, we discovered because the database is much larger than our other databases that pending processes were still running which is why the database under the availability group still displayed as red/offline after we tried to 'resume data'by right clicking the paused database.

    To check if you still have processes running just execute this command: select percent complete from sys.dm_exec_requests where percent_complete > 0

    How do I watch a file for changes?

    I don't know any Windows specific function. You could try getting the MD5 hash of the file every second/minute/hour (depends on how fast you need it) and compare it to the last hash. When it differs you know the file has been changed and you read out the newest lines.

    read file from assets

    Here is what I do in an activity for buffered reading extend/modify to match your needs

    BufferedReader reader = null;
    try {
        reader = new BufferedReader(
            new InputStreamReader(getAssets().open("filename.txt")));
    
        // do reading, usually loop until end of file reading  
        String mLine;
        while ((mLine = reader.readLine()) != null) {
           //process line
           ...
        }
    } catch (IOException e) {
        //log the exception
    } finally {
        if (reader != null) {
             try {
                 reader.close();
             } catch (IOException e) {
                 //log the exception
             }
        }
    }
    

    EDIT : My answer is perhaps useless if your question is on how to do it outside of an activity. If your question is simply how to read a file from asset then the answer is above.

    UPDATE :

    To open a file specifying the type simply add the type in the InputStreamReader call as follow.

    BufferedReader reader = null;
    try {
        reader = new BufferedReader(
            new InputStreamReader(getAssets().open("filename.txt"), "UTF-8")); 
    
        // do reading, usually loop until end of file reading 
        String mLine;
        while ((mLine = reader.readLine()) != null) {
           //process line
           ...
        }
    } catch (IOException e) {
        //log the exception
    } finally {
        if (reader != null) {
             try {
                 reader.close();
             } catch (IOException e) {
                 //log the exception
             }
        }
    }
    

    EDIT

    As @Stan says in the comment, the code I am giving is not summing up lines. mLine is replaced every pass. That's why I wrote //process line. I assume the file contains some sort of data (i.e a contact list) and each line should be processed separately.

    In case you simply want to load the file without any kind of processing you will have to sum up mLine at each pass using StringBuilder() and appending each pass.

    ANOTHER EDIT

    According to the comment of @Vincent I added the finally block.

    Also note that in Java 7 and upper you can use try-with-resources to use the AutoCloseable and Closeable features of recent Java.

    CONTEXT

    In a comment @LunarWatcher points out that getAssets() is a class in context. So, if you call it outside of an activity you need to refer to it and pass the context instance to the activity.

    ContextInstance.getAssets();
    

    This is explained in the answer of @Maneesh. So if this is useful to you upvote his answer because that's him who pointed that out.

    cancelling a handler.postdelayed process

    I do this to post a delayed runnable:

    myHandler.postDelayed(myRunnable, SPLASH_DISPLAY_LENGTH); 
    

    And this to remove it: myHandler.removeCallbacks(myRunnable);

    Export multiple classes in ES6 modules

    Try this in your code:

    import Foo from './Foo';
    import Bar from './Bar';
    
    // without default
    export {
      Foo,
      Bar,
    }
    

    Btw, you can also do it this way:

    // bundle.js
    export { default as Foo } from './Foo'
    export { default as Bar } from './Bar'
    export { default } from './Baz'
    
    // and import somewhere..
    import Baz, { Foo, Bar } from './bundle'
    

    Using export

    export const MyFunction = () => {}
    export const MyFunction2 = () => {}
    
    const Var = 1;
    const Var2 = 2;
    
    export {
       Var,
       Var2,
    }
    
    
    // Then import it this way
    import {
      MyFunction,
      MyFunction2,
      Var,
      Var2,
    } from './foo-bar-baz';
    

    The difference with export default is that you can export something, and apply the name where you import it:

    // export default
    export default class UserClass {
      constructor() {}
    };
    
    // import it
    import User from './user'
    

    Disable time in bootstrap date time picker

    $('#datetimepicker').datetimepicker({ 
        minView: 2, 
        pickTime: false, 
        language: 'pt-BR' 
    });
    

    Please try if it works for you as well

    What is the Git equivalent for revision number?

    Post build event for Visual Studio

    echo  >RevisionNumber.cs static class Git { public static int RevisionNumber =
    git  >>RevisionNumber.cs rev-list --count HEAD
    echo >>RevisionNumber.cs ; }
    

    What is a Memory Heap?

    A memory heap is a location in memory where memory may be allocated at random access.
    Unlike the stack where memory is allocated and released in a very defined order, individual data elements allocated on the heap are typically released in ways which is asynchronous from one another. Any such data element is freed when the program explicitly releases the corresponding pointer, and this may result in a fragmented heap. In opposition only data at the top (or the bottom, depending on the way the stack works) may be released, resulting in data element being freed in the reverse order they were allocated.

    Convert date formats in bash

    Maybe something changed since 2011 but this worked for me:

    $ date +"%Y%m%d"
    20150330
    

    No need for the -d to get the same appearing result.

    html5: display video inside canvas

    Using canvas to display Videos

    Displaying a video is much the same as displaying an image. The minor differences are to do with onload events and the fact that you need to render the video every frame or you will only see one frame not the animated frames.

    The demo below has some minor differences to the example. A mute function (under the video click mute/sound on to toggle sound) and some error checking to catch IE9+ and Edge if they don't have the correct drivers.

    Keeping answers current.

    The previous answers by user372551 is out of date (December 2010) and has a flaw in the rendering technique used. It uses the setTimeout and a rate of 33.333..ms which setTimeout will round down to 33ms this will cause the frames to be dropped every two seconds and may drop many more if the video frame rate is any higher than 30. Using setTimeout will also introduce video shearing created because setTimeout can not be synced to the display hardware.

    There is currently no reliable method that can determine a videos frame rate unless you know the video frame rate in advance you should display it at the maximum display refresh rate possible on browsers. 60fps

    The given top answer was for the time (6 years ago) the best solution as requestAnimationFrame was not widely supported (if at all) but requestAnimationFrame is now standard across the Major browsers and should be used instead of setTimeout to reduce or remove dropped frames, and to prevent shearing.

    The example demo.

    Loads a video and set it to loop. The video will not play until the you click on it. Clicking again will pause. There is a mute/sound on button under the video. The video is muted by default.

    Note users of IE9+ and Edge. You may not be able to play the video format WebM as it needs additional drivers to play the videos. They can be found at tools.google.com Download IE9+ WebM support

    _x000D_
    _x000D_
    // This code is from the example document on stackoverflow documentation. See HTML for link to the example._x000D_
    // This code is almost identical to the example. Mute has been added and a media source. Also added some error handling in case the media load fails and a link to fix IE9+ and Edge support._x000D_
    // Code by Blindman67._x000D_
    _x000D_
    _x000D_
    // Original source has returns 404_x000D_
    // var mediaSource = "http://video.webmfiles.org/big-buck-bunny_trailer.webm";_x000D_
    // New source from wiki commons. Attribution in the leading credits._x000D_
    var mediaSource = "http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv"_x000D_
    _x000D_
    var muted = true;_x000D_
    var canvas = document.getElementById("myCanvas"); // get the canvas from the page_x000D_
    var ctx = canvas.getContext("2d");_x000D_
    var videoContainer; // object to hold video and associated info_x000D_
    var video = document.createElement("video"); // create a video element_x000D_
    video.src = mediaSource;_x000D_
    // the video will now begin to load._x000D_
    // As some additional info is needed we will place the video in a_x000D_
    // containing object for convenience_x000D_
    video.autoPlay = false; // ensure that the video does not auto play_x000D_
    video.loop = true; // set the video to loop._x000D_
    video.muted = muted;_x000D_
    videoContainer = {  // we will add properties as needed_x000D_
         video : video,_x000D_
         ready : false,   _x000D_
    };_x000D_
    // To handle errors. This is not part of the example at the moment. Just fixing for Edge that did not like the ogv format video_x000D_
    video.onerror = function(e){_x000D_
        document.body.removeChild(canvas);_x000D_
        document.body.innerHTML += "<h2>There is a problem loading the video</h2><br>";_x000D_
        document.body.innerHTML += "Users of IE9+ , the browser does not support WebM videos used by this demo";_x000D_
        document.body.innerHTML += "<br><a href='https://tools.google.com/dlpage/webmmf/'> Download IE9+ WebM support</a> from tools.google.com<br> this includes Edge and Windows 10";_x000D_
        _x000D_
     }_x000D_
    video.oncanplay = readyToPlayVideo; // set the event to the play function that _x000D_
                                      // can be found below_x000D_
    function readyToPlayVideo(event){ // this is a referance to the video_x000D_
        // the video may not match the canvas size so find a scale to fit_x000D_
        videoContainer.scale = Math.min(_x000D_
                             canvas.width / this.videoWidth, _x000D_
                             canvas.height / this.videoHeight); _x000D_
        videoContainer.ready = true;_x000D_
        // the video can be played so hand it off to the display function_x000D_
        requestAnimationFrame(updateCanvas);_x000D_
        // add instruction_x000D_
        document.getElementById("playPause").textContent = "Click video to play/pause.";_x000D_
        document.querySelector(".mute").textContent = "Mute";_x000D_
    }_x000D_
    _x000D_
    function updateCanvas(){_x000D_
        ctx.clearRect(0,0,canvas.width,canvas.height); _x000D_
        // only draw if loaded and ready_x000D_
        if(videoContainer !== undefined && videoContainer.ready){ _x000D_
            // find the top left of the video on the canvas_x000D_
            video.muted = muted;_x000D_
            var scale = videoContainer.scale;_x000D_
            var vidH = videoContainer.video.videoHeight;_x000D_
            var vidW = videoContainer.video.videoWidth;_x000D_
            var top = canvas.height / 2 - (vidH /2 ) * scale;_x000D_
            var left = canvas.width / 2 - (vidW /2 ) * scale;_x000D_
            // now just draw the video the correct size_x000D_
            ctx.drawImage(videoContainer.video, left, top, vidW * scale, vidH * scale);_x000D_
            if(videoContainer.video.paused){ // if not playing show the paused screen _x000D_
                drawPayIcon();_x000D_
            }_x000D_
        }_x000D_
        // all done for display _x000D_
        // request the next frame in 1/60th of a second_x000D_
        requestAnimationFrame(updateCanvas);_x000D_
    }_x000D_
    _x000D_
    function drawPayIcon(){_x000D_
         ctx.fillStyle = "black";  // darken display_x000D_
         ctx.globalAlpha = 0.5;_x000D_
         ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
         ctx.fillStyle = "#DDD"; // colour of play icon_x000D_
         ctx.globalAlpha = 0.75; // partly transparent_x000D_
         ctx.beginPath(); // create the path for the icon_x000D_
         var size = (canvas.height / 2) * 0.5;  // the size of the icon_x000D_
         ctx.moveTo(canvas.width/2 + size/2, canvas.height / 2); // start at the pointy end_x000D_
         ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 + size);_x000D_
         ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 - size);_x000D_
         ctx.closePath();_x000D_
         ctx.fill();_x000D_
         ctx.globalAlpha = 1; // restore alpha_x000D_
    }    _x000D_
    _x000D_
    function playPauseClick(){_x000D_
         if(videoContainer !== undefined && videoContainer.ready){_x000D_
              if(videoContainer.video.paused){                                 _x000D_
                    videoContainer.video.play();_x000D_
              }else{_x000D_
                    videoContainer.video.pause();_x000D_
              }_x000D_
         }_x000D_
    }_x000D_
    function videoMute(){_x000D_
        muted = !muted;_x000D_
     if(muted){_x000D_
             document.querySelector(".mute").textContent = "Mute";_x000D_
        }else{_x000D_
             document.querySelector(".mute").textContent= "Sound on";_x000D_
        }_x000D_
    _x000D_
    _x000D_
    }_x000D_
    // register the event_x000D_
    canvas.addEventListener("click",playPauseClick);_x000D_
    document.querySelector(".mute").addEventListener("click",videoMute)
    _x000D_
    body {_x000D_
        font :14px  arial;_x000D_
        text-align : center;_x000D_
        background : #36A;_x000D_
    }_x000D_
    h2 {_x000D_
        color : white;_x000D_
    }_x000D_
    canvas {_x000D_
        border : 10px white solid;_x000D_
        cursor : pointer;_x000D_
    }_x000D_
    a {_x000D_
      color : #F93;_x000D_
    }_x000D_
    .mute {_x000D_
        cursor : pointer;_x000D_
        display: initial;   _x000D_
    }
    _x000D_
    <h2>Basic Video & canvas example</h2>_x000D_
    <p>Code example from Stackoverflow Documentation HTML5-Canvas<br>_x000D_
    <a href="https://stackoverflow.com/documentation/html5-canvas/3689/media-types-and-the-canvas/14974/basic-loading-and-playing-a-video-on-the-canvas#t=201607271638099201116">Basic loading and playing a video on the canvas</a></p>_x000D_
    <canvas id="myCanvas" width = "532" height ="300" ></canvas><br>_x000D_
    <h3><div id = "playPause">Loading content.</div></h3>_x000D_
    <div class="mute"></div><br>_x000D_
    <div style="font-size:small">Attribution in the leading credits.</div><br>
    _x000D_
    _x000D_
    _x000D_

    Canvas extras

    Using the canvas to render video gives you additional options in regard to displaying and mixing in fx. The following image shows some of the FX you can get using the canvas. Using the 2D API gives a huge range of creative possibilities.

    Image relating to answer Fade canvas video from greyscale to color Video filters "Lighten", "Black & white", "Sepia", "Saturate", and "Negative"

    See video title in above demo for attribution of content in above inmage.

    How to convert this var string to URL in Swift

    in swift 4 to convert to url use URL

    let fileUrl = URL.init(fileURLWithPath: filePath)
    

    or

    let fileUrl = URL(fileURLWithPath: filePath)
    

    Is there a way to specify how many characters of a string to print out using printf()?

    In C++ it is easy.

    std::copy(someStr.c_str(), someStr.c_str()+n, std::ostream_iterator<char>(std::cout, ""));
    

    EDIT: It is also safer to use this with string iterators, so you don't run off the end. I'm not sure what happens with printf and string that are too short, but I'm guess this may be safer.

    Got a NumberFormatException while trying to parse a text file for objects

    I changed Scanner fin = new Scanner(file); to Scanner fin = new Scanner(new File(file)); and it works perfectly now. I didn't think the difference mattered but there you go.

    How can I change the color of AlertDialog title and the color of the line under it

    Divider color:

    It is a hack a bit, but it works great for me and it works without any external library (at least on Android 4.4).

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.dialog)
           .setIcon(R.drawable.ic)
           .setMessage(R.string.dialog_msg);
    //The tricky part
    Dialog d = builder.show();
    int dividerId = d.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
    View divider = d.findViewById(dividerId);
    divider.setBackgroundColor(getResources().getColor(R.color.my_color));
    

    You can find more dialog's ids in alert_dialog.xml file. Eg. android:id/alertTitle for changing title color...

    UPDATE: Title color

    Hack for changing title color:

    int textViewId = d.getContext().getResources().getIdentifier("android:id/alertTitle", null, null);
    TextView tv = (TextView) d.findViewById(textViewId);
    tv.setTextColor(getResources().getColor(R.color.my_color));
    

    Remove scrollbar from iframe

    <div id="myInfoDiv" seamless="seamless" scrolling="no" style="width:100%; height: 100%; float: left; color: #FFF; background:#ed8719; line-height:100%; font-size:100%; font-family: sans-serif>;
    

    Use the above div and it will not show scroll bar in any browser.

    What is the difference between a string and a byte string?

    Unicode is an agreed-upon format for the binary representation of characters and various kinds of formatting (e.g. lower case/upper case, new line, carriage return), and other "things" (e.g. emojis). A computer is no less capable of storing a unicode representation (a series of bits), whether in memory or in a file, than it is of storing an ascii representation (a different series of bits), or any other representation (series of bits).

    For communication to take place, the parties to the communication must agree on what representation will be used.

    Because unicode seeks to represent all the possible characters (and other "things") used in inter-human and inter-computer communication, it requires a greater number of bits for the representation of many characters (or things) than other systems of representation that seek to represent a more limited set of characters/things. To "simplify," and perhaps to accommodate historical usage, unicode representation is almost exclusively converted to some other system of representation (e.g. ascii) for the purpose of storing characters in files.

    It is not the case that unicode cannot be used for storing characters in files, or transmitting them through any communications channel, simply that it is not.

    The term "string," is not precisely defined. "String," in its common usage, refers to a set of characters/things. In a computer, those characters may be stored in any one of many different bit-by-bit representations. A "byte string" is a set of characters stored using a representation that uses eight bits (eight bits being referred to as a byte). Since, these days, computers use the unicode system (characters represented by a variable number of bytes) to store characters in memory, and byte strings (characters represented by single bytes) to store characters to files, a conversion must be used before characters represented in memory will be moved into storage in files.

    How to hide Bootstrap previous modal when you opening new one?

    The best that I've been able to do is

    $(this).closest('.modal').modal('toggle');
    

    This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

    You can however do this:

    $(".modal:visible").modal('toggle');
    

    This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

    Query EC2 tags from within instance

    I have pieced together the following that is hopefully simpler and cleaner than some of the existing answers and uses only the AWS CLI and no additional tools.

    This code example shows how to get the value of tag 'myTag' for the current EC2 instance:

    Using describe-tags:

    export AWS_DEFAULT_REGION=us-east-1
    instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
    aws ec2 describe-tags \
      --filters "Name=resource-id,Values=$instance_id" 'Name=key,Values=myTag' \
      --query 'Tags[].Value' --output text
    

    Or, alternatively, using describe-instances:

    aws ec2 describe-instances --instance-id $instance_id \
      --query 'Reservations[].Instances[].Tags[?Key==`myTag`].Value' --output text
    

    Easiest way to mask characters in HTML(5) text input

    Look up the new HTML5 Input Types. These instruct browsers to perform client-side filtering of data, but the implementation is incomplete across different browsers. The pattern attribute will do regex-style filtering, but, again, browsers don't fully (or at all) support it.

    However, these won't block the input itself, it will simply prevent submitting the form with the invalid data. You'll still need to trap the onkeydown event to block key input before it displays on the screen.

    Differences in string compare methods in C#

    Using .Equals is also a lot easier to read.

    setImmediate vs. nextTick

    Use setImmediate if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.

    So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate rather than process.nextTick to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.

    Is a URL allowed to contain a space?

    To answer your question. I would say it's fairly common for applications to replace spaces in values that will be used in URLs. The reason for this is ussually to avoid the more difficult to read percent (URI) encoding that occurs.

    Check out this wikipedia article about Percent-encoding.

    List All Google Map Marker Images

    var pinIcon = new google.maps.MarkerImage(
        "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
        null, /* size is determined at runtime */
        null, /* origin is 0,0 */
        null, /* anchor is bottom center of the scaled image */
        new google.maps.Size(12, 18)
    );
    

    How to check if a URL exists or returns 404 with Java?

    Use HttpUrlConnection by calling openConnection() on your URL object.

    getResponseCode() will give you the HTTP response once you've read from the connection.

    e.g.

       URL u = new URL("http://www.example.com/"); 
       HttpURLConnection huc = (HttpURLConnection)u.openConnection(); 
       huc.setRequestMethod("GET"); 
       huc.connect() ; 
       OutputStream os = huc.getOutputStream(); 
       int code = huc.getResponseCode(); 
    

    (not tested)

    How to update fields in a model without creating a new record in django?

    Sometimes it may be required to execute the update atomically that is using one update request to the database without reading it first.

    Also get-set attribute-save may cause problems if such updates may be done concurrently or if you need to set the new value based on the old field value.

    In such cases query expressions together with update may by useful:

    TemperatureData.objects.filter(id=1).update(value=F('value') + 1)
    

    SyntaxError: import declarations may only appear at top level of a module

    I got this on Firefox (FF58). I fixed this with:

    1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

    Source: Import page on mozilla (See Browser compatibility)

    1. Add type="module" to your script tag where you import the js file

    <script type="module" src="appthatimports.js"></script>

    1. Import files have to be prefixed (./, /, ../ or http:// before)

    import * from "./mylib.js"

    For more examples, this blog post is good.

    Detecting user leaving page with react-router

    For react-router v3.x

    I had the same issue where I needed a confirmation message for any unsaved change on the page. In my case, I was using React Router v3, so I could not use <Prompt />, which was introduced from React Router v4.

    I handled 'back button click' and 'accidental link click' with the combination of setRouteLeaveHook and history.pushState(), and handled 'reload button' with onbeforeunload event handler.

    setRouteLeaveHook (doc) & history.pushState (doc)

    • Using only setRouteLeaveHook was not enough. For some reason, the URL was changed although the page remained the same when 'back button' was clicked.

        // setRouteLeaveHook returns the unregister method
        this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
          this.props.route,
          this.routerWillLeave
        );
      
        ...
      
        routerWillLeave = nextLocation => {
          // Using native 'confirm' method to show confirmation message
          const result = confirm('Unsaved work will be lost');
          if (result) {
            // navigation confirmed
            return true;
          } else {
            // navigation canceled, pushing the previous path
            window.history.pushState(null, null, this.props.route.path);
            return false;
          }
        };
      

    onbeforeunload (doc)

    • It is used to handle 'accidental reload' button

      window.onbeforeunload = this.handleOnBeforeUnload;
      
      ...
      
      handleOnBeforeUnload = e => {
        const message = 'Are you sure?';
        e.returnValue = message;
        return message;
      }
      

    Below is the full component that I have written

    • note that withRouter is used to have this.props.router.
    • note that this.props.route is passed down from the calling component
    • note that currentState is passed as prop to have initial state and to check any change

      import React from 'react';
      import PropTypes from 'prop-types';
      import _ from 'lodash';
      import { withRouter } from 'react-router';
      import Component from '../Component';
      import styles from './PreventRouteChange.css';
      
      class PreventRouteChange extends Component {
        constructor(props) {
          super(props);
          this.state = {
            // initialize the initial state to check any change
            initialState: _.cloneDeep(props.currentState),
            hookMounted: false
          };
        }
      
        componentDidUpdate() {
      
         // I used the library called 'lodash'
         // but you can use your own way to check any unsaved changed
          const unsaved = !_.isEqual(
            this.state.initialState,
            this.props.currentState
          );
      
          if (!unsaved && this.state.hookMounted) {
            // unregister hooks
            this.setState({ hookMounted: false });
            this.unregisterRouteHook();
            window.onbeforeunload = null;
          } else if (unsaved && !this.state.hookMounted) {
            // register hooks
            this.setState({ hookMounted: true });
            this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
              this.props.route,
              this.routerWillLeave
            );
            window.onbeforeunload = this.handleOnBeforeUnload;
          }
        }
      
        componentWillUnmount() {
          // unregister onbeforeunload event handler
          window.onbeforeunload = null;
        }
      
        handleOnBeforeUnload = e => {
          const message = 'Are you sure?';
          e.returnValue = message;
          return message;
        };
      
        routerWillLeave = nextLocation => {
          const result = confirm('Unsaved work will be lost');
          if (result) {
            return true;
          } else {
            window.history.pushState(null, null, this.props.route.path);
            if (this.formStartEle) {
              this.moveTo.move(this.formStartEle);
            }
            return false;
          }
        };
      
        render() {
          return (
            <div>
              {this.props.children}
            </div>
          );
        }
      }
      
      PreventRouteChange.propTypes = propTypes;
      
      export default withRouter(PreventRouteChange);
      

    Please let me know if there is any question :)

    How to set IE11 Document mode to edge as default?

    try to add this section in your web.config file on web server, sometimes it happens with php pages:

    <httpProtocol>
        <customHeaders>
            <clear />
            <add name="X-UA-Compatible" value="IE=edge" />
        </customHeaders>
    </httpProtocol>
    

    Bootstrap 3: Scroll bars

    You need to use the overflow option, but with the following parameters:

    .nav {
        max-height:300px;
        overflow-y:auto;  
    }
    

    Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

    If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

    Presumably you want something that adapts itself to the content rather then the the opposite.

    Hope it may helpful

    what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?

    Given this example url:

    http://www.example.com/some-dir/yourpage.php?q=bogus&n=10

    $_SERVER['REQUEST_URI'] will give you:

    /some-dir/yourpage.php?q=bogus&n=10

    Whereas $_GET['q'] will give you:

    bogus

    In other words, $_SERVER['REQUEST_URI'] will hold the full request path including the querystring. And $_GET['q'] will give you the value of parameter q in the querystring.

    How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

    For my project, I have a requirement to be able to build to both x86 and x64. The problem with this is that whenever you add references while using one, then it complains when you build the other.

    My solution is to manually edit the *.csproj files so that lines like these:

    <Reference Include="MyLibrary.MyNamespace, Version=1.0.0.0, Culture=neutral, processorArchitecture=x86"/>
    
    <Reference Include="MyLibrary.MyNamespace, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64"/>
    
    <Reference Include="MyLibrary.MyNamespace, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"/>
    

    get changed to this:

    <Reference Include="MyLibrary.MyNamespace, Version=1.0.0.0, Culture=neutral"/>
    

    Gradle Build Android Project "Could not resolve all dependencies" error

    Go to wherever you installed Android Studio (for me it's under C:\Users\username\AppData\Local\Android\android-studio\) and open sdk\tools, then run android.bat. From here, update and download any missing build-tools and make sure you update the Android Support Repository and Android Support Library under Extras. Restart Android Studio after the SDK Manager finishes.

    It seems that Android Studio completely ignores any installed Android SDK files and keeps a copy of its own. After running an update, everything compiled successfully for me using compile com.android.support:appcompat-v7:18.0.+

    Face recognition Library

    You can try open MVG library, It can be used for multiple interfaces too.

    JBoss AS 7: How to clean up tmp?

    As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time

    Before

    jboss-as-7
     |
     |---> standalone
     |      |----> lib
     |      |----> configuration
     |      |----> deployments
     |      
     |---> domain
     |....
    

    After

    jboss-as-7
         |
         |---> standalone
         |      |----> lib
         |      |----> configuration
         |      |----> deployments
         |      |----> tmp
         |      |----> data
         |      |----> log
         |      
         |---> domain
         |....
    

    As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.

    For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.

    Good luck!

    Access to build environment variables from a groovy script in a Jenkins build step (Windows)

    The Scriptler Groovy script doesn't seem to get all the environment variables of the build. But what you can do is force them in as parameters to the script:

    1. When you add the Scriptler build step into your job, select the option "Define script parameters"

    2. Add a parameter for each environment variable you want to pass in. For example "Name: JOB_NAME", "Value: $JOB_NAME". The value will get expanded from the Jenkins build environment using '$envName' type variables, most fields in the job configuration settings support this sort of expansion from my experience.

    3. In your script, you should have a variable with the same name as the parameter, so you can access the parameters with something like:

      println "JOB_NAME = $JOB_NAME"

    I haven't used Sciptler myself apart from some experimentation, but your question posed an interesting problem. I hope this helps!

    How to Resize image in Swift?

    Swift 4.2 version of @KiritModi answer

    func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
        let size = image.size
    
        let widthRatio  = targetSize.width  / size.width
        let heightRatio = targetSize.height / size.height
    
        var newSize: CGSize
        if(widthRatio > heightRatio) {
            newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize = CGSize(width: size.width * widthRatio, height: size.height *      widthRatio)
        }
    
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
    
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        image.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    
        return newImage!
    }
    

    Why can't I set text to an Android TextView?

    To settext in any of in activity than use this below code... Follow these step one by one:

    1.Declare

        private TextView event_post;
    

    2.Bind this

        event_post = (TextView) findViewById(R.id.text_post);
    

    3.SetText in

        event_post.setText(event_post_count);
    

    try/catch with InputMismatchException creates infinite loop

    another option is to define Scanner input = new Scanner(System.in); inside the try block, this will create a new object each time you need to re-enter the values.

    Is mathematics necessary for programming?

    I used a great deal of math when I was solving problems in solid mechanics and heat transfer using computers. Linear algebra, numerical methods, etc.

    I never tap into any of that knowledge now that I'm writing business applications that deliver information from relational databases to web-based user interfaces.

    I still would recommend a better math background to anyone.

    Discrete math is very helpful to a developer; I have no formal training in it.

    I think the techniques laid out in "Programming Collective Intelligence" are far from the stuff I did as an ME and could fall into the business apps that I'm doing now. Netflix has certainly made a nice business out of it. This group intelligence stuff appears to be on the rise.

    How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

    To point your apex/root/naked domain at a Heroku-hosted application, you'll need to use a DNS provider who supports CNAME-like records (often referred to as ALIAS or ANAME records). Currently Heroku recommends:

    Whichever of those you choose, your record will look like the following:

    Record: ALIAS or ANAME

    Name: empty or @

    Target: example.com.herokudns.com.

    That's all you need.


    However, it's not good for SEO to have both the www version and non-www version resolve. One should point to the other as the canonical URL. How you decide to do that depends on if you're using HTTPS or not. And if you're not, you probably should be as Heroku now handles SSL certificates for you automatically and for free for all applications running on paid dynos.

    If you're not using HTTPS, you can just set up a 301 Redirect record with most DNS providers pointing name www to http://example.com.

    If you are using HTTPS, you'll most likely need to handle the redirection at the application level. If you want to know why, check out these short and long explanations but basically since your DNS provider or other URL forwarding service doesn't have, and shouldn't have, your SSL certificate and private key, they can't respond to HTTPS requests for your domain.

    To handle the redirects at the application level, you'll need to:

    • Add both your apex and www host names to the Heroku application (heroku domains:add example.com and heroku domains:add www.example.com)
    • Set up your SSL certificates
    • Point your apex domain record at Heroku using an ALIAS or ANAME record as described above
    • Add a CNAME record with name www pointing to www.example.com.herokudns.com.
    • And then in your application, 301 redirect any www requests to the non-www URL (here's an example of how to do it in Django)
    • Also in your application, you should probably redirect any HTTP requests to HTTPS (for example, in Django set SECURE_SSL_REDIRECT to True)

    Check out this post from DNSimple for more.

    How do you run your own code alongside Tkinter's event loop?

    Use the after method on the Tk object:

    from tkinter import *
    
    root = Tk()
    
    def task():
        print("hello")
        root.after(2000, task)  # reschedule event in 2 seconds
    
    root.after(2000, task)
    root.mainloop()
    

    Here's the declaration and documentation for the after method:

    def after(self, ms, func=None, *args):
        """Call function once after given time.
    
        MS specifies the time in milliseconds. FUNC gives the
        function which shall be called. Additional parameters
        are given as parameters to the function call.  Return
        identifier to cancel scheduling with after_cancel."""
    

    What does print(... sep='', '\t' ) mean?

    sep='\t' is often used for Tab-delimited file.

    Why is it not advisable to have the database and web server on the same machine?

    On the other hand, referring to a different blogging Scott (Watermasyck, of Telligent) - they found that most users could speed up the websites (using Telligent's Community Server), by putting the database on the same machine as the web site. However, in their customer's case, usually the db & web server are the only applications on that machine, and the website isn't straining the machine that much. Then, the efficiency of not having to send data across the network more that made up for the increased strain.

    How to turn on WCF tracing?

    The following configuration taken from MSDN can be applied to enable tracing on your WCF service.

    <configuration>
      <system.diagnostics>
        <sources>
          <source name="System.ServiceModel"
                  switchValue="Information, ActivityTracing"
                  propagateActivity="true" >
            <listeners>
                 <add name="xml"/>
            </listeners>
          </source>
          <source name="System.ServiceModel.MessageLogging">
            <listeners>
                <add name="xml"/>
            </listeners>
          </source>
          <source name="myUserTraceSource"
                  switchValue="Information, ActivityTracing">
            <listeners>
                <add name="xml"/>
            </listeners>
          </source>
        </sources>
        <sharedListeners>
            <add name="xml"
                 type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="Error.svclog" />
        </sharedListeners>
      </system.diagnostics>
    </configuration>
    

    To view the log file, you can use "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe".

    If "SvcTraceViewer.exe" is not on your system, you can download it from the "Microsoft Windows SDK for Windows 7 and .NET Framework 4" package here:

    Windows SDK Download

    You don't have to install the entire thing, just the ".NET Development / Tools" part.

    When/if it bombs out during installation with a non-sensical error, Petopas' answer to Windows 7 SDK Installation Failure solved my issue.

    Setting Inheritance and Propagation flags with set-acl and powershell

    I think your answer can be found on this page. From the page:

    This Folder, Subfolders and Files:

    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit 
    PropagationFlags.None
    

    CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

    If you don't want to install the cors library and instead want to fix your original code, the other step you are missing is that Access-Control-Allow-Origin:* is wrong. When passing Authentication tokens (e.g. JWT) then you must explicitly state every url that is calling your server. You can't use "*" when doing authentication tokens.

    What is http multipart request?

    I have found an excellent and relatively short explanation here.

    A multipart request is a REST request containing several packed REST requests inside its entity.

    How to create batch file in Windows using "start" with a path and command with spaces

    start "" "c:\path with spaces\app.exe" "C:\path parameter\param.exe"
    

    When I used above suggestion, I've got:

    'c:\path' is not recognized a an internal or external command, operable program or batch file.

    I think second qoutation mark prevent command to run. After some search below solution save my day:

    start "" CALL "c:\path with spaces\app.exe" "C:\path parameter\param.exe"
    

    How to use a class object in C++ as a function parameter

    class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself.

    e.g.

    class ANewType
    {
        // ... details
    };
    

    This defines a new type called ANewType which is a class type.

    You can then use this in function declarations:

    void function(ANewType object);
    

    You can then pass objects of type ANewType into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.

    If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.

    void function(ANewType& object); // object passed by reference
    

    This syntax means that any use of object in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.

    [* The class keyword is also used in template definitions, but that's a different subject.]

    JQuery window scrolling event?

    See jQuery.scroll(). You can bind this to the window element to get your desired event hook.

    On scroll, then simply check your scroll position:

    $(window).scroll(function() {
      var scrollTop = $(window).scrollTop();
      if ( scrollTop > $(headerElem).offset().top ) { 
        // display add
      }
    });
    

    Uncaught TypeError: Cannot read property 'msie' of undefined

    $.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

    For Restful API, can GET method use json data?

    To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).

    I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1&param2=val2) or JSON (parsed by your API upon receipt)

    login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

    I faced the very same error when I was trying to connect to my SQL Server 2014 instance using sa user using SQL Server Management Studio (SSMS). I was facing this error even when security settings for sa user was all good and SQL authentication mode was enabled on the SQL Server instance.

    Finally, the issue turned out to be that Named Pipes protocol was disabled. Here is how you can enable it:

    Open SQL Server Configuration Manager application from start menu. Now, enable Named Pipes protocol for both Client Protocols and Protocols for <SQL Server Instance Name> nodes as shown in the snapshot below:

    enter image description here

    Note: Make sure you restart the SQL Server instance after making changes.

    P.S. I'm not very sure but there is a possibility that the Named Pipes enabling was required under only one of the two nodes that I've advised. So you can try it one after the other to reach to a more precise solution.

    How to set breakpoints in inline Javascript in Google Chrome?

    I know the Q is not about Firefox but I did not want to add a copy of this question to just answer it myself.

    For Firefox you need to add debugger; to be able to do what @matt-ball suggested for the script tag.

    So on your code, you add debugger above the line you want to debug and then you can add breakpoints. If you just set the breakpoints on the browser it won't stop.

    If this is not the place to add a Firefox answer given that the question is about Chrome. Don't :( minus the answer just let me know where I should post it and I'll happily move the post. :)

    How can I read comma separated values from a text file in Java?

    Use OpenCSV for reliability. Split should never be used for these kind of things. Here's a snippet from a program of my own, it's pretty straightforward. I check if a delimiter character was specified and use this one if it is, if not I use the default in OpenCSV (a comma). Then i read the header and fields

    CSVReader reader = null;
    try {
        if (delimiter > 0) {
            reader = new CSVReader(new FileReader(this.csvFile), this.delimiter);
        }
        else {
            reader = new CSVReader(new FileReader(this.csvFile));
        }
    
        // these should be the header fields
        header = reader.readNext();
        while ((fields = reader.readNext()) != null) {
            // more code
        }
    catch (IOException e) {
        System.err.println(e.getMessage());
    }
    

    How do I select the parent form based on which submit button is clicked?

    To get the form that the submit is inside why not just

    this.form
    

    Easiest & quickest path to the result.

    How to get current domain name in ASP.NET

    Using Request.Url.Host is appropriate - it's how you retrieve the value of the HTTP Host: header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.

    Note that localhost:5858 is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority.

    Furthermore, it is not valid to get somedomain.com from www.somedomain.com because a webserver could be configured to serve a different site for www.somedomain.com compared to somedomain.com, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.') works in a pinch.

    Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config) is a red-herring.

    Windows batch script to unhide files hidden by virus

    echo "Enter Drive letter" 
    set /p driveletter=
    
    attrib -s -h -a /s /d  %driveletter%:\*.*
    

    How do I horizontally center a span element inside a div

    I assume you want to center them on one line and not on two separate lines based on your fiddle. If that is the case, try the following css:

     div { background:red;
          overflow:hidden;
    }
    span { display:block;
           margin:0 auto;
           width:200px;
    }
    span a { padding:5px 10px;
             color:#fff;
             background:#222;
    }
    

    I removed the float since you want to center it, and then made the span surrounding the links centered by adding margin:0 auto to them. Finally, I added a static width to the span. This centers the links on one line within the red div.

    What's the best way to dedupe a table?

    For those of you who prefer a quick and dirty approach, just list all the columns that together define a unique record and create a unique index with those columns, like so:

    ALTER IGNORE TABLE TABLE_NAME ADD UNIQUE (column1,column2,column3)

    You can drop the unique index afterwords.

    How to execute INSERT statement using JdbcTemplate class from Spring Framework

    You'll need a datasource for working with JdbcTemplate.

    JdbcTemplate template = new JdbcTemplate(yourDataSource);
    
    template.update(
        new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection)
                throws SQLException {
    
                PreparedStatement statement = connection.prepareStatement(ourInsertQuery);
                //statement.setLong(1, beginning); set parameters you need in your insert
    
                return statement;
            }
        });
    

    How do I force Robocopy to overwrite files?

    This is really weird, why nobody is mentioning the /IM switch ?! I've been using it for a long time in backup jobs. But I tried googling just now and I couldn't land on a single web page that says anything about it even on MS website !!! Also found so many user posts complaining about the same issue!!

    Anyway.. to use Robocopy to overwrite EVERYTHING what ever size or time in source or distination you must include these three switches in your command (/IS /IT /IM)

    /IS :: Include Same files. (Includes same size files)
    /IT :: Include Tweaked files. (Includes same files with different Attributes)
    /IM :: Include Modified files (Includes same files with different times).
    

    This is the exact command I use to transfer few TeraBytes of mostly 1GB+ files (ISOs - Disk Images - 4K Videos):

    robocopy B:\Source D:\Destination /E /J /COPYALL /MT:1 /DCOPY:DATE /IS /IT /IM /X /V /NP /LOG:A:\ROBOCOPY.LOG
    

    I did a small test for you .. and here is the result:

                   Total    Copied   Skipped  Mismatch    FAILED    Extras
        Dirs :      1028      1028         0         0         0       169
       Files :      8053      8053         0         0         0         1
       Bytes : 649.666 g 649.666 g         0         0         0   1.707 g
       Times :   2:46:53   0:41:43                       0:00:00   0:41:44
    
    
       Speed :           278653398 Bytes/sec.
       Speed :           15944.675 MegaBytes/min.
       Ended : Friday, August 21, 2020 7:34:33 AM
    

    Dest, Disk: WD Gold 6TB (Compare the write speed with my result)

    Even with those "Extras", that's for reporting only because of the "/X" switch. As you can see nothing was Skipped and Total number and size of all files are equal to the Copied. Sometimes It will show small number of skipped files when I abuse it and cancel it multiple times during operation but even with that the values in the first 2 columns are always Equal. I also confirmed that once before by running a PowerShell script that scans all files in destination and generate a report of all time-stamps.

    Some performance tips from my history with it and so many tests & troubles!:

    . Despite of what most users online advise to use maximum threads "/MT:128" like it's a general trick to get the best performance ... PLEASE DON'T USE "/MT:128" WITH VERY LARGE FILES ... that's a big mistake and it will decrease your drive performance dramatically after several runs .. it will create very high fragmentation or even cause the files system to fail in some cases and you end up spending valuable time trying to recover a RAW partition and all that nonsense. And above all that, It will perform 4-6 times slower!!

    For very large files:

    1. Use Only "One" thread "/MT:1" | Impact: BIG
    2. Must use "/J" to disable buffering. | Impact: High
    3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: Medium.
    4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: Low.

    For regular big files:

    1. Use multi threads, I would not exceed "/MT:4" | Impact: BIG
    2. IF destination disk has low Cache specs use "/J" to disable buffering | Impact: High
    3. & 4 same as above.

    For thousands of tiny files:

    1. Go nuts :) with Multi threads, at first I would start with 16 and multibly by 2 while monitoring the disk performance. Once it starts dropping I'll fall back to the prevouse value and stik with it | Impact: BIG
    2. Don't use "/J" | Impact: High
    3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: HIGH.
    4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: HIGH.

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

    maxAge = Persons.Max(c => c.age)
    

    or something along those lines.

    Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

    If you have the correct encoding in the string, you need not do more to get the bytes for another encoding.

    public static void main(String[] args) throws Exception {
        printBytes("â");
        System.out.println(
                new String(new byte[] { (byte) 0xE2 }, "ISO-8859-1"));
        System.out.println(
                new String(new byte[] { (byte) 0xC3, (byte) 0xA2 }, "UTF-8"));
    }
    
    private static void printBytes(String str) {
        System.out.println("Bytes in " + str + " with ISO-8859-1");
        for (byte b : str.getBytes(StandardCharsets.ISO_8859_1)) {
            System.out.printf("%3X", b);
        }
        System.out.println();
        System.out.println("Bytes in " + str + " with UTF-8");
        for (byte b : str.getBytes(StandardCharsets.UTF_8)) {
            System.out.printf("%3X", b);
        }
        System.out.println();
    }
    

    Output:

    Bytes in â with ISO-8859-1
     E2
    Bytes in â with UTF-8
     C3 A2
    â
    â
    

    Create normal zip file programmatically

    You can now use the ZipArchive class (System.IO.Compression.ZipArchive), available from .NET 4.5

    You have to add System.IO.Compression as a reference.

    Example: Generating a zip of PDF files

    using (var fileStream = new FileStream(@"C:\temp\temp.zip", FileMode.CreateNew))
    {
        using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
        {
            foreach (var creditNumber in creditNumbers)
            {
                var pdfBytes = GeneratePdf(creditNumber);
                var fileName = "credit_" + creditNumber + ".pdf";
                var zipArchiveEntry = archive.CreateEntry(fileName, CompressionLevel.Fastest);
                using (var zipStream = zipArchiveEntry.Open())
                    zipStream.Write(pdfBytes, 0, pdfBytes.Length);
                }
            }
        }
    }
    

    Git Symlinks in Windows

    I use sym links all the time between my document root and git repo directory. I like to keep them separate. On windows I use mklink /j option. The junction seems to let git behave normally:

    >mklink /j <location(path) of link> <source of link>

    for example:

    >mklink /j c:\gitRepos\Posts C:\Bitnami\wamp\apache2\htdocs\Posts

    How do I find out what all symbols are exported from a shared object?

    Do you have a "shared object" (usually a shared library on AIX), a UNIX shared library, or a Windows DLL? These are all different things, and your question conflates them all :-(

    • For an AIX shared object, use dump -Tv /path/to/foo.o.
    • For an ELF shared library, use readelf -Ws /path/to/libfoo.so, or (if you have GNU nm) nm -D /path/to/libfoo.so.
    • For a non-ELF UNIX shared library, please state which UNIX you are interested in.
    • For a Windows DLL, use dumpbin /EXPORTS foo.dll.

    iPhone and WireShark

    You can proceed as follow:

    1. Install Charles Web Proxy.
    2. Disable SSL proxying (uncheck the flag in Proxy->Proxy Settings...->SSL
    3. Connect your iDevice to the Charles proxy, as explained here
    4. Sniff the packets via Wireshark or Charles

    Cannot convert lambda expression to type 'string' because it is not a delegate type

    My case it solved i was using

    @Html.DropDownList(model => model.TypeId ...)  
    

    using

    @Html.DropDownListFor(model => model.TypeId ...) 
    

    will solve it

    How do I simulate a hover with a touch in touch enabled browsers?

    A mix of native Javascript and jQuery:

    var gFireEvent = function (oElem,sEvent) 
    {
     try {
     if( typeof sEvent == 'string' && o.isDOM( oElem ))
     {
      var b = !!(document.createEvent),
         evt = b?document.createEvent("HTMLEvents"):document.createEventObject();
      if( b )    
      {  evt.initEvent(sEvent, true, true ); 
        return !oElem.dispatchEvent(evt);
      }
      return oElem.fireEvent('on'+sEvent,evt);
     }
     } catch(e) {}
     return false;
    };
    
    
    // Next you can do is (bIsMob etc you have to determine yourself):
    
       if( <<< bIsMob || bIsTab || bisTouch >>> )
       {
         $(document).on('mousedown', function(e)
         {
           gFireEvent(e.target,'mouseover' );
         }).on('mouseup', function(e)
         {
           gFireEvent(e.target,'mouseout' );
         });
       }
    

    get original element from ng-click

    You need $event.currentTarget instead of $event.target.

    Relational Database Design Patterns?

    Your question is a bit vague, but I suppose UPSERT could be considered a design pattern. For languages that don't implement MERGE, a number of alternatives to solve the problem (if a suitable rows exists, UPDATE; else INSERT) exist.

    How to Generate a random number of fixed length using JavaScript?

    parseInt(Math.random().toString().slice(2,Math.min(length+2, 18)), 10); // 18 -> due to max digits in Math.random

    Update: This method has few flaws: - Sometimes the number of digits might be lesser if its left padded with zeroes.

    How do you find the current user in a Windows environment?

    As far as find BlueBearr response the best (while I,m running my batch script with eg. SYSTEM rights) I have to add something to it. Because in my Windows language version (Polish) line that is to be catched by "%%a %%b"=="User Name:" gets REALLY COMPLICATED (it contains some diacritic characters in my language) I skip first 7 lines and operate on the 8th.

    @for /f "SKIP= 7 TOKENS=3,4 DELIMS=\ " %%G in ('tasklist /FI "IMAGENAME eq explorer.exe" /FO LIST /V') do @IF %%G==%COMPUTERNAME% set _currdomain_user=%%H
    

    PyTorch: How to get the shape of a Tensor as a list of int

    Previous answers got you list of torch.Size Here is how to get list of ints

    listofints = [int(x) for x in tensor.shape]
    

    HTML5 Video tag not working in Safari , iPhone and iPad

    Working around for few days into the same problem (and after check "playsinline" and "autoplay" and "muted" ok, "mime-types" and "range" in server ok, etc). The solution for all browsers was:

    <video controls autoplay loop muted playsinline>
        <source src="https://example.com/my_video.mov" type="video/mp4">
    </video>
    

    Yes: convert video to .MOV and type="video/mp4" in the same tag. Working!

    Printing a java map Map<String, Object> - How?

    I'm sure there's some nice library that does this sort of thing already for you... But to just stick with the approach you're already going with, Map#entrySet gives you a combined Object with the key and the value. So something like:

    for (Map.Entry<String, Object> entry : map.entrySet()) {
        System.out.println(entry.getKey() + ":" + entry.getValue().toString());
    }
    

    will do what you're after.


    If you're using java 8, there's also the new streaming approach.

    map.forEach((key, value) -> System.out.println(key + ":" + value));
    

    CSS-moving text from left to right

    You could simply use CSS animated text generator. There are pre-created templates already

    Convert column classes in data.table

    I provide a more general and safer way to do this stuff,

    ".." <- function (x) 
    {
      stopifnot(inherits(x, "character"))
      stopifnot(length(x) == 1)
      get(x, parent.frame(4))
    }
    
    
    set_colclass <- function(x, class){
      stopifnot(all(class %in% c("integer", "numeric", "double","factor","character")))
      for(i in intersect(names(class), names(x))){
        f <- get(paste0("as.", class[i]))
        x[, (..("i")):=..("f")(get(..("i")))]
      }
      invisible(x)
    }
    

    The function .. makes sure we get a variable out of the scope of data.table; set_colclass will set the classes of your cols. You can use it like this:

    dt <- data.table(i=1:3,f=3:1)
    set_colclass(dt, c(i="character"))
    class(dt$i)
    

    How to make a Python script run like a service or daemon in Linux

    You have two options here.

    1. Make a proper cron job that calls your script. Cron is a common name for a GNU/Linux daemon that periodically launches scripts according to a schedule you set. You add your script into a crontab or place a symlink to it into a special directory and the daemon handles the job of launching it in the background. You can read more at Wikipedia. There is a variety of different cron daemons, but your GNU/Linux system should have it already installed.

    2. Use some kind of python approach (a library, for example) for your script to be able to daemonize itself. Yes, it will require a simple event loop (where your events are timer triggering, possibly, provided by sleep function).

    I wouldn't recommend you to choose 2., because you would be, in fact, repeating cron functionality. The Linux system paradigm is to let multiple simple tools interact and solve your problems. Unless there are additional reasons why you should make a daemon (in addition to trigger periodically), choose the other approach.

    Also, if you use daemonize with a loop and a crash happens, no one will check the mail after that (as pointed out by Ivan Nevostruev in comments to this answer). While if the script is added as a cron job, it will just trigger again.

    How to deploy a war file in Tomcat 7

    If you installed tomcat7 using apt-get in linux then, deploy your app to /var/lib/tomcat7/webapps/

    eg.

    sudo service tomcat7 stop
    
    mvn clean package
    sudo cp target/DestroyTheWorldWithPeace.war /var/lib/tomcat7/webapps/
    #you might also want to make sure war file has permission (`777` not just `+x`)
    sudo service tomcat7 start
    

    Also, keep tailing the tomcat log so that you can verify that your app is actually making peace with tomcat.

    tail -f /var/lib/tomcat7/logs/catalina.out
    

    The deployed application should appear in http://172.16.35.155:8080/manager/html

    Java generics - ArrayList initialization

    Think of the ? as to mean "unknown". Thus, "ArrayList<? extends Object>" is to say "an unknown type that (or as long as it)extends Object". Therefore, needful to say, arrayList.add(3) would be putting something you know, into an unknown. I.e 'Forgetting'.

    How do you stash an untracked file?

    Updated Answer In 2020

    I was surprised that no other answers on this page mentioned git stash push.

    This article helped me understand:

    The command git stash is shorthand for git stash push. In this mode, non-option arguments are not allowed to prevent a misspelled subcommand from making an unwanted stash entry. There are also another alias for this command git stash save which is deprecated in favour of git stash push.

    By default git ignores untracked files when doing stash. If those files need to be added to stash you can use -u options which tells git to include untracked files. Ignored files can be added as well if -a option is specified. -a will include both untracked and ignored files.

    I care about naming my stashes, and I want them to include untracked files, so the command I most commonly run is: git stash push -u -m "whatIWantToNameThisStash"

    How can I avoid ResultSet is closed exception in Java?

    I got same error everything was correct only i was using same statement interface object to execute and update the database. After separating i.e. using different objects of statement interface for updating and executing query i resolved this error. i.e. do get rid from this do not use same statement object for both updating and executing the query.

    How to auto resize and adjust Form controls with change in resolution

    Here I like to use https://www.netresize.net/index.php?c=3a&id=11#buyopt. But it is paid version.

    You also can get their source codes if you buy 1 Site License (Unlimited Developers).

    How ever I am finding the nuget package solution.

    What do column flags mean in MySQL Workbench?

    This exact question is answered on mySql workbench-faq:

    Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.

    That means hover over an acronym in the mySql Workbench table editor.

    Section 8.1.11.2, “The Columns Tab”

    Remove "Using default security password" on Spring Boot

    If you have enabled actuator feature (spring-boot-starter-actuator), additional exclude should be added in application.yml:

    spring:
      autoconfigure:
        exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration
    

    Tested in Spring Boot version 2.3.4.RELEASE.

    C# Help reading foreign characters using StreamReader

    I'm also reading an exported file which contains french and German languages. I used Encoding.GetEncoding("iso-8859-1"), true which worked out without any challenges.

    Calling a user defined function in jQuery

    jQuery.fn.clear = function()
    {
        var $form = $(this);
    
        $form.find('input:text, input:password, input:file, textarea').val('');
        $form.find('select option:selected').removeAttr('selected');
        $form.find('input:checkbox, input:radio').removeAttr('checked');
    
        return this;
    }; 
    
    
    $('#my-form').clear();
    

    OAuth2 and Google API: access token expiration time?

    The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

    Check substring exists in a string in C

    My own humble (case sensitive) solution:

    uint8_t strContains(char* string, char* toFind)
    {
        uint8_t slen = strlen(string);
        uint8_t tFlen = strlen(toFind);
        uint8_t found = 0;
    
        if( slen >= tFlen )
        {
            for(uint8_t s=0, t=0; s<slen; s++)
            {
                do{
    
                    if( string[s] == toFind[t] )
                    {
                        if( ++found == tFlen ) return 1;
                        s++;
                        t++;
                    }
                    else { s -= found; found=0; t=0; }
    
                  }while(found);
            }
            return 0;
        }
        else return -1;
    }
    

    Results

    strContains("this is my sample example", "th") // 1
    strContains("this is my sample example", "sample") // 1
    strContains("this is my sample example", "xam") // 1
    strContains("this is my sample example", "ple") // 1
    strContains("this is my sample example", "ssample") // 0
    strContains("this is my sample example", "samplee") // 0
    strContains("this is my sample example", "") // 0
    strContains("str", "longer sentence") // -1
    strContains("ssssssample", "sample") // 1
    strContains("sample", "sample") // 1
    

    Tested on ATmega328P (avr8-gnu-toolchain-3.5.4.1709) ;)

    How to add a bot to a Telegram Group?

    You have to use @BotFather, send it command: /setjoingroups There will be dialog like this:

    YOU: /setjoingroups

    BotFather: Choose a bot to change group membership settings.

    YOU: @YourBot

    BotFather: 'Enable' - bot can be added to groups. 'Disable' - block group invitations, the bot can't be added to groups. Current status is: DISABLED

    YOU: Enable

    BotFather: Success! The new status is: ENABLED.

    After this you will see button "Add to Group" in your bot's profile.

    Get loop counter/index using for…of syntax in JavaScript

    That's my version of a composite iterator that yields an index and any passed generator function's value with an example of (slow) prime search:

    _x000D_
    _x000D_
    const eachWithIndex = (iterable) => {_x000D_
      return {_x000D_
        *[Symbol.iterator]() {_x000D_
          let i = 0_x000D_
          for(let val of iteratable) {_x000D_
            i++_x000D_
              yield [i, val]_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    _x000D_
    }_x000D_
    _x000D_
    const isPrime = (n) => {_x000D_
      for (i = 2; i < Math.floor(Math.sqrt(n) + 1); i++) {_x000D_
        if (n % i == 0) {_x000D_
          return false_x000D_
        }_x000D_
      }_x000D_
      return true_x000D_
    }_x000D_
    _x000D_
    let primes = {_x000D_
      *[Symbol.iterator]() {_x000D_
        let candidate = 2_x000D_
        while (true) {_x000D_
          if (isPrime(candidate)) yield candidate_x000D_
            candidate++_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    for (const [i, prime] of eachWithIndex(primes)) {_x000D_
      console.log(i, prime)_x000D_
      if (i === 100) break_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    How to create an empty array in PHP with predefined size?

    PHP provides two types of array.

    • normal array
    • SplFixedArray

    normal array : This array is dynamic.

    SplFixedArray : this is a standard php library which provides the ability to create array of fix size.

    Swipe to Delete and the "More" button (like in Mail app on iOS 7)

    To improve on Johnny's answer, this can now be done using the public API as follows :

    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
    
        let moreRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "More", handler:{action, indexpath in
            print("MORE•ACTION");
        });
        moreRowAction.backgroundColor = UIColor(red: 0.298, green: 0.851, blue: 0.3922, alpha: 1.0);
    
        let deleteRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Delete", handler:{action, indexpath in
            print("DELETE•ACTION");
        });
    
        return [deleteRowAction, moreRowAction];
    }
    

    How to install and use "make" in Windows?

    1. Install Msys2 http://www.msys2.org
    2. Follow installation instructions
    3. Install make with $ pacman -S make gettext base-devel
    4. Add C:\msys64\usr\bin\ to your path

    jQuery Validate - Enable validation for hidden fields

    Just added ignore: [] in the specific page for the specific form, this solution worked for me.

    $("#form_name").validate({
            ignore: [],
            onkeyup: false,
            rules: {            
            },      
            highlight:false,
        });
    

    How do I check if a PowerShell module is installed?

    When I use a non-default modules in my scripts I call the function below. Beside the module name you can provide a minimum version.

    # See https://www.powershellgallery.com/ for module and version info
    Function Install-ModuleIfNotInstalled(
        [string] [Parameter(Mandatory = $true)] $moduleName,
        [string] $minimalVersion
    ) {
        $module = Get-Module -Name $moduleName -ListAvailable |`
            Where-Object { $null -eq $minimalVersion -or $minimalVersion -ge $_.Version } |`
            Select-Object -Last 1
        if ($null -ne $module) {
             Write-Verbose ('Module {0} (v{1}) is available.' -f $moduleName, $module.Version)
        }
        else {
            Import-Module -Name 'PowershellGet'
            $installedModule = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue
            if ($null -ne $installedModule) {
                Write-Verbose ('Module [{0}] (v {1}) is installed.' -f $moduleName, $installedModule.Version)
            }
            if ($null -eq $installedModule -or ($null -ne $minimalVersion -and $installedModule.Version -lt $minimalVersion)) {
                Write-Verbose ('Module {0} min.vers {1}: not installed; check if nuget v2.8.5.201 or later is installed.' -f $moduleName, $minimalVersion)
                #First check if package provider NuGet is installed. Incase an older version is installed the required version is installed explicitly
                if ((Get-PackageProvider -Name NuGet -Force).Version -lt '2.8.5.201') {
                    Write-Warning ('Module {0} min.vers {1}: Install nuget!' -f $moduleName, $minimalVersion)
                    Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope CurrentUser -Force
                }        
                $optionalArgs = New-Object -TypeName Hashtable
                if ($null -ne $minimalVersion) {
                    $optionalArgs['RequiredVersion'] = $minimalVersion
                }  
                Write-Warning ('Install module {0} (version [{1}]) within scope of the current user.' -f $moduleName, $minimalVersion)
                Install-Module -Name $moduleName @optionalArgs -Scope CurrentUser -Force -Verbose
            } 
        }
    }
    

    usage example:

    Install-ModuleIfNotInstalled 'CosmosDB' '2.1.3.528'
    

    Please let me known if it's usefull (or not)

    How do I find the time difference between two datetime objects in python?

    I have used time differences for continuous integration tests to check and improve my functions. Here is simple code if somebody need it

    from datetime import datetime
    
    class TimeLogger:
        time_cursor = None
    
        def pin_time(self):
            global time_cursor
            time_cursor = datetime.now()
    
        def log(self, text=None) -> float:
            global time_cursor
    
            if not time_cursor:
                time_cursor = datetime.now()
    
            now = datetime.now()
            t_delta = now - time_cursor
    
            seconds = t_delta.total_seconds()
    
            result = str(now) + ' tl -----------> %.5f' % seconds
            if text:
                result += "   " + text
            print(result)
    
            self.pin_time()
    
            return seconds
    
    
    time_logger = TimeLogger()
    

    Using:

    from .tests_time_logger import time_logger
    class Tests(TestCase):
        def test_workflow(self):
        time_logger.pin_time()
    
        ... my functions here ...
    
        time_logger.log()
    
        ... other function(s) ...
    
        time_logger.log(text='Tests finished')
    

    and i have something like that in log output

    2019-12-20 17:19:23.635297 tl -----------> 0.00007
    2019-12-20 17:19:28.147656 tl -----------> 4.51234   Tests finished
    

    How to make a new line or tab in <string> XML (eclipse/android)?

    Use \t to add tab and \n for new line, here is a simple example below.

    <string name="list_with_tab_tag">\tbanana\torange\tblueberry\tmango</string>
    <string name="sentence_with_new_line_tag">This is the first sentence\nThis is the second scentence\nThis is the third sentence</string>
    

    How do I iterate through children elements of a div using jQuery?

    children() is a loop in itself.

    $('.element').children().animate({
    'opacity':'0'
    });
    

    Windows Forms ProgressBar: Easiest way to start/stop marquee?

    Many good answers here already, although you also need to keep in mind that if you are doing long-running processing on the UI thread (generally a bad idea), then you won't see the marquee moving either.

    In Python, how do I loop through the dictionary and change the value if it equals something?

    for k, v in mydict.iteritems():
        if v is None:
            mydict[k] = ''
    

    In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems.

    In Python3 however the code gives AttributeError: 'dict' object has no attribute 'iteritems' error. Use items() instead of iteritems() here.

    Refer to this post.

    How to use double or single brackets, parentheses, curly braces

    Brackets

    if [ CONDITION ]    Test construct  
    if [[ CONDITION ]]  Extended test construct  
    Array[1]=element1   Array initialization  
    [a-z]               Range of characters within a Regular Expression
    $[ expression ]     A non-standard & obsolete version of $(( expression )) [1]
    

    [1] http://wiki.bash-hackers.org/scripting/obsolete

    Curly Braces

    ${variable}                             Parameter substitution  
    ${!variable}                            Indirect variable reference  
    { command1; command2; . . . commandN; } Block of code  
    {string1,string2,string3,...}           Brace expansion  
    {a..z}                                  Extended brace expansion  
    {}                                      Text replacement, after find and xargs
    

    Parentheses

    ( command1; command2 )             Command group executed within a subshell  
    Array=(element1 element2 element3) Array initialization  
    result=$(COMMAND)                  Command substitution, new style  
    >(COMMAND)                         Process substitution  
    <(COMMAND)                         Process substitution 
    

    Double Parentheses

    (( var = 78 ))            Integer arithmetic   
    var=$(( 20 + 5 ))         Integer arithmetic, with variable assignment   
    (( var++ ))               C-style variable increment   
    (( var-- ))               C-style variable decrement   
    (( var0 = var1<98?9:21 )) C-style ternary operation
    

    How to create a list of objects?

    Storing a list of object instances is very simple

    class MyClass(object):
        def __init__(self, number):
            self.number = number
    
    my_objects = []
    
    for i in range(100):
        my_objects.append(MyClass(i))
    
    # later
    
    for obj in my_objects:
        print obj.number
    

    How to restart ADB manually from Android Studio

    AndroidStudio:

    Go to: Tools -> Android -> Android Device Monitor

    see the Device tab, under many icons, last one is drop-down arrow.

    Open it.

    At the bottom: RESET ADB.

    Filter Excel pivot table using VBA

    I think i am understanding your question. This filters things that are in the column labels or the row labels. The last 2 sections of the code is what you want but im pasting everything so that you can see exactly how It runs start to finish with everything thats defined etc. I definitely took some of this code from other sites fyi.

    Near the end of the code, the "WardClinic_Category" is a column of my data and in the column label of the pivot table. Same for the IVUDDCIndicator (its a column in my data but in the row label of the pivot table).

    Hope this helps others...i found it very difficult to find code that did this the "proper way" rather than using code similar to the macro recorder.

    Sub CreatingPivotTableNewData()
    
    
    'Creating pivot table
    Dim PvtTbl As PivotTable
    Dim wsData As Worksheet
    Dim rngData As Range
    Dim PvtTblCache As PivotCache
    Dim wsPvtTbl As Worksheet
    Dim pvtFld As PivotField
    
    'determine the worksheet which contains the source data
    Set wsData = Worksheets("Raw_Data")
    
    'determine the worksheet where the new PivotTable will be created
    Set wsPvtTbl = Worksheets("3N3E")
    
    'delete all existing Pivot Tables in the worksheet
    'in the TableRange1 property, page fields are excluded; to select the entire PivotTable report, including the page fields, use the TableRange2 property.
    For Each PvtTbl In wsPvtTbl.PivotTables
    If MsgBox("Delete existing PivotTable!", vbYesNo) = vbYes Then
    PvtTbl.TableRange2.Clear
    End If
    Next PvtTbl
    
    
    'A Pivot Cache represents the memory cache for a PivotTable report. Each Pivot Table report has one cache only. Create a new PivotTable cache, and then create a new PivotTable report based on the cache.
    
    'set source data range:
    Worksheets("Raw_Data").Activate
    Set rngData = wsData.Range(Range("A1"), Range("H1").End(xlDown))
    
    
    'Creates Pivot Cache and PivotTable:
    Worksheets("Raw_Data").Activate
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData.Address, Version:=xlPivotTableVersion12).CreatePivotTable TableDestination:=wsPvtTbl.Range("A1"), TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12
    Set PvtTbl = wsPvtTbl.PivotTables("PivotTable1")
    
    'Default value of ManualUpdate property is False so a PivotTable report is recalculated automatically on each change.
    'Turn this off (turn to true) to speed up code.
    PvtTbl.ManualUpdate = True
    
    
    'Adds row and columns for pivot table
    PvtTbl.AddFields RowFields:="VerifyHr", ColumnFields:=Array("WardClinic_Category", "IVUDDCIndicator")
    
    'Add item to the Report Filter
    PvtTbl.PivotFields("DayOfWeek").Orientation = xlPageField
    
    
    'set data field - specifically change orientation to a data field and set its function property:
    With PvtTbl.PivotFields("TotalVerified")
    .Orientation = xlDataField
    .Function = xlAverage
    .NumberFormat = "0.0"
    .Position = 1
    End With
    
    'Removes details in the pivot table for each item
    Worksheets("3N3E").PivotTables("PivotTable1").PivotFields("WardClinic_Category").ShowDetail = False
    
    'Removes pivot items from pivot table except those cases defined below (by looping through)
    For Each PivotItem In PvtTbl.PivotFields("WardClinic_Category").PivotItems
        Select Case PivotItem.Name
            Case "3N3E"
                PivotItem.Visible = True
            Case Else
                PivotItem.Visible = False
            End Select
        Next PivotItem
    
    
    'Removes pivot items from pivot table except those cases defined below (by looping through)
    For Each PivotItem In PvtTbl.PivotFields("IVUDDCIndicator").PivotItems
        Select Case PivotItem.Name
            Case "UD", "IV"
                PivotItem.Visible = True
            Case Else
                PivotItem.Visible = False
            End Select
        Next PivotItem
    
    'turn on automatic update / calculation in the Pivot Table
    PvtTbl.ManualUpdate = False
    
    
    End Sub
    

    How to set width of mat-table column in angular?

    we can add attribute width directly to th

    eg:

    <ng-container matColumnDef="position" >
        <th mat-header-cell *matHeaderCellDef width ="20%"> No. </th>
        <td mat-cell *matCellDef="let element"> {{element.position}} </td>
      </ng-container>
    

    Python: Adding element to list while iterating

    Expanding S.Lott's answer so that new items are processed as well:

    todo = myarr
    done = []
    while todo:
        added = []
        for a in todo:
            if somecond(a):
                added.append(newObj())
        done.extend(todo)
        todo = added
    

    The final list is in done.

    How to remove duplicates from a list?

    Does Customer implement the equals() contract?

    If it doesn't implement equals() and hashCode(), then listCustomer.contains(customer) will check to see if the exact same instance already exists in the list (By instance I mean the exact same object--memory address, etc). If what you are looking for is to test whether or not the same Customer( perhaps it's the same customer if they have the same customer name, or customer number) is in the list already, then you would need to override equals() to ensure that it checks whether or not the relevant fields(e.g. customer names) match.

    Note: Don't forget to override hashCode() if you are going to override equals()! Otherwise, you might get trouble with your HashMaps and other data structures. For a good coverage of why this is and what pitfalls to avoid, consider having a look at Josh Bloch's Effective Java chapters on equals() and hashCode() (The link only contains iformation about why you must implement hashCode() when you implement equals(), but there is good coverage about how to override equals() too).

    By the way, is there an ordering restriction on your set? If there isn't, a slightly easier way to solve this problem is use a Set<Customer> like so:

    Set<Customer> noDups = new HashSet<Customer>();
    noDups.addAll(tmpListCustomer);
    return new ArrayList<Customer>(noDups);
    

    Which will nicely remove duplicates for you, since Sets don't allow duplicates. However, this will lose any ordering that was applied to tmpListCustomer, since HashSet has no explicit ordering (You can get around that by using a TreeSet, but that's not exactly related to your question). This can simplify your code a little bit.

    Android, Java: HTTP POST Request

    HTTP request POST in java does not dump the answer?

    public class HttpClientExample 
    {
     private final String USER_AGENT = "Mozilla/5.0";
     public static void main(String[] args) throws Exception 
     {
    
    HttpClientExample http = new HttpClientExample();
    
    System.out.println("\nTesting 1 - Send Http POST request");
    http.sendPost();
    
    }
    
     // HTTP POST request
     private void sendPost() throws Exception {
     String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
    
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    
    // add header
    post.setHeader("User-Agent", USER_AGENT);
    
    List<NameValuePair> urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
            urlParameters.add(new BasicNameValuePair("modo", "1"));
    urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
    
    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    
    HttpResponse response = client.execute(post);
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());
    System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
    
     BufferedReader rd = new BufferedReader(new 
     InputStreamReader(response.getEntity().getContent()));
    
      StringBuilder result = new StringBuilder();
      String line = "";
      while ((line = rd.readLine()) != null) 
            {
          result.append(line);
                    System.out.println(line);
        }
    
       }
     }
    

    This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!

    How to change port number in vue-cli project

    First Option:

    OPEN package.json and add "--port port-no" in "serve" section.

    Just like below, I have done it.

    {
      "name": "app-name",
      "version": "0.1.0",
      "private": true,
      "scripts": {
        "serve": "vue-cli-service serve --port 8090",
        "build": "vue-cli-service build",
        "lint": "vue-cli-service lint"
    }
    

    Second Option: If You want through command prompt

    npm run serve --port 8090

    How to get the last element of a slice?

    For just reading the last element of a slice:

    sl[len(sl)-1]
    

    For removing it:

    sl = sl[:len(sl)-1]
    

    See this page about slice tricks

    Set the layout weight of a TextView programmatically

    The answer is that you have to use TableRow.LayoutParams, not LinearLayout.LayoutParams or any other LayoutParams.

    TextView tv = new TextView(v.getContext());
    LayoutParams params = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
    tv.setLayoutParams(params);
    

    The different LayoutParams are not interchangeable and if you use the wrong one then nothing seems to happen. The text view's parent is a table row, hence:

    http://developer.android.com/reference/android/widget/TableRow.LayoutParams.html

    How can I read and parse CSV files in C++?

    I wrote a nice way of parsing CSV files and I thought I should add it as an answer:

    #include <algorithm>
    #include <fstream>
    #include <iostream>
    #include <stdlib.h>
    #include <stdio.h>
    
    struct CSVDict
    {
      std::vector< std::string > inputImages;
      std::vector< double > inputLabels;
    };
    
    /**
    \brief Splits the string
    
    \param str String to split
    \param delim Delimiter on the basis of which splitting is to be done
    \return results Output in the form of vector of strings
    */
    std::vector<std::string> stringSplit( const std::string &str, const std::string &delim )
    {
      std::vector<std::string> results;
    
      for (size_t i = 0; i < str.length(); i++)
      {
        std::string tempString = "";
        while ((str[i] != *delim.c_str()) && (i < str.length()))
        {
          tempString += str[i];
          i++;
        }
        results.push_back(tempString);
      }
    
      return results;
    }
    
    /**
    \brief Parse the supplied CSV File and obtain Row and Column information. 
    
    Assumptions:
    1. Header information is in first row
    2. Delimiters are only used to differentiate cell members
    
    \param csvFileName The full path of the file to parse
    \param inputColumns The string of input columns which contain the data to be used for further processing
    \param inputLabels The string of input labels based on which further processing is to be done
    \param delim The delimiters used in inputColumns and inputLabels
    \return Vector of Vector of strings: Collection of rows and columns
    */
    std::vector< CSVDict > parseCSVFile( const std::string &csvFileName, const std::string &inputColumns, const std::string &inputLabels, const std::string &delim )
    {
      std::vector< CSVDict > return_CSVDict;
      std::vector< std::string > inputColumnsVec = stringSplit(inputColumns, delim), inputLabelsVec = stringSplit(inputLabels, delim);
      std::vector< std::vector< std::string > > returnVector;
      std::ifstream inFile(csvFileName.c_str());
      int row = 0;
      std::vector< size_t > inputColumnIndeces, inputLabelIndeces;
      for (std::string line; std::getline(inFile, line, '\n');)
      {
        CSVDict tempDict;
        std::vector< std::string > rowVec;
        line.erase(std::remove(line.begin(), line.end(), '"'), line.end());
        rowVec = stringSplit(line, delim);
    
        // for the first row, record the indeces of the inputColumns and inputLabels
        if (row == 0)
        {
          for (size_t i = 0; i < rowVec.size(); i++)
          {
            for (size_t j = 0; j < inputColumnsVec.size(); j++)
            {
              if (rowVec[i] == inputColumnsVec[j])
              {
                inputColumnIndeces.push_back(i);
              }
            }
            for (size_t j = 0; j < inputLabelsVec.size(); j++)
            {
              if (rowVec[i] == inputLabelsVec[j])
              {
                inputLabelIndeces.push_back(i);
              }
            }
          }
        }
        else
        {
          for (size_t i = 0; i < inputColumnIndeces.size(); i++)
          {
            tempDict.inputImages.push_back(rowVec[inputColumnIndeces[i]]);
          }
          for (size_t i = 0; i < inputLabelIndeces.size(); i++)
          {
            double test = std::atof(rowVec[inputLabelIndeces[i]].c_str());
            tempDict.inputLabels.push_back(std::atof(rowVec[inputLabelIndeces[i]].c_str()));
          }
          return_CSVDict.push_back(tempDict);
        }
        row++;
      }
    
      return return_CSVDict;
    }
    

    The Definitive C Book Guide and List

    Beginner

    Introductory, no previous programming experience

    • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

      * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

    • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

    Introductory, with previous programming experience

    • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

    • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

    Best practices

    • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

    • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

    • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


    Intermediate

    • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

    • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

    • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

    • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

    • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

    • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

    • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

    • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

    • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

    • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


    Advanced

    • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

    • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

    • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

    • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


    Reference Style - All Levels

    • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

    • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

    • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

    C++11/14/17/… References:

    • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

    • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

    • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

    • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

    • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

    • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


    Classics / Older

    Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

    • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

    • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

    • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

    • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

    • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

    • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

    • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

    • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

    how can I display tooltip or item information on mouse over?

    The title attribute works on most HTML tags and is widely supported by modern browsers.

    How to align linearlayout to vertical center?

    For me, I have fixed the problem using android:layout_centerVertical="true" in a parent RelativeLayout:

    <RelativeLayout ... >
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_centerVertical="true">
    
    </RelativeLayout>
    

    Using prepared statements with JDBCTemplate

    class Main {
        public static void main(String args[]) throws Exception {
            ApplicationContext ac = new
              ClassPathXmlApplicationContext("context.xml", Main.class);
            DataSource dataSource = (DataSource) ac.getBean("dataSource");
    // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");
    
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    
            String prasobhName = 
            jdbcTemplate.query(
               "select first_name from customer where last_name like ?",
                new PreparedStatementSetter() {
                  public void setValues(PreparedStatement preparedStatement) throws
                    SQLException {
                      preparedStatement.setString(1, "nair%");
                  }
                }, 
                new ResultSetExtractor<Long>() {
                  public Long extractData(ResultSet resultSet) throws SQLException,
                    DataAccessException {
                      if (resultSet.next()) {
                          return resultSet.getLong(1);
                      }
                      return null;
                  }
                }
            );
            System.out.println(machaceksName);
        }
    }
    

    Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

    I wrote a simple library for manipulating the JavaScript date object. You can try this:

    var dateString = timeSolver.getString(new Date(), "YYYY/MM/DD HH:MM:SS.SSS")
    

    Library here: https://github.com/sean1093/timeSolver

    Display / print all rows of a tibble (tbl_df)

    you can print it in Rstudio with View() more convenient:

    df %>% View()
    
    View(df)
    

    How to pass data from child component to its parent in ReactJS?

    Considering React Function Components and using Hooks are getting more popular these days , I will give a simple example of how to Passing data from child to parent component

    in Parent Function Component we will have :

    import React, { useState, useEffect } from "react";
    

    then

    const [childData, setChildData] = useState("");
    

    and passing setChildData (which do a job similar to this.setState in Class Components) to Child

    return( <ChildComponent passChildData={setChildData} /> )
    

    in Child Component first we get the receiving props

    function ChildComponent(props){ return (...) }
    

    then you can pass data anyhow like using a handler function

    const functionHandler = (data) => {
    
    props.passChildData(data);
    
    }
    

    Hashing a dictionary?

    You could use the third-party frozendict module to freeze your dict and make it hashable.

    from frozendict import frozendict
    my_dict = frozendict(my_dict)
    

    For handling nested objects, you could go with:

    import collections.abc
    
    def make_hashable(x):
        if isinstance(x, collections.abc.Hashable):
            return x
        elif isinstance(x, collections.abc.Sequence):
            return tuple(make_hashable(xi) for xi in x)
        elif isinstance(x, collections.abc.Set):
            return frozenset(make_hashable(xi) for xi in x)
        elif isinstance(x, collections.abc.Mapping):
            return frozendict({k: make_hashable(v) for k, v in x.items()})
        else:
            raise TypeError("Don't know how to make {} objects hashable".format(type(x).__name__))
    

    If you want to support more types, use functools.singledispatch (Python 3.7):

    @functools.singledispatch
    def make_hashable(x):
        raise TypeError("Don't know how to make {} objects hashable".format(type(x).__name__))
    
    @make_hashable.register
    def _(x: collections.abc.Hashable):
        return x
    
    @make_hashable.register
    def _(x: collections.abc.Sequence):
        return tuple(make_hashable(xi) for xi in x)
    
    @make_hashable.register
    def _(x: collections.abc.Set):
        return frozenset(make_hashable(xi) for xi in x)
    
    @make_hashable.register
    def _(x: collections.abc.Mapping):
        return frozendict({k: make_hashable(v) for k, v in x.items()})
    
    # add your own types here
    

    Datetime BETWEEN statement not working in SQL Server

    From Sql Server 2008 you have "date" format.

    So you can use

    SELECT * FROM LOGS WHERE CONVERT(date,[CHECK_IN]) BETWEEN '2013-10-18' AND '2013-10-18'
    

    https://docs.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql

    How to install beautiful soup 4 with python 2.7 on windows

    Install pip

    Download get-pip. Remember to save it as "get-pip.py"

    Now go to the download folder. Right click on get-pip.py then open with python.exe.

    You can add system variable by

    (by doing this you can use pip and easy_install without specifying path)

    1 Clicking on Properties of My Computer

    2 Then chose Advanced System Settings

    3 Click on Advanced Tab

    4 Click on Environment Variables

    5 From System Variables >>> select variable path.

    6 Click edit then add the following lines at the end of it

     ;c:\Python27;c:\Python27\Scripts
    

    (please dont copy this, just go to your python directory and copy the paths similar to this)

    NB:- you have to do this once only.

    Install beautifulsoup4

    Open cmd and type

    pip install beautifulsoup4
    

    Scrolling a div with jQuery

    I was looking for this same answer and I couldn't find anything that did exactly what I wanted so I created my own and posted it here:

    http://seekieran.com/2011/03/jquery-scrolling-box/

    Working Demo: http://jsbin.com/azoji3

    Here is the important code:

    function ScrollDown(){
    
      //var topVal = $('.up').parents(".container").find(".content").css("top").replace(/[^-\d\.]/g, '');
      var topVal = $(".content").css("top").replace(/[^-\d\.]/g, '');
        topVal = parseInt(topVal);
      console.log($(".content").height()+ " " + topVal);
      if(Math.abs(topVal) < ($(".content").height() - $(".container").height() + 60)){ //This is to limit the bottom of the scrolling - add extra to compensate for issues
      $('.up').parents(".container").find(".content").stop().animate({"top":topVal - 20  + 'px'},'slow');
        if (mouseisdown)
    setTimeout(ScrollDown, 400);
      }
    

    Recursion to make it happen:

     $('.dn').mousedown(function(event) {
        mouseisdown = true;
        ScrollDown();
    }).mouseup(function(event) {
        mouseisdown = false;
    });
    

    Thanks to Jonathan Sampson for some code to start but it didn't work initially so I have heavily modified it. Any suggestions to improve it would be great here in either the comments or comments on the blog.

    Googlemaps API Key for Localhost

    If you are working on localhost, create a separate APIkey for your development and then remove restrictions on that key so that your localhost can use it. Remember to not use this key on production, so you don't expose your key to hunters online.

    I had the same issue and all attempts to get the restrictions working on my localhost environment was not successful until I created a separate apikey specifically for development and then removed its restrictions. However I don't use that key on production environment, and once am done with developments, I will delete the API key immediately.

    I Know this post is late, but for people that will likely face this issue in the future, this is the best route to go.

    How to collapse blocks of code in Eclipse?

    If you want folding an all your editors, I found you can enable Folding in

    Preferences > Editors > Structured Text Editors

    Enable Folding

    Display image as grayscale using matplotlib

    import matplotlib.pyplot as plt

    You can also run once in your code

    plt.gray()
    

    This will show the images in grayscale as default

    im = array(Image.open('I_am_batman.jpg').convert('L'))
    plt.imshow(im)
    plt.show()
    

    How to set a Timer in Java?

        new java.util.Timer().schedule(new TimerTask(){
            @Override
            public void run() {
                System.out.println("Executed...");
               //your code here 
               //1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly 
            }
        },1000*5,1000*5); 
    

    Should ol/ul be inside <p> or outside?

    The short answer is that ol elements are not legally allowed inside p elements.

    To see why, let's go to the spec! If you can get comfortable with the HTML spec, it will answer many of your questions and curiosities. You want to know if an ol can live inside a p. So…

    4.5.1 The p element:

    Categories: Flow content, Palpable content.
    Content model: Phrasing content.


    4.5.5 The ol element:

    Categories: Flow content.
    Content model: Zero or more li and script-supporting elements.

    The first part says that p elements can only contain phrasing content (which are “inline” elements like span and strong).

    The second part says ols are flow content (“block” elements like p and div). So they can't be used inside a p.


    ols and other flow content can be used in in some other elements like div:

    4.5.13 The div element:

    Categories: Flow content, Palpable content.
    Content model: Flow content.

    How to change the default background color white to something else in twitter bootstrap

    You can simply add this line into your bootstrap_and_overides.css.less file

    body { background: #000000 !important;}
    

    that's it

    Session state can only be used when enableSessionState is set to true either in a configuration

    I realise there is an accepted answer, but this may help people. I found I had a similar problem with a ASP.NET site using NET 3.5 framework when running it in Visual Studio 2012 using IIS Express 8. I'd tried all of the above solutions and none worked - in the end running the solution in the in-built VS 2012 webserver worked. Not sure why, but I suspect it was a link between 3.5 framework and IIS 8.

    How to create a library project in Android Studio and an application project that uses the library project

    Check out this link about multi project setups.

    Some things to point out, make sure you have your settings.gradle updated to reference both the app and library modules.

    settings.gradle: include ':app', ':libraries:lib1', ':libraries:lib2'

    Also make sure that the app's build.gradle has the followng:

    dependencies {
         compile project(':libraries:lib1')
    }
    

    You should have the following structure:

     MyProject/
      | settings.gradle
      + app/
        | build.gradle
      + libraries/
        + lib1/
           | build.gradle
        + lib2/
           | build.gradle
    

    The app's build.gradle should use the com.android.application plugin while any libraries' build.gradle should use the com.android.library plugin.

    The Android Studio IDE should update if you're able to build from the command line with this setup.

    What does "Use of unassigned local variable" mean?

    Change your declarations to this:

    double lateFee = 0.0;
    double monthlyCharge = 0.0;
    double annualRate = 0.0;
    

    The error is caused because there is at least one path through your code where these variables end up not getting set to anything.

    SQL- Ignore case while searching for a string

    Use something like this -

    SELECT DISTINCT COL_NAME FROM myTable WHERE UPPER(COL_NAME) LIKE UPPER('%PriceOrder%')
    

    or

    SELECT DISTINCT COL_NAME FROM myTable WHERE LOWER(COL_NAME) LIKE LOWER('%PriceOrder%')
    

    Convert character to ASCII code in JavaScript

    You can enter a character and get Ascii Code Using this Code

    For Example Enter a Character Like A You Get Ascii Code 65

    _x000D_
    _x000D_
    function myFunction(){_x000D_
        var str=document.getElementById("id1");_x000D_
        if (str.value=="") {_x000D_
           str.focus();_x000D_
           return;_x000D_
        }_x000D_
        var a="ASCII Code is == >  ";_x000D_
    document.getElementById("demo").innerHTML =a+str.value.charCodeAt(0);_x000D_
    }
    _x000D_
    <p>Check ASCII code</p>_x000D_
    _x000D_
    <p>_x000D_
      Enter any character:  _x000D_
      <input type="text" id="id1" name="text1" maxLength="1"> </br>_x000D_
    </p>_x000D_
    _x000D_
    <button onclick="myFunction()">Get ASCII code</button>_x000D_
    _x000D_
    <p id="demo" style="color:red;"></p>
    _x000D_
    _x000D_
    _x000D_

    Make TextBox uneditable

    This is for GridView.

     grid.Rows[0].Cells[1].ReadOnly = true;
    

    Set object property using reflection

    Reflection, basically, i.e.

    myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);
    

    or there are libraries to help both in terms of convenience and performance; for example with FastMember:

    var wrapped = ObjectAccessor.Create(obj); 
    wrapped[property] = "Bob";
    

    (which also has the advantage of not needing to know in advance whether it is a field vs a property)

    Replace image src location using CSS

    Here is another dirty hack :)

    .application-title > img {
    display: none;
    }
    
    .application-title::before {
    content: url(path/example.jpg);
    }
    

    How to copy text from a div to clipboard

    I was getting selectNode() param 1 is not of type node error.

    changed the code to this and its working. (for chrome)

    _x000D_
    _x000D_
    function copy_data(containerid) {_x000D_
      var range = document.createRange();_x000D_
      range.selectNode(containerid); //changed here_x000D_
      window.getSelection().removeAllRanges(); _x000D_
      window.getSelection().addRange(range); _x000D_
      document.execCommand("copy");_x000D_
      window.getSelection().removeAllRanges();_x000D_
      alert("data copied");_x000D_
    }
    _x000D_
    <div id="select_txt">This will be copied to clipboard!</div>_x000D_
    <button type="button" onclick="copy_data(select_txt)">copy</button>_x000D_
    <br>_x000D_
    <hr>_x000D_
    <p>Try paste it here after copying</p>_x000D_
    <textarea></textarea>
    _x000D_
    _x000D_
    _x000D_

    Multiline TextBox multiple newline

    When page IsPostback, the following code work correctly. But when page first loading, there is not multiple newline in the textarea. Bug

    textBox1.Text = "Line1\r\n\r\n\r\nLine2";
    

    CSS text-align not working

    You have to make the UL inside the div behave like a block. Try adding

    .navigation ul {
         display: inline-block;
    }
    

    Setting query string using Fetch GET request

    I know this is stating the absolute obvious, but I feel it's worth adding this as an answer as it's the simplest of all:

    const orderId = 1;
    fetch('http://myapi.com/orders?order_id=' + orderId);
    

    recursion versus iteration

    Question :

    And if recursion is usually slower what is the technical reason for ever using it over for loop iteration?

    Answer :

    Because in some algorithms are hard to solve it iteratively. Try to solve depth-first search in both recursively and iteratively. You will get the idea that it is plain hard to solve DFS with iteration.

    Another good thing to try out : Try to write Merge sort iteratively. It will take you quite some time.

    Question :

    Is it correct to say that everywhere recursion is used a for loop could be used?

    Answer :

    Yes. This thread has a very good answer for this.

    Question :

    And if it is always possible to convert an recursion into a for loop is there a rule of thumb way to do it?

    Answer :

    Trust me. Try to write your own version to solve depth-first search iteratively. You will notice that some problems are easier to solve it recursively.

    Hint : Recursion is good when you are solving a problem that can be solved by divide and conquer technique.