Programs & Examples On #Xfdl

Extensible Forms Description Language (XFDL) describes a class of XML documents proposed to the World Wide Web Consortium (W3C). XFDL is a high-level computer language that defines a form as a single, stand-alone object using XML structure. XFDL supports mathematical/Boolean computations, external code extensibility, the capture of multiple digital signatures and the ability for signatures to disable input or alteration on all or a portion of the form.

Python base64 data decode

Well, I assume you are not on Interactive Mode and you used this code to decode your string:

import base64
your_string = 'Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YHcAAAAABDlgeCAAAAAEOWB5QAAAAAQ5YHpkNx8H9Dlge4REqBx0OWB8pEpZ10Q5YH3ES2lxFDlgfuRIuPbEOWB/9EA9SqQ5YIEUIFJtxDlggjAAAAAEOWCDVDDMm3Q5YIR0N5wOtDlghZQ4GkeEOWCGtDD0CbQ5YIfQAAAABDlgiOAAAAAEOWCKAAAAAAQ5YIsgAAAABDlob5AAAAAEOWhwsAAAAAQ5aHHQAAAABDlocvAAAAAEOWh0FBC+dQQ5aHU0NJ9WdDlodlQ9RK6kOWh3dEDRdFQ5aHiUQARjZDloebQ5xn3kOWh61C1TYMQ5aHvwAAAABDlofRAAAAAEOWh+MAAAAAQ5aH9QAAAABDnFl9AAAAAEOcWZAAAAAAQ5xZpAAAAABDnFm3AAAAAEOcWctDH72jQ5xZ3kNDentDnFnxQ0QCp0OcWgVDK52XQ5xaGEMDUuNDnFosAAAAAEOcWj8AAAAAQ5xaUwAAAABDnFpmAAAAAEOcWnkAAAAAQ5xajQAAAABDnFqgAAAAAEOcWrRBnlHwQ5xax0MvOY9DnFraQ6AiZkOcWu5DquEAQ5xbAUNtwQNDnFsVQqVdQEOcWygAAAAAQ5xbPAAAAABDnFtPAAAAAEOcW2IAAAAAQ6Cg+AAAAABDoKEMAAAAAEOgoSEAAAAAQ6ChNQAAAABDoKFKQwi7a0OgoV5DOmAdQ6Chc0NSxE9DoKGHQy7KVUOgoZxCvXN4Q6ChsAAAAABDoKHFAAAAAEO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ERHx5JDh8FaREfH0UO9DJBER8gRQ9bfKERHyFBDzkoWREfIkEOuMHxER8jPAAAAAERHyQ4AAAAAREfJTgAAAABER8mNAAAAAERIbk4AAAAAREhujgAAAABESG7OAAAAAERIbw4AAAAAREhvTkMM9UlESG+NQ083Y0RIb81DOgL9REhwDUK2XghESHBNAAAAAERIcI0AAAAAREhwzQAAAABESHEMAAAAAERKh+IAAAAAREqIIwAAAABESohkAAAAAERKiKYAAAAAREqI50Lh96RESokoQ35MV0RKiWlDnMTYREqJqkNxeg9ESonrQr2M/kRKii0AAAAAREqKbgAAAABESoqvAAAAAERKivAAAAAAREvFtwAAAABES8X5AAAAAERLxjsAAAAAREvGfQAAAABES8a/QwTfiURLxwFDcL+ZREvHQ0OJfrJES8eFQ2HTSURLx8dDAQzpREvICQAAAABES8hLAAAAAERLyI0AAAAAREvIzwAAAABES8wpAAAAAERLzGsAAAAAREvMrQAAAABES8zvAAAAAERLzTFC78e2REvNc0NWbJ9ES821Q5QpeERLzfdDbnPBREvOOUJOhwhES857AAAAAERLzrwAAAAAREvO/gAAAABES89AAAAAAERMDGoAAAAAREwMrQAAAABETAzvAAAAAERMDTEAAAAAREwNc0MbaL1ETA21Q4XDPkRMDfdDlMa4REwOOkNYuqFETA58QoUC7kRMDr4AAAAAREwPAAAAAABETA9CAAAAAERMD4QAAAAARE+u2AAAAABET68dAAAAAERPr2EAAAAARE+vpgAAAABET6/qQyyLhURPsC9DWN/HRE+wc0NkY0tET7C4QxkM20RPsPwAAAAARE+xQQAAAABET7GFAAAAAERPscoAAAAARFAOCQAAAABEUA5OAAAAAERQDpMAAAAARFAO1wAAAABEUA8cQwDAqURQD2FDdvAjRFAPpkOL1RJEUA/qQ0OKJURQEC9CXTp0RFAQdAAAAABEUBC5AAAAAERQEP4AAAAARFARQgAAAABEVcuoAAAAAERVy/AAAAAARFXMOQAAAABEVcyCAAAAAERVzMpCzsoORFXNE0NaGXFEVc1bQ3R5C0RVzaRDKbY/RFXN7QAAAABEVc41AAAAAERVzn4AAAAARFXOxwAAAABEV5BlAAAAAERXkK4AAAAARFeQ+AAAAABEV5FCAAAAAERXkYxDKSu1RFeR1kNbVSFEV5IgQ1lH20RXkmlDOlYfRFeSs0M4QDVEV5L9Q0YP/0RXk0dDMzG5RFeTkQAAAABEV5PaAAAAAERXlCQAAAAARFeUbgAAAABEV6FpAAAAAERXobMAAAAARFeh/QAAAABEV6JHAAAAAERXopFDDVORRFei20NxGSNEV6MlQ22aoURXo25C9lnCRFejuAAAAABEV6QCAAAAAERXpEwAAAAARFeklgAAAABEV6W9AAAAAERXpgcAAAAARFemUQAAAABEV6abAAAAAERXpuVDLnHjRFenL0M9OBdEV6d5QxBdL0RXp8MAAAAARFeoDQAAAABEV6hWAAAAAERXqKAAAAAARF33JAAAAABEXfdzAAAAAERd98EAAAAARF34DwAAAABEXfheQy+tTURd+KxDS93XRF34+kM42jtEXflIQswuZkRd+ZcAAAAARF355QAAAABEXfozAAAAAERd+oEAAAAARF5M4QAAAABEXk0wAAAAAEReTX4AAAAARF5NzQAAAABEXk4bQrksMkReTmpDvnVcRF5OuEQoL11EXk8HREPcqkReT1VEI/uQRF5PpEPTigZEXk/zQ4LN9kReUEFDX7PhRF5QkAAAAABEXlDeAAAAAEReUS0AAAAARF5RewAAAABEXo0MAAAAAERejVsAAAAARF6NqQAAAABEXo34AAAAAERejkdDA7iRRF6OlUOCrD5EXo7kQ8vYCkRejzND56FuRF6PgUO0Y8BEXo/QQyOz3URekB8AAAAARF6QbgAAAABEXpC8AAAAAERekQsAAAAARF7MvgAAAABEXs0NAAAAAERezVwAAAAARF7NqgAAAABEXs35Q478yERezkhDw2IoRF7Ol0PtNthEXs7mQ+gZFERezzVDnL2ORF7PhAAAAABEXs/TAAAAAERe0CEAAAAARF7QcAAAAABEYs8hAAAAAERiz3MAAAAARGLPxQAAAABEYtAXAAAAAERi0GhCk7m4RGLQukOaFH5EYtEMQ8gFaERi0V1DoL7mRGLRr0MQ5L1EYtIBAAAAAERi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EdRJ2Q5gAnkR1EtZDj7qGRHUTNUN1fidEdROVQxFdtUR1E/QAAAAARHUUUwAAAABEdRSzAAAAAER1FRIAAAAARIFNGgAAAABEgU1PAAAAAESBTYQAAAAARIFNuQAAAABEgU3uQy178USBTiNDb4JRRIFOWEOhvR5EgU6NQ7dIFESBTsNDkg3MRIFO+ELaUAREgU8tAAAAAESBT2IAAAAARIFPlwAAAABEgU/MAAAAAESBpzIAAAAARIGnZwAAAABEgaecAAAAAESBp9IAAAAARIGoB0Jew0REgag9QzrtF0SBqHJDhC78RIGop0NtEDlEgajdQy4kQ0SBqRIAAAAARIGpSAAAAABEgal9AAAAAESBqbMAAAAARIHnXgAAAABEgeeUAAAAAESB58kAAAAARIHn/wAAAABEgeg1QwZ+g0SB6GpDhNUoRIHooEOId6xEgejWQvQoEkSB6QsAAAAARIHpQQAAAABEgel2AAAAAESB6awAAAAARIIHpwAAAABEggfdAAAAAESCCBMAAAAARIIISAAAAABEggh+Qv4nckSCCLRDWj6rRIII6kNbO+tEggkfQwvuw0SCCVUAAAAARIIJiwAAAABEggnBAAAAAESCCfYAAAAARIInlQAAAABEgifLAAAAAESCKAAAAAAARIIoNgAAAABEgihsQpgZsESCKKJDTqwDRIIo2ENlUilEgikOQwzsVUSCKUMAAAAARIIpeQAAAABEgimvAAAAAESCKeUAAAAARIJjZgAAAABEgmOcAAAAAESCY9IAAAAARIJkCAAAAABEgmQ+QxAFj0SCZHRDUubtRIJkq0NEJytEgmThQrRT7ESCZRcAAAAARIJlTQAAAABEgmWDAAAAAESCZbkAAAAARILgJgAAAABEguBcAAAAAESC4JMAAAAARILgyQAAAABEguEAQykld0SC4TZDdX0HRILhbENFmp9EguGjQb3PWESC4dkAAAAARILiEAAAAABEguJGAAAAAESC4n0AAAAARILldwAAAABEguWtAAAAAESC5eMAAAAARILmGgAAAABEguZQQwBjuUSC5odDV6cNRILmvUM6wtdEgub0QqvdxESC5yoAAAAARILnYQAAAABEgueXAAAAAESC580AAAAARIQHrQ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xHaAAAAABErEfGAAAAAESsSCVCE4y4RKxIg0NICpdErEjhQ4IvIkSsSUBDKx7dRKxJngAAAABErEn8AAAAAESsSloAAAAARKxKuQAAAABEtQkRAAAAAES1CXkAAAAARLUJ4QAAAABEtQpKAAAAAES1CrJDJhD9RLULGkN2IZtEtQuCQ0j6M0S1C+pCqdwmRLUMUgAAAABEtQy6AAAAAES1DSMAAAAARLUNiwAAAABEt1aPAAAAAES3VvkAAAAARLdXZAAAAABEt1fPAAAAAES3WDpDesoPRLdYpUPA01ZEt1kPQ9YeGkS3WXpDvpdCRLdZ5UOX1rpEt1pQAAAAAES3WrsAAAAARLdbJgAAAABEt1uQAAAAAETFGvIAAAAARMUbbQAAAABExRvpAAAAAETFHGQAAAAARMUc30JvoHRExR1bQ31mOUTFHdZDt+aSRMUeUkPAB3pExR7NQ6mPcETFH0lDgLBwRMUfxEMHHK9ExSBAAAAAAETFILsAAAAARMUhNwAAAABExSGyAAAAAETHFHgAAAAARMcU9gAAAABExxV0AAAAAETHFfIAAAAARMcWcEM1n/lExxbuQ1u19UTHF2xDRxs7RMcX6kLjC6ZExxhoAAAAAETHGOYAAAAARMcZZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA'
base64.b64decode(your_string)

Well first of all you need to assign the finished product to a variable to be able to be printed out:

code_string = base64.b64decode(your_string)

Then like any beginner programmer would know, you would print the results out: Python 2.7x:

print code_string

Python 3.x:

print(code_string)

After the successful decoding, you will get a string about the size of the not yet decoded string. I hope this helps you!

How to dismiss AlertDialog in android

Try this:

   AlertDialog.Builder builder = new AlertDialog.Builder(this);
   AlertDialog OptionDialog = builder.create();
  background.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            SetBackground();
       OptionDialog .dismiss();
        }
    });

What does %s and %d mean in printf in the C language?

The first argument to printf is a string of identifiers.

%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].

Linq order by, group by and order by each group?

I think you want an additional projection that maps each group to a sorted-version of the group:

.Select(group => group.OrderByDescending(student => student.Grade))

It also appears like you might want another flattening operation after that which will give you a sequence of students instead of a sequence of groups:

.SelectMany(group => group)

You can always collapse both into a single SelectMany call that does the projection and flattening together.


EDIT: As Jon Skeet points out, there are certain inefficiencies in the overall query; the information gained from sorting each group is not being used in the ordering of the groups themselves. By moving the sorting of each group to come before the ordering of the groups themselves, the Max query can be dodged into a simpler First query.

Python can't find module in the same folder

Your code is fine, I suspect your problem is how you are launching it.

You need to launch python from your '2014_07_13_test' directory.

Open up a command prompt and 'cd' into your '2014_07_13_test' directory.

For instance:

$ cd /path/to/2014_07_13_test
$ python test.py

If you cannot 'cd' into the directory like this you can add it to sys.path

In test.py:

import sys, os
sys.path.append('/path/to/2014_07_13_test')

Or set/edit the PYTHONPATH

And all should be well...

...well there is a slight mistake with your 'shebang' lines (the first line in both your files), there shouldn't be a space between the '#' and the '!'

There is a better shebang you should use.

Also you don't need the shebang line on every file... only the ones you intend to run from your shell as executable files.

Reading value from console, interactively

A common use case would probably be for the app to display a generic prompt and handle it in a switch statement.

You could get a behaviour equivalent to a while loop by using a helper function that would call itself in the callback:

const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);

function promptInput (prompt, handler)
{
    rl.question(prompt, input =>
    {
        if (handler(input) !== false)
        {
            promptInput(prompt, handler);
        }
        else
        {
            rl.close();
        }
    });
}

promptInput('app> ', input =>
{
    switch (input)
    {
        case 'my command':
            // handle this command
            break;
        case 'exit':
            console.log('Bye!');
            return false;
    }
});

You could pass an empty string instead of 'app> ' if your app already prints something to the screen outside of this loop.

How do I rename a local Git branch?

For Locally

at first change your current branch from the branch you want to update name for example I have 3 branch branch1 , branch2 , branch3

check current branch

git branch --show-current

output may : branch1

then you can update name of branch2 and branch3 not the current one

git branch -m old_branchname new_branchname



For remote

Just three steps to replicate change in name on remote as well as on GitHub:

git branch -m old_branchname new_branchname
git push origin :old_branchname new_branchname
git push --set-upstream origin new_branchname

How to create Select List for Country and States/province in MVC

Thank You All! I am able to to load Select List as per MVC now My Working Code is below:

HTML+MVC Code in View:-

    <tr>
        <th>@Html.Label("Country")</th>
        <td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetCountryList())<span class="required">*</span></td>
    </tr>
    <tr>
        <th>@Html.LabelFor(x=>x.Province)</th>
        <td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetProvincesList())<span class="required">*</span></td>
    </tr>

Created a Controller under "UTIL" folder: Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MedAvail.Applications.MedProvision.Web.Util
{
    public class SelectListItemHelper
    {
        public static IEnumerable<SelectListItem> GetProvincesList()
        {
            IList<SelectListItem> items = new List<SelectListItem>
            {
                new SelectListItem{Text = "California", Value = "B"},
                new SelectListItem{Text = "Alaska", Value = "B"},
                new SelectListItem{Text = "Illinois", Value = "B"},
                new SelectListItem{Text = "Texas", Value = "B"},
                new SelectListItem{Text = "Washington", Value = "B"}

            };
            return items;
        }


        public static IEnumerable<SelectListItem> GetCountryList()
        {
            IList<SelectListItem> items = new List<SelectListItem>
            {
                new SelectListItem{Text = "United States", Value = "B"},
                new SelectListItem{Text = "Canada", Value = "B"},
                new SelectListItem{Text = "United Kingdom", Value = "B"},
                new SelectListItem{Text = "Texas", Value = "B"},
                new SelectListItem{Text = "Washington", Value = "B"}

            };
            return items;
        }


    }
}

And its working COOL now :-)

Thank you!!

What's the simplest way to print a Java array?

In java 8 it is easy. there are two keywords

  1. stream: Arrays.stream(intArray).forEach
  2. method reference: ::println

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    Arrays.stream(intArray).forEach(System.out::println);
    

If you want to print all elements in the array in the same line, then just use print instead of println i.e.

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

Another way without method reference just use:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));

Gson: Is there an easier way to serialize a map

I'm pretty sure GSON serializes/deserializes Maps and multiple-nested Maps (i.e. Map<String, Map<String, Object>>) just fine by default. The example provided I believe is nothing more than just a starting point if you need to do something more complex.

Check out the MapTypeAdapterFactory class in the GSON source: http://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java

So long as the types of the keys and values can be serialized into JSON strings (and you can create your own serializers/deserializers for these custom objects) you shouldn't have any issues.

Java: Identifier expected

You can't call methods outside a method. Code like this cannot float around in the class.

You need something like:

public class MyClass {

  UserInput input = new UserInput();

  public void foo() {
      input.name();
  }
}

or inside a constructor:

public class MyClass {

  UserInput input = new UserInput();

  public MyClass() {
      input.name();
  }
}

Does a TCP socket connection have a "keep alive"?

Now will this socket connection remain open forever or is there a timeout limit associated with it similar to HTTP keep-alive?

The short answer is no it won't remain open forever, it will probably time out after a few hours. Therefore yes there is a timeout and it is enforced via TCP Keep-Alive.

If you would like to configure the Keep-Alive timeout on your machine, see the "Changing TCP Timeouts" section below. Otherwise read through the rest of the answer to learn how TCP Keep-Alive works.

Introduction

TCP connections consist of two sockets, one on each end of the connection. When one side wants to terminate the connection, it sends an RST packet which the other side acknowledges and both close their sockets.

Until that happens, however, both sides will keep their socket open indefinitely. This leaves open the possibility that one side may close their socket, either intentionally or due to some error, without informing the other end via RST. In order to detect this scenario and close stale connections the TCP Keep Alive process is used.

Keep-Alive Process

There are three configurable properties that determine how Keep-Alives work. On Linux they are1:

  • tcp_keepalive_time
    • default 7200 seconds
  • tcp_keepalive_probes
    • default 9
  • tcp_keepalive_intvl
    • default 75 seconds

The process works like this:

  1. Client opens TCP connection
  2. If the connection is silent for tcp_keepalive_time seconds, send a single empty ACK packet.1
  3. Did the server respond with a corresponding ACK of its own?
    • No
      1. Wait tcp_keepalive_intvl seconds, then send another ACK
      2. Repeat until the number of ACK probes that have been sent equals tcp_keepalive_probes.
      3. If no response has been received at this point, send a RST and terminate the connection.
    • Yes: Return to step 2

This process is enabled by default on most operating systems, and thus dead TCP connections are regularly pruned once the other end has been unresponsive for 2 hours 11 minutes (7200 seconds + 75 * 9 seconds).

Gotchas

2 Hour Default

Since the process doesn't start until a connection has been idle for two hours by default, stale TCP connections can linger for a very long time before being pruned. This can be especially harmful for expensive connections such as database connections.

Keep-Alive is Optional

According to RFC 1122 4.2.3.6, responding to and/or relaying TCP Keep-Alive packets is optional:

Implementors MAY include "keep-alives" in their TCP implementations, although this practice is not universally accepted. If keep-alives are included, the application MUST be able to turn them on or off for each TCP connection, and they MUST default to off.

...

It is extremely important to remember that ACK segments that contain no data are not reliably transmitted by TCP.

The reasoning being that Keep-Alive packets contain no data and are not strictly necessary and risk clogging up the tubes of the interwebs if overused.

In practice however, my experience has been that this concern has dwindled over time as bandwidth has become cheaper; and thus Keep-Alive packets are not usually dropped. Amazon EC2 documentation for instance gives an indirect endorsement of Keep-Alive, so if you're hosting with AWS you are likely safe relying on Keep-Alive, but your mileage may vary.

Changing TCP Timeouts

Per Socket

Unfortunately since TCP connections are managed on the OS level, Java does not support configuring timeouts on a per-socket level such as in java.net.Socket. I have found some attempts3 to use Java Native Interface (JNI) to create Java sockets that call native code to configure these options, but none appear to have widespread community adoption or support.

Instead, you may be forced to apply your configuration to the operating system as a whole. Be aware that this configuration will affect all TCP connections running on the entire system.

Linux

The currently configured TCP Keep-Alive settings can be found in

  • /proc/sys/net/ipv4/tcp_keepalive_time
  • /proc/sys/net/ipv4/tcp_keepalive_probes
  • /proc/sys/net/ipv4/tcp_keepalive_intvl

You can update any of these like so:

# Send first Keep-Alive packet when a TCP socket has been idle for 3 minutes
$ echo 180 > /proc/sys/net/ipv4/tcp_keepalive_time
# Send three Keep-Alive probes...
$ echo 3 > /proc/sys/net/ipv4/tcp_keepalive_probes
# ... spaced 10 seconds apart.
$ echo 10 > /proc/sys/net/ipv4/tcp_keepalive_intvl

Such changes will not persist through a restart. To make persistent changes, use sysctl:

sysctl -w net.ipv4.tcp_keepalive_time=180 net.ipv4.tcp_keepalive_probes=3 net.ipv4.tcp_keepalive_intvl=10

Mac OS X

The currently configured settings can be viewed with sysctl:

$ sysctl net.inet.tcp | grep -E "keepidle|keepintvl|keepcnt"
net.inet.tcp.keepidle: 7200000
net.inet.tcp.keepintvl: 75000
net.inet.tcp.keepcnt: 8

Of note, Mac OS X defines keepidle and keepintvl in units of milliseconds as opposed to Linux which uses seconds.

The properties can be set with sysctl which will persist these settings across reboots:

sysctl -w net.inet.tcp.keepidle=180000 net.inet.tcp.keepcnt=3 net.inet.tcp.keepintvl=10000

Alternatively, you can add them to /etc/sysctl.conf (creating the file if it doesn't exist).

$ cat /etc/sysctl.conf
net.inet.tcp.keepidle=180000
net.inet.tcp.keepintvl=10000
net.inet.tcp.keepcnt=3

Windows

I don't have a Windows machine to confirm, but you should find the respective TCP Keep-Alive settings in the registry at

\HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\TCPIP\Parameters

Footnotes

1. See man tcp for more information.

2. This packet is often referred to as a "Keep-Alive" packet, but within the TCP specification it is just a regular ACK packet. Applications like Wireshark are able to label it as a "Keep-Alive" packet by meta-analysis of the sequence and acknowledgement numbers it contains in reference to the preceding communications on the socket.

3. Some examples I found from a basic Google search are lucwilliams/JavaLinuxNet and flonatel/libdontdie.

Print array elements on separate lines in Bash?

You could use a Bash C Style For Loop to do what you want.

my_array=(one two three)

for ((i=0; i < ${#my_array[@]}; i++ )); do echo "${my_array[$i]}"; done
one
two
three

Set height of chart in Chart.js

Just to add on to the answer given by @numediaweb

In case you're banging your head against the wall because after following the instructions to set maintainAspectRatio=false: I originally copied my code from an example I got on a website on using Chart.js with Angular 2+:

        <div style="display: block">
          <canvas baseChart
                  [datasets]="chartData"
                  [labels]="chartLabels"
                  [options]="chartOptions"
                  [legend]="chartLegend"
                  [colors]="chartColors"
                  [chartType]="chartType">
          </canvas>
        </div>

To make this work correctly you must remove the embedded (and unnecessary) style="display: block" Instead define a class for the enclosing div, and define its height in CSS.

Once you do that, the chart should have responsive width but fixed height.

Intercept page exit event

I have users who have not been completing all required data.

<cfset unloadCheck=0>//a ColdFusion precheck in my page generation to see if unload check is needed
var erMsg="";
$(document).ready(function(){
<cfif q.myData eq "">
    <cfset unloadCheck=1>
    $("#myInput").change(function(){
        verify(); //function elsewhere that checks all fields and populates erMsg with error messages for any fail(s)
        if(erMsg=="") window.onbeforeunload = null; //all OK so let them pass
        else window.onbeforeunload = confirmExit(); //borrowed from Jantimon above;
    });
});
<cfif unloadCheck><!--- if any are outstanding, set the error message and the unload alert --->
    verify();
    window.onbeforeunload = confirmExit;
    function confirmExit() {return "Data is incomplete for this Case:"+erMsg;}
</cfif>

How to declare an array in Python?

variable = []

Now variable refers to an empty list*.

Of course this is an assignment, not a declaration. There's no way to say in Python "this variable should never refer to anything other than a list", since Python is dynamically typed.


*The default built-in Python type is called a list, not an array. It is an ordered container of arbitrary length that can hold a heterogenous collection of objects (their types do not matter and can be freely mixed). This should not be confused with the array module, which offers a type closer to the C array type; the contents must be homogenous (all of the same type), but the length is still dynamic.

What is tail call optimization?

In a functional language, tail call optimization is as if a function call could return a partially evaluated expression as the result, which would then be evaluated by the caller.

f x = g x

f 6 reduces to g 6. So if the implementation could return g 6 as the result, and then call that expression it would save a stack frame.

Also

f x = if c x then g x else h x.

Reduces to f 6 to either g 6 or h 6. So if the implementation evaluates c 6 and finds it is true then it can reduce,

if true then g x else h x ---> g x

f x ---> h x

A simple non tail call optimization interpreter might look like this,

class simple_expresion
{
    ...
public:
    virtual ximple_value *DoEvaluate() const = 0;
};

class simple_value
{
    ...
};

class simple_function : public simple_expresion
{
    ...
private:
    simple_expresion *m_Function;
    simple_expresion *m_Parameter;

public:
    virtual simple_value *DoEvaluate() const
    {
        vector<simple_expresion *> parameterList;
        parameterList->push_back(m_Parameter);
        return m_Function->Call(parameterList);
    }
};

class simple_if : public simple_function
{
private:
    simple_expresion *m_Condition;
    simple_expresion *m_Positive;
    simple_expresion *m_Negative;

public:
    simple_value *DoEvaluate() const
    {
        if (m_Condition.DoEvaluate()->IsTrue())
        {
            return m_Positive.DoEvaluate();
        }
        else
        {
            return m_Negative.DoEvaluate();
        }
    }
}

A tail call optimization interpreter might look like this,

class tco_expresion
{
    ...
public:
    virtual tco_expresion *DoEvaluate() const = 0;
    virtual bool IsValue()
    {
        return false;
    }
};

class tco_value
{
    ...
public:
    virtual bool IsValue()
    {
        return true;
    }
};

class tco_function : public tco_expresion
{
    ...
private:
    tco_expresion *m_Function;
    tco_expresion *m_Parameter;

public:
    virtual tco_expression *DoEvaluate() const
    {
        vector< tco_expression *> parameterList;
        tco_expression *function = const_cast<SNI_Function *>(this);
        while (!function->IsValue())
        {
            function = function->DoCall(parameterList);
        }
        return function;
    }

    tco_expresion *DoCall(vector<tco_expresion *> &p_ParameterList)
    {
        p_ParameterList.push_back(m_Parameter);
        return m_Function;
    }
};

class tco_if : public tco_function
{
private:
    tco_expresion *m_Condition;
    tco_expresion *m_Positive;
    tco_expresion *m_Negative;

    tco_expresion *DoEvaluate() const
    {
        if (m_Condition.DoEvaluate()->IsTrue())
        {
            return m_Positive;
        }
        else
        {
            return m_Negative;
        }
    }
}

How to link an image and target a new window

<a href="http://www.google.com" target="_blank"> //gives blank window
<img width="220" height="250" border="0" align="center"  src=""/> // show image into new window
</a>

See the code

Git submodule push

Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:

"git push --recurse-submodules" learned to optionally look into the histories of submodules bound to the superproject and push them out.

Probably done after this patch and the --on-demand option:

recurse-submodules=<check|on-demand>::

Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.

  • If check is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
    Otherwise the push will be aborted and exit with non-zero status.
  • If on-demand is used, all submodules that changed in the revisions to be pushed will be pushed.
    If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.

So you could push everything in one go with (from the parent repo) a:

git push --recurse-submodules=on-demand

This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.


With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.

See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe).
(Merged by Junio C Hamano -- gitster -- in commit 5d35d72, 21 Dec 2015)

push: add recurseSubmodules config option

The --recurse-submodules command line parameter has existed for some time but it has no config file equivalent.

Following the style of the corresponding parameter for git fetch, let's invent push.recurseSubmodules to provide a default for this parameter.
This also requires the addition of --recurse-submodules=no to allow the configuration to be overridden on the command line when required.

The most straightforward way to implement this appears to be to make push use code in submodule-config in a similar way to fetch.

The git config doc now include:

push.recurseSubmodules:

Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.

  • If the value is 'check', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.
  • If the value is 'on-demand' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -
  • If the value is 'no' then default behavior of ignoring submodules when pushing is retained.

You may override this configuration at time of push by specifying '--recurse-submodules=check|on-demand|no'.

So:

git config push.recurseSubmodules on-demand
git push

Git 2.12 (Q1 2017)

git push --dry-run --recurse-submodules=on-demand will actually work.

See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 12cf113, 16 Dec 2016)

push run with --dry-run doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.

Teach push to respect the --dry-run option when configured to recursively push submodules 'on-demand'.
This is done by passing the --dry-run flag to the child process which performs a push for a submodules when performing a dry-run.


And still in Git 2.12, you now havea "--recurse-submodules=only" option to push submodules out without pushing the top-level superproject.

See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 792e22e, 31 Jan 2017)

How to get current PHP page name

In your case you can use __FILE__ variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php

Converting a String array into an int Array in java

To get rid of additional whitespace, you could change the code like this:

intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line

In Java, how can I determine if a char array contains a particular character?

This method does the trick.

boolean contains(char c, char[] array) {
    for (char x : array) {
        if (x == c) {
            return true;
        }
    }
    return false;
}

Example of usage:

class Main {

    static boolean contains(char c, char[] array) {
        for (char x : array) {
            if (x == c) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] a) {
        char[] charArray = new char[] {'h','e','l','l','o'};
        if (!contains('q', charArray)) {
            // Do something...
            System.out.println("Hello world!");
        }
    }

}

Alternative way:

if (!String.valueOf(charArray).contains("q")) {
    // do something...
}

How to create a responsive image that also scales up in Bootstrap 3

Sure things!

.img-responsive is the right way to make images responsive with bootstrap 3 You can add some height rule for the picture you want to make responsive, because with responsibility, width changes along the height, fix it and there you are.

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

In WSL, there seems to be a problem with path conversion. The location of the Dockerfile in Ubuntu (where I'm running docker and where Dockerfile lives) is "/home/sxw455/App1", but neither of these commands worked:

$ pwd
/home/sxw455/App1
$ ll
total 4
drwxrwxrwx 0 sxw455 sxw455 4096 Dec 11 19:28 ./
drwxr-xr-x 0 sxw455 sxw455 4096 Dec 11 19:25 ../
-rwxrwxrwx 1 sxw455 sxw455  531 Dec 11 19:26 Dockerfile*
-rwxrwxrwx 1 sxw455 sxw455  666 Dec 11 19:28 app.py*
-rwxrwxrwx 1 sxw455 sxw455   12 Dec 11 19:27 requirements.txt*

$ docker build -t friendlyhello .
unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx C:\Windows\System32\Dockerfile: The system cannot find the file specified.

$ docker build -t friendlyhello "/home/sxw455/App1"
unable to prepare context: path "/home/sxw455/App1" not found

But in Windows, the actual path is:

C:\Users\sxw455\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState\rootfs\home\sxw455\App1

And so I had to do this (even though I ran it from bash):

$ docker build -t friendlyhello 
"C:\Users\sxw455\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState\rootfs\home\sxw455\App1"

Sending build context to Docker daemon   5.12kB
Step 1/7 : FROM python:2.7-slim
 ---> 0dc3d8d47241
Step 2/7 : WORKDIR /app
 ---> Using cache
 ---> f739aa02ce04
Step 3/7 : COPY . /app
 ---> Using cache
 ---> 88686c524ae9
Step 4/7 : RUN pip install --trusted-host pypi.python.org -r requirements.txt
 ---> Using cache
 ---> b95f02b14f78
Step 5/7 : EXPOSE 80
 ---> Using cache
 ---> 0924dbc3f695
Step 6/7 : ENV NAME World
 ---> Using cache
 ---> 85c145785b87
Step 7/7 : CMD ["python", "app.py"]
 ---> Using cache
 ---> c2e43b7f0d4a
Successfully built c2e43b7f0d4a
Successfully tagged friendlyhello:latest
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

I had similar problems with environment variables during the initial installation, and followed some advice that said to install the Windows DockerCE and hack the environment variables rather than installing the Ubuntu DockerCE, because (I hope I remembered this correctly) that WSL does not fully implement systemctl. Once the Windows Docker CE installation is done and environment variables are set, docker then works fine under WSL/Ubuntu.

What is the difference between int, Int16, Int32 and Int64?

Int=Int32 --> Original long type

Int16 --> Original int

Int64 --> New data type become available after 64 bit systems

"int" is only available for backward compatibility. We should be really using new int types to make our programs more precise.

---------------

One more thing I noticed along the way is there is no class named Int similar to Int16, Int32 and Int64. All the helpful functions like TryParse for integer come from Int32.TryParse.

How do I send a POST request with PHP?

I was looking for a similar problem and found a better approach of doing this. So here it goes.

You can simply put the following line on the redirection page (say page1.php).

header("Location: URL", TRUE, 307); // Replace URL with to be redirected URL, e.g. final.php

I need this to redirect POST requests for REST API calls. This solution is able to redirect with post data as well as custom header values.

Here is the reference link.

Is it possible to run selenium (Firefox) web driver without a GUI?

Yes. You can use HTMLUnitDriver instead for FirefoxDriver while starting webdriver. This is headless browser setup. Details can be found here.

C# How do I click a button by hitting Enter whilst textbox has focus?

Simply set form "Accept Button" Property to button that you want to hit by Enter key. Or in load event write this.acceptbutton = btnName;

Anonymous method in Invoke call

Because Invoke/BeginInvoke accepts Delegate (rather than a typed delegate), you need to tell the compiler what type of delegate to create ; MethodInvoker (2.0) or Action (3.5) are common choices (note they have the same signature); like so:

control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});

If you need to pass in parameters, then "captured variables" are the way:

string message = "Hi";
control.Invoke((MethodInvoker) delegate {this.Text = message;});

(caveat: you need to be a bit cautious if using captures async, but sync is fine - i.e. the above is fine)

Another option is to write an extension method:

public static void Invoke(this Control control, Action action)
{
    control.Invoke((Delegate)action);
}

then:

this.Invoke(delegate { this.Text = "hi"; });
// or since we are using C# 3.0
this.Invoke(() => { this.Text = "hi"; });

You can of course do the same with BeginInvoke:

public static void BeginInvoke(this Control control, Action action)
{
    control.BeginInvoke((Delegate)action);
}

If you can't use C# 3.0, you could do the same with a regular instance method, presumably in a Form base-class.

How to check if a network port is open on linux?

Building upon the psutil solution mentioned by Joe (only works for checking local ports):

import psutil
1111 in [i.laddr.port for i in psutil.net_connections()]

returns True if port 1111 currently used.

psutil is not part of python stdlib, so you'd need to pip install psutil first. It also needs python headers to be available, so you need something like python-devel

What does it mean to "program to an interface"?

Let's start out with some definitions first:

Interface n. The set of all signatures defined by an object's operations is called the interface to the object

Type n. A particular interface

A simple example of an interface as defined above would be all the PDO object methods such as query(), commit(), close() etc., as a whole, not separately. These methods, i.e. its interface define the complete set of messages, requests that can be sent to the object.

A type as defined above is a particular interface. I will use the made-up shape interface to demonstrate: draw(), getArea(), getPerimeter() etc..

If an object is of the Database type we mean that it accepts messages/requests of the database interface, query(), commit() etc.. Objects can be of many types. You can have a database object be of the shape type as long as it implements its interface, in which case this would be sub-typing.

Many objects can be of many different interfaces/types and implement that interface differently. This allows us to substitute objects, letting us choose which one to use. Also known as polymorphism.

The client will only be aware of the interface and not the implementation.

So in essence programming to an interface would involve making some type of abstract class such as Shape with the interface only specified i.e. draw(), getCoordinates(), getArea() etc.. And then have different concrete classes implement those interfaces such as a Circle class, Square class, Triangle class. Hence program to an interface not an implementation.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

Just to elaborate a bit more on Henry's answer, you can also use specific error codes, from raise_application_error and handle them accordingly on the client side. For example:

Suppose you had a PL/SQL procedure like this to check for the existence of a location record:

   PROCEDURE chk_location_exists
   (
      p_location_id IN location.gie_location_id%TYPE
   )
   AS
      l_cnt INTEGER := 0;
   BEGIN
      SELECT COUNT(*)
        INTO l_cnt
        FROM location
       WHERE gie_location_id = p_location_id;

       IF l_cnt = 0
       THEN
          raise_application_error(
             gc_entity_not_found,
             'The associated location record could not be found.');
       END IF;
   END;

The raise_application_error allows you to raise a specific error code. In your package header, you can define: gc_entity_not_found INTEGER := -20001;

If you need other error codes for other types of errors, you can define other error codes using -20002, -20003, etc.

Then on the client side, you can do something like this (this example is for C#):

/// <summary>
/// <para>Represents Oracle error number when entity is not found in database.</para>
/// </summary>
private const int OraEntityNotFoundInDB = 20001;

And you can execute your code in a try/catch

try
{
   // call the chk_location_exists SP
}
catch (Exception e)
{
    if ((e is OracleException) && (((OracleException)e).Number == OraEntityNotFoundInDB))
    {
        // create an EntityNotFoundException with message indicating that entity was not found in
        // database; use the message of the OracleException, which will indicate the table corresponding
        // to the entity which wasn't found and also the exact line in the PL/SQL code where the application
        // error was raised
        return new EntityNotFoundException(
            "A required entity was not found in the database: " + e.Message);
    }
}

" netsh wlan start hostednetwork " command not working no matter what I try

Same issue.

I solved the problem first activating (right click mouse and select activate) from control panel (network connections) and later changing to set mode to allow (by netsh command), to finally starting the hostednetwork with other netsh command, that is:

1.- Activate (Network Connections) by right click

2.- netsh wlan set hostednetwork mode=allow

3.- netsh wlan start hosted network

Good luck mate !!!

Rename a file using Java

This is an easy way to rename a file:

        File oldfile =new File("test.txt");
        File newfile =new File("test1.txt");

        if(oldfile.renameTo(newfile)){
            System.out.println("File renamed");
        }else{
            System.out.println("Sorry! the file can't be renamed");
        }

Resize iframe height according to content height in it

I just spent the better part of 3 days wrestling with this. I'm working on an application that loads other applications into itself while maintaining a fixed header and a fixed footer. Here's what I've come up with. (I also used EasyXDM, with success, but pulled it out later to use this solution.)

Make sure to run this code AFTER the <iframe> exists in the DOM. Put it into the page that pulls in the iframe (the parent).

// get the iframe
var theFrame = $("#myIframe");
// set its height to the height of the window minus the combined height of fixed header and footer
theFrame.height(Number($(window).height()) - 80);

function resizeIframe() {
    theFrame.height(Number($(window).height()) - 80);
}

// setup a resize method to fire off resizeIframe.
// use timeout to filter out unnecessary firing.
var TO = false;
$(window).resize(function() {
    if (TO !== false) clearTimeout(TO);
    TO = setTimeout(resizeIframe, 500); //500 is time in miliseconds
});

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

use this command:

sudo sed -i "s/mirrorlist=https/mirrorlist=http/" /etc/yum.repos.d/epel.repo

or alternatively use command

vi /etc/yum.repos.d/epel.repo

go to line number 4 and change the url from

mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch

to

mirrorlist=http://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch

What is the difference between a framework and a library?

A framework can be made out of different libraries. Let's take an example.

Let's say you want to cook a fish curry. Then you need ingredients like oil, spices and other utilities. You also need fish which is your base to prepare your dish on (This is data of your application). all ingredients together called a framework. Now you gonna use them one by one or in combination to make your fish curry which is your final product. Compare that with a web framework which is made out of underscore.js, bootstrap.css, bootstrap.js, fontawesome, AngularJS etc. For an example, Twitter Bootstrap v.35.

Now, if you consider only one ingredient, like say oil. You can't use any oil you want because then it will ruin your fish (data). You can only use Olive Oil. Compare that with underscore.js. Now what brand of oil you want to use is up to you. Some dish was made with American Olive Oil (underscore.js) or Indian Olive Oil (lodash.js). This will only change taste of your application. Since they serve almost same purpose, their use depends on the developer's preference and they are easily replaceable.

enter image description here


Framework : A collection of libraries which provide unique properties and behavior to your application. (All ingredients)

Library : A well defined set of instructions which provide unique properties and behavior to your data. (Oil on Fish)

Plugin : A utility build for a library (ui-router -> AngularJS) or many libraries in combination (date-picker -> bootstrap.css + jQuery) without which your plugin might now work as expected.


P.S. AngularJS is a MVC framework but a JavaScript library. Because I believe Library extends default behavior of native technology (JavaScript in this case).

What is the current directory in a batch file?

Your bat file should be in the directory that the bat file is/was in when you opened it. However if you want to put it into a different directory you can do so with cd [whatever directory]

How to view DLL functions?

Use the free DLL Export Viewer, it is very easy to use.

IF statement: how to leave cell blank if condition is false ("" does not work)

You can do something like this to show blank space:

=IF(AND((E2-D2)>0)=TRUE,E2-D2," ")

Inside if before first comma is condition then result and return value if true and last in value as blank if condition is false

correct way of comparing string jquery operator =

First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"

Set field value with reflection

You can try this:

//Your class instance
Publication publication = new Publication();

//Get class with full path(with package name)
Class<?> c = Class.forName("com.example.publication.models.Publication");

//Get method
Method  method = c.getDeclaredMethod ("setTitle", String.class);

//set value
method.invoke (publication,  "Value to want to set here...");

How do you echo a 4-digit Unicode character in Bash?

I'm using this:

$ echo -e '\u2620'
?

This is pretty easier than searching a hex representation... I'm using this in my shell scripts. That works on gnome-term and urxvt AFAIK.

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I found a better solution, maybe it can help somebody replace "watch?v=" by "v/" and it will work

var url = url.replace("watch?v=", "v/");

Case Statement Equivalent in R

If you want to have sql-like syntax you can just make use of sqldf package. Tthe function to be used is also names sqldf and the syntax is as follows

sqldf(<your query in quotation marks>)

python variable NameError

Your if statements are checking for int values. raw_input returns a string. Change the following line:

tSizeAns = raw_input() 

to

tSizeAns = int(raw_input()) 

How to tell which row number is clicked in a table?

You can use object.rowIndex property which has an index starting at 0.

$("table tr").click(function(){
    alert (this.rowIndex);
});

See a working demo

Scroll to the top of the page using JavaScript?

Active all Browser. Good luck

var process;
        var delay = 50; //milisecond scroll top
        var scrollPixel = 20; //pixel U want to change after milisecond
        //Fix Undefine pageofset when using IE 8 below;
        function getPapeYOfSet() {
            var yOfSet = (typeof (window.pageYOffset) === "number") ? window.pageYOffset : document.documentElement.scrollTop;
            return yOfSet;
        }



        function backToTop() {
            process = setInterval(function () {
                var yOfSet = getPapeYOfSet();
                if (yOfSet === 0) {
                    clearInterval(process);
                } else {
                    window.scrollBy(0, -scrollPixel);
                }
            }, delay);
        }

Can (domain name) subdomains have an underscore "_" in it?

I followed the link to RFC1034 and read most of it and was surprised to see this:

The labels must follow the rules for ARPANET host names. They must start with a letter, end with a letter or digit, and have as interior characters only letters, digits, and hyphen. There are also some restrictions on the length. Labels must be 63 characters or less.

For clarification, a domain names are made up of labels which are separated by dots ".". This spec must be outdated because it doesn't mention the use of underscores. I can understand the confusion if anybody stumbles over this spec without knowing it is obsolete. It is obsolete, isn't it?

I followed the link to RFC2181 and read some of it. Especially where it pertains to the issue of what is an authoritative, or canonical, name and the issue of what makes a valid DNS label.

As posted earlier it states there's only a length restriction then to sum it up it reads:

(about names and valid labels)

These are already adequately specified, however the specifications seem to be sometimes ignored. We seek to reinforce the existing specifications.

Kind of leaves me wondering if "a length only restriction" is "adequate". Are we going to start seeing domain names like @#$%!! soon? Isn't the internet screwed up enough?

How to extend available properties of User.Identity

Check out this great blog post by John Atten: ASP.NET Identity 2.0: Customizing Users and Roles

It has great step-by-step info on the whole process. Go read it : )

Here are some of the basics.

Extend the default ApplicationUser class by adding new properties (i.e.- Address, City, State, etc.):

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> 
    GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this,  DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }

    // Use a sensible display name for views:
    [Display(Name = "Postal Code")]
    public string PostalCode { get; set; }

    // Concatenate the address info for display in tables and such:
    public string DisplayAddress
    {
        get
        {
            string dspAddress = string.IsNullOrWhiteSpace(this.Address) ? "" : this.Address;
            string dspCity = string.IsNullOrWhiteSpace(this.City) ? "" : this.City;
            string dspState = string.IsNullOrWhiteSpace(this.State) ? "" : this.State;
            string dspPostalCode = string.IsNullOrWhiteSpace(this.PostalCode) ? "" : this.PostalCode;

            return string.Format("{0} {1} {2} {3}", dspAddress, dspCity, dspState, dspPostalCode);
        }
    }

Then you add your new properties to your RegisterViewModel.

    // Add the new address properties:
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }

Then update the Register View to include the new properties.

    <div class="form-group">
        @Html.LabelFor(m => m.Address, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
        </div>
    </div>

Then update the Register() method on AccountController with the new properties.

    // Add the Address properties:
    user.Address = model.Address;
    user.City = model.City;
    user.State = model.State;
    user.PostalCode = model.PostalCode;

What is the cleanest way to get the progress of JQuery ajax request?

Something like this for $.ajax (HTML5 only though):

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                //Do something with upload progress here
            }
       }, false);

       xhr.addEventListener("progress", function(evt) {
           if (evt.lengthComputable) {
               var percentComplete = evt.loaded / evt.total;
               //Do something with download progress
           }
       }, false);

       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        //Do something on success
    }
});

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Plotting time in Python with Matplotlib

7 years later and this code has helped me. However, my times still were not showing up correctly.

enter image description here

Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

I changed the format to (%H:%M) and the time displayed correctly. enter image description here

All thanks to the community.

AngularJS - Any way for $http.post to send request parameters instead of JSON?

Quick adjustment - for those of you having trouble with the global configuration of the transformRequest function, here's the snippet i'm using to get rid of the Cannot read property 'jquery' of undefined error:

$httpProvider.defaults.transformRequest = function(data) {
        return data != undefined ? $.param(data) : null;
    }

Error in Swift class: Property not initialized at super.init call

You are just initing in the wrong order.

     class Shape2 {
        var numberOfSides = 0
        var name: String
        init(name:String) {
            self.name = name
        }
        func simpleDescription() -> String {
            return "A shape with \(numberOfSides) sides."
        }
    }

    class Square2: Shape2 {
        var sideLength: Double

        init(sideLength:Double, name:String) {

            self.sideLength = sideLength
            super.init(name:name) // It should be behind "self.sideLength = sideLength"
            numberOfSides = 4
        }
        func area () -> Double {
            return sideLength * sideLength
        }
    }

How to comment out a block of Python code in Vim

No plugins or mappings required. Try the built-in "norm" command, which literally executes anything you want on every selected line.

Add # Comments

1. shift V to visually select lines
2. :norm i#

Remove # Comments

1. visually select region as before
2. :norm x

Or if your comments are indented you can do :norm ^x

Notice that these are just ordinary vim commands being preceded by ":norm" to execute them on each line.

More detailed answer for using "norm" command in one of the answers here

What's a quick way to comment/uncomment lines in Vim?

How to initialize a two-dimensional array in Python?

Often I use this approach for initializing a 2-dimensional array

n=[[int(x) for x in input().split()] for i in range(int(input())]

How to find a hash key containing a matching value

You can invert the hash. clients.invert["client_id"=>"2180"] returns "orange"

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

Java Date cut off time information

It really annoyed me that the new "improved" calendar constructor doesn't take an int for milliseconds like the "awful" old Date one. I then got really cross and wrote this:

long stuffYou = startTime.getTimeInMillis() % 1000;
startTime.setTimeInMillis(startTime.getTimeInMillis() - stuffYou);

I didn't use the word "stuff" at the time, but then I discovered the happiness of this:

startTime.set(Calendar.MILLISECOND, 0);

But I'm still quite cross about it.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

If you face this issue directly after a complete new installation on Windows:

It seems like the setup program already starts the http.exe process and blocks the initial port 80 but does not reflect this state in the control panel.

To verify, just test for a running server in your browser. Type into your browser address bar:

localhost

If this displays the XAMPP dashboard, you're fine. Alternatively, check the Task Manager for a running 'Apache HTTP Server' (httpd.exe) process.

You could stop the apache process with the xampp_stop.exe in your xampp base folder. Then, the XAMPP control panel should work as expected.

Delete last N characters from field in a SQL Server database

I got the answer to my own question, ant this is:

select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))

Where N is the number of characters to remove. This avoids to write the complex column/string twice

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

How to run a cron job inside a docker container?

For those who wants to use a simple and lightweight image:

FROM alpine:3.6

# copy crontabs for root user
COPY config/cronjobs /etc/crontabs/root

# start crond with log level 8 in foreground, output to stderr
CMD ["crond", "-f", "-d", "8"]

Where cronjobs is the file that contains your cronjobs, in this form:

* * * * * echo "hello stackoverflow" >> /test_file 2>&1
# remember to end this file with an empty new line

jQuery find parent form

I would suggest using closest, which selects the closest matching parent element:

$('input[name="submitButton"]').closest("form");

Instead of filtering by the name, I would do this:

$('input[type=submit]').closest("form");

ActionLink htmlAttributes

Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:

@Html.ActionLink("Edit", "edit", "markets",
    new { id = 1 },
    new {@class="ui-btn-right", data_icon="gear"})

becomes:

<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>

Direct download from Google Drive using Google Drive API

Using a Service Account might work for you.

$http.get(...).success is not a function

This might be redundant but the above most voted answer says .then(function (success) and that didn't work for me as of Angular version 1.5.8. Instead use response then inside the block response.data got me my json data I was looking for.

$http({
    method: 'get', 
    url: 'data/data.json'
}).then(function (response) {
    console.log(response, 'res');
    data = response.data;
},function (error){
    console.log(error, 'can not get data.');
});

Calculating how many minutes there are between two times

In your quesion code you are using TimeSpan.FromMinutes incorrectly. Please see the MSDN Documentation for TimeSpan.FromMinutes, which gives the following method signature:

public static TimeSpan FromMinutes(double value)

hence, the following code won't compile

var intMinutes = TimeSpan.FromMinutes(varTime); // won't compile

Instead, you can use the TimeSpan.TotalMinutes property to perform this arithmetic. For instance:

TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue; 
double fractionalMinutes = varTime.TotalMinutes;
int wholeMinutes = (int)fractionalMinutes;

How do you change video src using jQuery?

JQUERY

_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
  var videoID = 'videoclip';_x000D_
  var sourceID = 'mp4video';_x000D_
  var newmp4 = 'media/video2.mp4';_x000D_
  var newposter = 'media/video-poster2.jpg';_x000D_
 _x000D_
  $('#videolink1').click(function(event) {_x000D_
    $('#'+videoID).get(0).pause();_x000D_
    $('#'+sourceID).attr('src', newmp4);_x000D_
    $('#'+videoID).get(0).load();_x000D_
     //$('#'+videoID).attr('poster', newposter); //Change video poster_x000D_
    $('#'+videoID).get(0).play();_x000D_
  });_x000D_
});
_x000D_
_x000D_
_x000D_

strcpy() error in Visual studio 2012

A quick fix is to add the _CRT_SECURE_NO_WARNINGS definition to your project's settings

Right-click your C++ and chose the "Properties" item to get to the properties window.

Now follow and expand to, "Configuration Properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".

In the "Preprocessor definitions" add

_CRT_SECURE_NO_WARNINGS

but it would be a good idea to add

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)

as to inherit predefined definitions

IMHO & for the most part this is a good approach.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

My case, the server was encrypting with padding disabled. But the client was trying to decrypt with the padding enabled.

While using EVP_CIPHER*, by default the padding is enabled. To disable explicitly we need to do

EVP_CIPHER_CTX_set_padding(context, 0);

So non matching padding options can be one reason.

The PowerShell -and conditional operator

Another option:

if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
   ...
}

Get Insert Statement for existing row in MySQL

With PDO you can do it this way.

$stmt = DB::getDB()->query("SELECT * FROM sometable", array());

$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $fields = array_keys($array[0]);

    $statement = "INSERT INTO user_profiles_copy (".implode(",",$fields).") VALUES ";
    $statement_values = null;

    foreach ($array as $key => $post) {
        if(isset($statement_values)) {
            $statement_values .= ", \n";
        }

        $values = array_values($post);
        foreach($values as $index => $value) {
            $quoted = str_replace("'","\'",str_replace('"','\"', $value));
            $values[$index] = (!isset($value) ? 'NULL' : "'" . $quoted."'") ;
        }

        $statement_values .= "(".implode(',',$values).")";


    }
    $statement .= $statement_values . ";";

    echo $statement;

Create a string and append text to it

Concatenate with & operator

Dim str as String  'no need to create a string instance
str = "Hello " & "World"

You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.


Concatenate with String.Concat()

str = String.Concat("Hello ", "World")

Useful when concatenating array of strings


StringBuilder.Append()

When concatenating large amounts of strings use StringBuilder, it will result in much better performance.

    Dim sb as new System.Text.StringBuilder()
    str = sb.Append("Hello").Append(" ").Append("World").ToString()

Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.

How to convert Json array to list of objects in c#

you have an unmatched jSon string, if you want to convert into a list, try this

{
    "id": "MyID",

     "values": [
        {
            "id": "100",
            "diaplayName": "MyValue1",
        },
        {
            "id": "200",
            "diaplayName": "MyValue2",
        }
   ]    
}

Command-line Unix ASCII-based charting / plotting tool

Check the package plotext which allows to plot data directly on terminal using python3. It is very intuitive as its use is very similar to the matplotlib package.

Here is a basic example:

enter image description here

You can install it with the following command:

sudo -H pip install plotext

As for matplotlib, the main functions are scatter (for single points), plot (for points joined by lines) and show (to actually print the plot on terminal). It is easy to specify the plot dimensions, the point and line styles and whatever to show the axes, number ticks and final equations, which are used to convert the plotted coordinates to the original real values.

Here is the code to produce the plot shown above:

import plotext.plot as plx
import numpy as np

l=3000
x=np.arange(0, l)
y=np.sin(4*np.pi/l*np.array(x))*np.exp(-0.5*np.pi/l*x)

plx.scatter(x, y, rows = 17, cols = 70)
plx.show(clear = 0)

The option clear=True inside show is used to clear the terminal before plotting: this is useful, for example, when plotting a continuous flow of data. An example of plotting a continuous data flow is shown here: enter image description here

The package description provides more information how to customize the plot. The package has been tested on Ubuntu 16 where it works perfectly. Possible future developments (upon request) could involve extension to python2 and to other graphical interfaces (e.g. jupiter). Please let me know if you have any issues using it. Thanks.

I hope this answers your problem.

Simultaneously merge multiple data.frames in a list

I will reuse the data example from @PaulRougieux

x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)

Here's a short and sweet solution using purrr and tidyr

library(tidyverse)

 list(x, y, z) %>% 
  map_df(gather, key=key, value=value, -i) %>% 
  spread(key, value)

Finding all possible combinations of numbers to reach a given sum

An iterative C++ stack solution for a flavor of this problem. Unlike some other iterative solutions, it doesn't make unnecessary copies of intermediate sequences.

// Given a positive integer, return all possible combinations of
// positive integers that sum up to it. 

vector<vector<int>> print_all_sum(int target){
    vector<vector<int>> output;
    vector<int> stack;

    int curr_min = 1;
    int sum = 0;
    while (curr_min < target) {
        sum += curr_min;
        if (sum >= target) {
            if (sum == target) {
                output.push_back(stack); // make a copy
                output.back().push_back(curr_min);
            }
            sum -= curr_min + stack.back();
            curr_min = stack.back() + 1;
            stack.pop_back();
        } else {
            stack.push_back(curr_min);
        }
    }

    return output;
}

Split String into an array of String

You need a regular expression like "\\s+", which means: split whenever at least one whitespace is encountered. The full Java code is:

try {
    String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
    // 
}

How to get number of video views with YouTube API?

Here an example that I used in my TubeCount app.

I also use the fields parameter to filter the JSON result, so only the fields that I need are returned.

var fields = "fields=openSearch:totalResults,entry(title,media:group(yt:videoid),media:group(yt:duration),media:group(media:description),media:group(media:thumbnail[@yt:name='default'](@url)),yt:statistics,yt:rating,published,gd:comments(gd:feedLink(@countHint)))";

var channel = "wiibart";

$.ajax({
    url: "http://gdata.youtube.com/feeds/api/users/"+channel+"/uploads?"+fields+"&v=2&alt=json",
    success: function(data){

        var len = data.feed.entry.length;

        for(var k =0; k<len; k++){
            var yt = data.feed.entry[k];
            v.count = Number(yt.yt$statistics != undefined && yt.yt$statistics.viewCount != undefined ? yt.yt$statistics.viewCount : 0);
        }
    }
});

rails bundle clean

I assume you install gems into vendor/bundle? If so, why not just delete all the gems and do a clean bundle install?

"register" keyword in C?

Register indicates to compiler to optimize this code by storing that particular variable in registers then in memory. it is a request to compiler, compiler may or may not consider this request. You can use this facility in case where some of your variable are being accessed very frequently. For ex: A looping.

One more thing is that if you declare a variable as register then you can't get its address as it is not stored in memory. it gets its allocation in CPU register.

String or binary data would be truncated. The statement has been terminated

The maximal length of the target column is shorter than the value you try to insert.

Rightclick the table in SQL manager and go to 'Design' to visualize your table structure and column definitions.

Edit:

Try to set a length on your nvarchar inserts thats the same or shorter than whats defined in your table.

WPF - add static items to a combo box

Like this:

<ComboBox Text="MyCombo">
<ComboBoxItem  Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem  Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem  Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

node.js execute system command synchronously

Node.js (since version 0.12 - so for a while) supports execSync:

child_process.execSync(command[, options])

You can now directly do this:

const execSync = require('child_process').execSync;
code = execSync('node -v');

and it'll do what you expect. (Defaults to pipe the i/o results to the parent process). Note that you can also spawnSync now.

How to yum install Node.JS on Amazon Linux

You can update/install the node by reinstalling the installed package to the current version which may save us from lotta of errors, while doing the update.

This is done by nvm with the below command. Here, I have updated my node version to 8 and reinstalled all the available packages to v8 too!

nvm i v8 --reinstall-packages-from=default

It works on AWS Linux instance as well.

Why Git is not allowing me to commit even after configuration?

I had this problem even after setting the config properly. git config

My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).

What is the difference between HTTP status code 200 (cache) vs status code 304?

The items with code "200 (cache)" were fulfilled directly from your browser cache, meaning that the original requests for the items were returned with headers indicating that the browser could cache them (e.g. future-dated Expires or Cache-Control: max-age headers), and that at the time you triggered the new request, those cached objects were still stored in local cache and had not yet expired.

304s, on the other hand, are the response of the server after the browser has checked if a file was modified since the last version it had cached (the answer being "no").

For most optimal web performance, you're best off setting a far-future Expires: or Cache-Control: max-age header for all assets, and then when an asset needs to be changed, changing the actual filename of the asset or appending a version string to requests for that asset. This eliminates the need for any request to be made unless the asset has definitely changed from the version in cache (no need for that 304 response). Google has more details on correct use of long-term caching.

Excel to JSON javascript code?

@Kwang-Chun Kang Thanks Kang a lot! I found the solution is working and very helpful, it really save my day. For me I am trying to create a React.js component that convert *.xlsx to json object when user upload the excel file to a html input tag. First I need to install XLSX package with:

npm install xlsx --save

Then in my component code, import with:

import XLSX from 'xlsx'

The component UI should look like this:

<input
  accept=".xlsx"
  type="file"
  onChange={this.fileReader}
/>

It calls a function fileReader(), which is exactly same as the solution provided. To learn more about fileReader API, I found this blog to be helpful: https://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

Formatting code in Notepad++

If all you need is alignment, try the plugin called Code Alignment.

You can get it from the built-in plugin manager in Notepad++.

Removing double quotes from a string in Java

You can just go for String replace method.-

line1 = line1.replace("\"", "");

Inner join with count() on three tables

Your solution is nearly correct. You could add DISTINCT:

SELECT
    people.pe_name,
    COUNT(distinct orders.ord_id) AS num_orders,
    COUNT(items.item_id) AS num_items
FROM
    people
    INNER JOIN orders ON (orders.pe_id = people.pe_id)
    INNER JOIN items ON items.pe_id = people.pe_id
GROUP BY
    people.pe_id;

jquery simple image slideshow tutorial

I dont know why you havent marked on of these gr8 answers... here is another option which would enable you and anyone else visiting to control transition speed and pause time

JAVASCRIPT

$(function () {

    /* SET PARAMETERS */
    var change_img_time     = 5000; 
    var transition_speed    = 100;

    var simple_slideshow    = $("#exampleSlider"),
        listItems           = simple_slideshow.children('li'),
        listLen             = listItems.length,
        i                   = 0,

        changeList = function () {

            listItems.eq(i).fadeOut(transition_speed, function () {
                i += 1;
                if (i === listLen) {
                    i = 0;
                }
                listItems.eq(i).fadeIn(transition_speed);
            });

        };

    listItems.not(':first').hide();
    setInterval(changeList, change_img_time);

});

.

HTML

<ul id="exampleSlider">
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
</ul>

.
If your keeping this simple its easy to keep it resposive
best to visit the: DEMO

.
If you want something with special transition FX (Still responsive) - check this out
DEMO WITH SPECIAL FX

How to open mail app from Swift

You should try sending with built-in mail composer, and if that fails, try with share:

func contactUs() {

    let email = "[email protected]" // insert your email here
    let subject = "your subject goes here"
    let bodyText = "your body text goes here"

    // https://developer.apple.com/documentation/messageui/mfmailcomposeviewcontroller
    if MFMailComposeViewController.canSendMail() {

        let mailComposerVC = MFMailComposeViewController()
        mailComposerVC.mailComposeDelegate = self as? MFMailComposeViewControllerDelegate

        mailComposerVC.setToRecipients([email])
        mailComposerVC.setSubject(subject)
        mailComposerVC.setMessageBody(bodyText, isHTML: false)

        self.present(mailComposerVC, animated: true, completion: nil)

    } else {
        print("Device not configured to send emails, trying with share ...")

        let coded = "mailto:\(email)?subject=\(subject)&body=\(bodyText)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        if let emailURL = URL(string: coded!) {
            if #available(iOS 10.0, *) {
                if UIApplication.shared.canOpenURL(emailURL) {
                    UIApplication.shared.open(emailURL, options: [:], completionHandler: { (result) in
                        if !result {
                            print("Unable to send email.")
                        }
                    })
                }
            }
            else {
                UIApplication.shared.openURL(emailURL as URL)
            }
        }
    }
}

Calculate the mean by group

2015 update with dplyr:

df %>% group_by(dive) %>% summarise(percentage = mean(speed))
Source: local data frame [2 x 2]

   dive percentage
1 dive1  0.4777462
2 dive2  0.6726483

How can I delete all Git branches which have been merged?

Given you want to delete the merged branches, you need to delete the remote-tracking branches only, unless you state otherwise.

So to delete those branches you can do it by

git branch --remote --merged origin/master | egrep -v "(^\*|master|development)" | cut -b 10- | xargs git push --delete origin

This will delete all merged branches (merged to master) except master and development.

String to LocalDate

As you use Joda Time, you should use DateTimeFormatter:

final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);

If using Java 8 or later, then refer to hertzi's answer

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You could make a recursive function do the work

  • Let L = size(M)
  • Let idx = zeros(L,1)
  • Take length(L) as the maximum depth
  • Loop for idx(depth) = 1:L(depth)
  • If your depth is length(L), do the element operation, else call the function again with depth+1

Not as fast as vectorized methods if you want to check all the points, but if you don't need to evaluate most of them it can be quite a time saver.

Unable to use Intellij with a generated sources folder

With gradle, the project settings will be cleared whenever you refresh the gradle settings. Instead you need to add the following lines (or similar) in your build.gradle, I'm using kotlin so:

sourceSets {
    main {
        java {
            srcDir "${buildDir.absolutePath}/generated/source/kapt/main"
        }
    }
}

How to get row count in an Excel file using POI library?

To find last data row, in case you created table template in excel where it is filled partially or in between rows are empty. Logic:

int count = 0;
int emptyrow=0;
int irow=0;
while (rowIterator.hasNext()) {
    row = (Row) rowIterator.next();
    if (count != 0 && !checkIfRowIsEmpty(row)) { }
    else{
        if(count!=0 && emptyrow==irow){
            emptyrow++;
        }else{
            emptyrow=0;
            irow=0;
        }
    }
    if(emptyrow>0){
        irow++;
    }
    if(emptyrow>3){
        break;
    }
    count++;
}

Error 405 (Method Not Allowed) Laravel 5

When use method delete in form then must have to set route delete

Route::delete("empresas/eliminar/{id}", "CompaniesController@delete");

How to prevent favicon.ico requests?

You could use

<link rel="shortcut icon" href="http://localhost/" />

That way it won't actually be requested from the server.

How can I generate random number in specific range in Android?

int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

Javascript Array.sort implementation?

JavaScript's Array.sort() function has internal mechanisms to selects the best sorting algorithm ( QuickSort, MergeSort, etc) on the basis of the datatype of array elements.

When should null values of Boolean be used?

Boolean can be very helpful when you need three state. Like in software testing if Test is passed send true , if failed send false and if test case interrupted send null which will denote test case not executed .

Python list of dictionaries search

This is a general way of searching a value in a list of dictionaries:

def search_dictionaries(key, value, list_of_dictionaries):
    return [element for element in list_of_dictionaries if element[key] == value]

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

Selector on background color of TextView

For who is searching to do it without creating a background sector, just add those lines to the TextView

android:background="?android:attr/selectableItemBackground"
android:clickable="true"

Also to make it selectable use:

android:textIsSelectable="true"

Text file with 0D 0D 0A line breaks

This typically stems from a bug in revision control system, or similar. This was a product from CVS, if a file was checked in from Windows to Unix server, and then checked out again...

In other words, it is just broken...

Viewing local storage contents on IE

Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".

Difference between x86, x32, and x64 architectures?

As the 64bit version is an x86 architecture and was accordingly first called x86-64, that would be the most appropriate name, IMO. Also, x32 is a thing (as mentioned before)—‘x64’, however, is not a continuation of that, so is (theoretically) missleading (even though many people will know what you are talking about) and should thus only be recognised as a marketing thing, not an ‘official’ architecture (again, IMO–obviously, others disagree).

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

This line seems to sum up the crux of your problem:

The issue with this is that now you can't call any new methods (only overrides) on the implementing class, as your object reference variable has the interface type.

You are pretty stuck in your current implementation, as not only do you have to attempt a cast, you also need the definition of the method(s) that you want to call on this subclass. I see two options:

1. As stated elsewhere, you cannot use the String representation of the Class name to cast your reflected instance to a known type. You can, however, use a String equals() test to determine whether your class is of the type that you want, and then perform a hard-coded cast:

try {
   String className = "com.path.to.ImplementationType";// really passed in from config
   Class c = Class.forName(className);
   InterfaceType interfaceType = (InterfaceType)c.newInstance();
   if (className.equals("com.path.to.ImplementationType") {
      ((ImplementationType)interfaceType).doSomethingOnlyICanDo();
   } 
} catch (Exception e) {
   e.printStackTrace();
}

This looks pretty ugly, and it ruins the nice config-driven process that you have. I dont suggest you do this, it is just an example.

2. Another option you have is to extend your reflection from just Class/Object creation to include Method reflection. If you can create the Class from a String passed in from a config file, you can also pass in a method name from that config file and, via reflection, get an instance of the Method itself from your Class object. You can then call invoke(http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object, java.lang.Object...)) on the Method, passing in the instance of your class that you created. I think this will help you get what you are after.

Here is some code to serve as an example. Note that I have taken the liberty of hard coding the params for the methods. You could specify them in a config as well, and would need to reflect on their class names to define their Class obejcts and instances.

public class Foo {

    public void printAMessage() {
    System.out.println(toString()+":a message");
    }
    public void printAnotherMessage(String theString) {
        System.out.println(toString()+":another message:" + theString);
    }

    public static void main(String[] args) {
        Class c = null;
        try {
            c = Class.forName("Foo");
            Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{});
            Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class});
            Object o = c.newInstance();
            System.out.println("this is my instance:" + o.toString());
            method1.invoke(o);
            method2.invoke(o, "this is my message, from a config file, of course");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException nsme){
            nsme.printStackTrace();
        } catch (IllegalAccessException iae) {
            iae.printStackTrace();
        } catch (InstantiationException ie) {
            ie.printStackTrace();
        } catch (InvocationTargetException ite) {
            ite.printStackTrace();
        }
    }
}

and my output:

this is my instance:Foo@e0cf70
Foo@e0cf70:a message
Foo@e0cf70:another message:this is my message, from a config file, of course

jquery Ajax call - data parameters are not being passed to MVC Controller action

In my case, if I remove the the contentType, I get the Internal Server Error.

This is what I got working after multiple attempts:

var request =  $.ajax({
    type: 'POST',
    url: '/ControllerName/ActionName' ,
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
    dataType: 'json'
});

request.done(function(msg) {
    alert(msg);
});

request.fail(function (jqXHR, textStatus, errorThrown) {
    alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
});

And this is the controller code:

public JsonResult ActionName(int projId, int userId)
{
    var obj = new ClassName();

    var result = obj.MethodName(projId, userId); // variable used for readability
    return Json(result, JsonRequestBehavior.AllowGet);
}

Please note, the case of ASP.NET is little different, we have to apply JSON.stringify() to the data as mentioned in the update of this answer.

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

What is the difference between window, screen, and document in Javascript?

Window is the main JavaScript object root, aka the global object in a browser, also can be treated as the root of the document object model. You can access it as window

window.screen or just screen is a small information object about physical screen dimensions.

window.document or just document is the main object of the potentially visible (or better yet: rendered) document object model/DOM.

Since window is the global object you can reference any properties of it with just the property name - so you do not have to write down window. - it will be figured out by the runtime.

Efficiently test if a port is open on Linux?

ss -tl4 '( sport = :22 )'

2ms is quick enough ?

Add the colon and this works on Linux

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

Iterate through pairs of items in a Python list

You can zip the list with itself sans the first element:

a = [5, 7, 11, 4, 5]

for previous, current in zip(a, a[1:]):
    print(previous, current)

This works even if your list has no elements or only 1 element (in which case zip returns an empty iterable and the code in the for loop never executes). It doesn't work on generators, only sequences (tuple, list, str, etc).

How do I access my webcam in Python?

OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install numpy for the OpenCV Python extension (called cv2) to work. As of 2019, you can install both of these libraries with pip: pip install numpy pip install opencv-python

More information on using OpenCV with Python.

An example copied from Displaying webcam feed using opencv and python:

import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break
cv2.destroyWindow("preview")

Two inline-block, width 50% elements wrap to second line

I continued to have this problem in ie7 when the browser was at certain widths. Turns out older browsers round the pixel value up if the percentage result isn't a whole number. To solve this you can try setting

overflow: hidden;

on the last element (or all of them).

Change DIV content using ajax, php and jQuery

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",//post
     url: 'Your URL',
     data: "id="+id, // appears as $_GET['id'] @ ur backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

How to horizontally center an element

In my case I needed to center(on screen) a dropdown menu(using flexbox for it's items) below a button that could have various locations vertically. None of the suggestions worked until I changed position from absolute to fixed, like this:

  margin: auto;
  left: 0;
  right: 0;
  position: fixed;

The above codes makes the dropdown to always center on the screen for devices of all sizes, no matter where the dropdown button is located vertically.

Show Image View from file path?

onLoadImage Full load

private void onLoadImage(final String imagePath) {
    ImageSize targetSize = new ImageSize(imageView.getWidth(), imageView.getHeight()); // result Bitmap will be fit to this size

    //ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleto
    com.nostra13.universalimageloader.core.ImageLoader imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
    imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));

    imageLoader.loadImage(imagePath, targetSize, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(final String imageUri, View view) {
            super.onLoadingStarted(imageUri, view);

            progress2.setVisibility(View.VISIBLE);

            new Handler().post(new Runnable() {
                public void run() {
                    progress2.setColorSchemeResources(android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);

                    // Picasso.with(getContext()).load(imagePath).into(imageView);
                    // Picasso.with(getContext()).load(imagePath) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(imageView);

                    Glide.with(getContext())
                            .load(imagePath)
                            .asBitmap()
                            .into(imageView);
                }
          });
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            // else { 
              Log.e("onLoadImage", "onLoadingComplete");
            //   progress2.setVisibility(View.INVISIBLE);
            // }
            // setLoagingCompileImage();
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            super.onLoadingFailed(imageUri, view, failReason);
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            Log.e("onLoadingFailed", imageUri);
            Log.e("onLoadingFailed", failReason.toString());
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            super.onLoadingCancelled(imageUri, view);
            if (view == null) {
                progress2.setVisibility(View.INVISIBLE);
            }
            Log.e("onLoadImage", "onLoadingCancelled");
        }
    });
}

NPM clean modules

You can just delete the node_module directory

rm -rf node_modules/

How do I get the path to the current script with Node.js?

I know this is pretty old, and the original question I was responding to is marked as duplicate and directed here, but I ran into an issue trying to get jasmine-reporters to work and didn't like the idea that I had to downgrade in order for it to work. I found out that jasmine-reporters wasn't resolving the savePath correctly and was actually putting the reports folder output in jasmine-reporters directory instead of the root directory of where I ran gulp. In order to make this work correctly I ended up using process.env.INIT_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.

var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
  savePath: process.env.INIT_CWD + '/report/e2e/',
  consolidateAll: true,
  captureStdout: true
 });

Create pandas Dataframe by appending one row at a time

If you know the number of entries ex ante, you should preallocate the space by also providing the index (taking the data example from a different answer):

import pandas as pd
import numpy as np
# we know we're gonna have 5 rows of data
numberOfRows = 5
# create dataframe
df = pd.DataFrame(index=np.arange(0, numberOfRows), columns=('lib', 'qty1', 'qty2') )

# now fill it up row by row
for x in np.arange(0, numberOfRows):
    #loc or iloc both work here since the index is natural numbers
    df.loc[x] = [np.random.randint(-1,1) for n in range(3)]
In[23]: df
Out[23]: 
   lib  qty1  qty2
0   -1    -1    -1
1    0     0     0
2   -1     0    -1
3    0    -1     0
4   -1     0     0

Speed comparison

In[30]: %timeit tryThis() # function wrapper for this answer
In[31]: %timeit tryOther() # function wrapper without index (see, for example, @fred)
1000 loops, best of 3: 1.23 ms per loop
100 loops, best of 3: 2.31 ms per loop

And - as from the comments - with a size of 6000, the speed difference becomes even larger:

Increasing the size of the array (12) and the number of rows (500) makes the speed difference more striking: 313ms vs 2.29s

libz.so.1: cannot open shared object file

For Fedora (can be useful for someone)

sudo dnf install zlib-1.2.8-10.fc24.i686 libgcc-6.1.1-2.fc24.i686

Returning Arrays in Java

If you want to use the numbers method, you need an int array to store the returned value.

public static void main(String[] args){
    int[] someNumbers = numbers();
    //do whatever you want with them...
    System.out.println(Arrays.toString(someNumbers));
}

Why do people hate SQL cursors so much?

For what it's worth I have read that the "one" place a cursor will out perform its set-based counterpart is in a running total. Over a small table the speed of summing up the rows over the order by columns favors the set-based operation but as the table increases in row size the cursor will become faster because it can simply carry the running total value to the next pass of the loop. Now where you should do a running total is a different argument...

How to use ClassLoader.getResources() correctly?

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

How do I delete unpushed git commits?

Delete the most recent commit, keeping the work you've done:

git reset --soft HEAD~1

Delete the most recent commit, destroying the work you've done:

git reset --hard HEAD~1

How do I see the extensions loaded by PHP?

Running

php -m
will give you all the modules, and
php -i
will give you a lot more detailed information on what the current configuration.

Spring MVC UTF-8 Encoding

Depending on how you render your view, you may also need:

@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
    return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}

Response Content type as CSV

Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )

  • text/comma-separated-values
  • text/csv
  • application/csv
  • application/excel
  • application/vnd.ms-excel
  • application/vnd.msexcel

Also, the mime-type might be case sensitive...

Pass a String from one Activity to another Activity in Android

Most likely as others have said you want to attach it to your Intent with putExtra. But I want to throw out there that depending on what your use case is, it may be better to have one activity that switches between two fragments. The data is stored in the activity and never has to be passed.

Regex expressions in Java, \\s vs. \\s+

Those two replaceAll calls will always produce the same result, regardless of what x is. However, it is important to note that the two regular expressions are not the same:

  • \\s - matches single whitespace character
  • \\s+ - matches sequence of one or more whitespace characters.

In this case, it makes no difference, since you are replacing everything with an empty string (although it would be better to use \\s+ from an efficiency point of view). If you were replacing with a non-empty string, the two would behave differently.

Convert RGBA PNG to RGB with PIL

The transparent parts mostly have RGBA value (0,0,0,0). Since the JPG has no transparency, the jpeg value is set to (0,0,0), which is black.

Around the circular icon, there are pixels with nonzero RGB values where A = 0. So they look transparent in the PNG, but funny-colored in the JPG.

You can set all pixels where A == 0 to have R = G = B = 255 using numpy like this:

import Image
import numpy as np

FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
x = np.array(img)
r, g, b, a = np.rollaxis(x, axis = -1)
r[a == 0] = 255
g[a == 0] = 255
b[a == 0] = 255
x = np.dstack([r, g, b, a])
img = Image.fromarray(x, 'RGBA')
img.save('/tmp/out.jpg')

enter image description here


Note that the logo also has some semi-transparent pixels used to smooth the edges around the words and icon. Saving to jpeg ignores the semi-transparency, making the resultant jpeg look quite jagged.

A better quality result could be made using imagemagick's convert command:

convert logo.png -background white -flatten /tmp/out.jpg

enter image description here


To make a nicer quality blend using numpy, you could use alpha compositing:

import Image
import numpy as np

def alpha_composite(src, dst):
    '''
    Return the alpha composite of src and dst.

    Parameters:
    src -- PIL RGBA Image object
    dst -- PIL RGBA Image object

    The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
    '''
    # http://stackoverflow.com/a/3375291/190597
    # http://stackoverflow.com/a/9166671/190597
    src = np.asarray(src)
    dst = np.asarray(dst)
    out = np.empty(src.shape, dtype = 'float')
    alpha = np.index_exp[:, :, 3:]
    rgb = np.index_exp[:, :, :3]
    src_a = src[alpha]/255.0
    dst_a = dst[alpha]/255.0
    out[alpha] = src_a+dst_a*(1-src_a)
    old_setting = np.seterr(invalid = 'ignore')
    out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
    np.seterr(**old_setting)    
    out[alpha] *= 255
    np.clip(out,0,255)
    # astype('uint8') maps np.nan (and np.inf) to 0
    out = out.astype('uint8')
    out = Image.fromarray(out, 'RGBA')
    return out            

FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
white = Image.new('RGBA', size = img.size, color = (255, 255, 255, 255))
img = alpha_composite(img, white)
img.save('/tmp/out.jpg')

enter image description here

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

In one of my projects I run tests against Python 2 and 3. For that I wrote a small script which starts a local server independently:

$ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')
Serving HTTP on 0.0.0.0 port 8000 ...

As an alias:

$ alias serve="python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')"
$ serve
Serving HTTP on 0.0.0.0 port 8000 ...

Please note that I control my Python version via conda environments, because of that I can use python instead of python3 for using Python 3.

How to declare a vector of zeros in R

You have several options

integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)

vba pass a group of cells as range to function

As I'm beginner for vba, I'm willing to get a deep knowledge of vba of how all excel in-built functions work form there back.

So as on the above question I have putted my basic efforts.

Function multi_add(a As Range, ParamArray b() As Variant) As Double

    Dim ele As Variant

    Dim i As Long

    For Each ele In a
        multi_add = a + ele.Value **- a**
    Next ele

    For i = LBound(b) To UBound(b)
        For Each ele In b(i)
            multi_add = multi_add + ele.Value
        Next ele
    Next i

End Function

- a: This is subtracted for above code cause a count doubles itself so what values you adds it will add first value twice.

How to get first and last day of the current week in JavaScript

Nice suggestion but you got a small problem in lastday. You should change it to:

lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);

How to check if click event is already bound - JQuery

One more way - mark such buttons with a CSS class and filter:

$('#myButton:not(.bound)').addClass('bound').bind('click',  onButtonClicked);

In recent jQuery versions replace bind with on:

$('#myButton:not(.bound)').addClass('bound').on('click',  onButtonClicked);

Generate C# class from XML

Use below syntax to create schema class from XSD file.

C:\xsd C:\Test\test-Schema.xsd /classes /language:cs /out:C:\Test\

What is the Difference Between Mercurial and Git?

Sometime last year I evaluated both git and hg for my own use, and decided to go with hg. I felt it looked like a cleaner solution, and worked better on more platforms at the time. It was mostly a toss-up, though.

More recently, I started using git because of git-svn and the ability to act as a Subversion client. This won me over and I've now switched completely to git. I think it's got a slightly higher learning curve (especially if you need to poke around the insides), but it really is a great system. I'm going to go read those two comparison articles that John posted now.

How can I make XSLT work in chrome?

I tried putting the file in the wwwroot. So when accessing the page in Chrome, this is the address localhost/yourpage.xml.

Automatic HTTPS connection/redirect with node.js/express

you can use "net" module to listening for HTTP & HTTPS on the same port

var https = require('https');
var http = require('http');
var fs = require('fs');

var net=require('net');
var handle=net.createServer().listen(8000)

var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(handle);

http.createServer(function(req,res){
  res.writeHead(200);
  res.end("hello world\n");
}).listen(handle)

Change package name for Android in React Native

If you are using VSCode and Windows.

1.Press Control + Shift + F.

2.Find Your Package Name and Replace All with your new Package Name.

  1. type "cd android"

  2. type "./gradlew clean"

What is a correct MIME type for .docx, .pptx, etc.?

To load a .docx file:

    if let htmlFile = Bundle.main.path(forResource: "fileName", ofType: "docx") {
        let url = URL(fileURLWithPath: htmlFile)
        do{
            let data = try Data(contentsOf: url)
            self.webView.load(data, mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", textEncodingName: "UTF-8", baseURL: url)
        }catch{
            print("errrr")
        }
    }

C# equivalent of C++ vector, with contiguous memory?

use List<T>. Internally it uses arrays and arrays do use contiguous memory.

How to store Node.js deployment settings/configuration files?

Are you guys using npm to start your scripts (env etc) ?

If you use .env files you can include them in your package.json and use npm to source/start them.

Example:

{
  "name": "server",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node test.js",
    "start-dev": "source dev.env; node test.js",
    "start-prod": "source prod.env; node test.js"
  },
  "dependencies": {
    "mysql": "*"
  }
}

then run the npm scripts:

$ npm start-dev

Its described here https://gist.github.com/ericelliott/4152984 All credit to Eric Elliot

How to write and read a file with a HashMap?

You can write an object to a file using writeObject in ObjectOutputStream

ObjectOutputStream

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

With the mechanism explained in the answer of Jan I have instructed the m2e pluging to ignore the goal "generate-application-xml". This gets rid of the error and seems to work since m2e creates application.xml.

So basically the error forced us to decide which mechanism is in charge for generating application.xml when the Maven build runs inside Eclipse under the control of the m2e plugin. And we have decided that m2e is in charge.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-ear-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <version>6</version>
                <defaultLibBundleDir>lib</defaultLibBundleDir>
            </configuration>
        </plugin>
    </plugins>
    <pluginManagement>
        <plugins>
            **<!-- This plugin's configuration is used to store Eclipse m2e settings 
                only. It has no influence on the Maven build itself. -->
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-ear-plugin</artifactId>
                                    <versionRange>[2.1,)</versionRange>
                                    <goals>
                                        <goal>generate-application-xml</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore></ignore>
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>**
        </plugins>
    </pluginManagement>
</build>

Python - abs vs fabs

math.fabs() always returns float, while abs() may return integer.

Python `if x is not None` or `if not x is None`?

Code should be written to be understandable to the programmer first, and the compiler or interpreter second. The "is not" construct resembles English more closely than "not is".

Genymotion Android emulator - adb access?

My working solution is:

cd /opt/genymobile/genymotion/tools
./adb shell

You have to use its own adb tool.

How to permanently add a private key with ssh-add on Ubuntu?

very simple ^_^ two steps

1.yum install keychain

2.add code below to .bash_profile

/usr/bin/keychain $HOME/.ssh/id_dsa
source $HOME/.keychain/$HOSTNAME-sh

Squash my last X commits together using Git

What about an answer for the question related to a workflow like this?

  1. many local commits, mixed with multiple merges FROM master,
  2. finally a push to remote,
  3. PR and merge TO master by reviewer. (Yes, it would be easier for the developer to merge --squash after the PR, but the team thought that would slow down the process.)

I haven't seen a workflow like that on this page. (That may be my eyes.) If I understand rebase correctly, multiple merges would require multiple conflict resolutions. I do NOT want even to think about that!

So, this seems to work for us.

  1. git pull master
  2. git checkout -b new-branch
  3. git checkout -b new-branch-temp
  4. edit and commit a lot locally, merge master regularly
  5. git checkout new-branch
  6. git merge --squash new-branch-temp // puts all changes in stage
  7. git commit 'one message to rule them all'
  8. git push
  9. Reviewer does PR and merges to master.

Can I run CUDA on Intel's integrated graphics processor?

If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.

Access-Control-Allow-Origin Multiple Origin Domains?

If you try so many code examples like me to make it work using CORS, it is worth to mention that you have to clear your cache first to try if it actually works, similiar to issues like when old images are still present, even if it's deleted on the server (because it is still saved in your cache).

For example CTRL + SHIFT + DEL in Google Chrome to delete your cache.

This helped me using this code after trying many pure .htaccess solutions and this seemed the only one working (at least for me):

    Header add Access-Control-Allow-Origin "http://google.com"
    Header add Access-Control-Allow-Headers "authorization, origin, user-token, x-requested-with, content-type"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

    <FilesMatch "\.(ttf|otf|eot|woff)$">
        <IfModule mod_headers.c>
            SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.com|dev02.otherdomain.net)$" AccessControlAllowOrigin=$0
            Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
        </IfModule>
    </FilesMatch>

Also note that it is widely spread that many solutions say you have to type Header set ... but it is Header add .... Hope this helps someone having the same troubles for some hours now like me.

Add a new line to a text file in MS-DOS

echo "text to echo" > file.txt

Convert NaN to 0 in javascript

Write your own method, and use it everywhere you want a number value:

function getNum(val) {
   if (isNaN(val)) {
     return 0;
   }
   return val;
}

Set focus on textbox in WPF

Another possible solution is to use FocusBehavior provided by free DevExpress MVVM Framework:

<TextBox Text="This control is focused on startup">
    <dxmvvm:Interaction.Behaviors>
        <dxmvvm:FocusBehavior/>
    </dxmvvm:Interaction.Behaviors>
</TextBox>

It allows you to focus a control when it's loaded, when a certain event is raised or a property is changed.

htaccess - How to force the client's browser to clear the cache?

In my case, I change a lot an specific JS file and I need it to be in its last version in all browsers where is being used.

I do not have a specific version number for this file, so I simply hash the current date and time (hour and minute) and pass it as the version number:

<script src="/js/panel/app.js?v={{ substr(md5(date("Y-m-d_Hi")),10,18) }}"></script>

I need it to be loaded every minute, but you can decide when it should be reloaded.

adding child nodes in treeview

May i add to Stormenet example some KISS (Keep It Simple & Stupid):

If you already have a treeView or just created an instance of it: Let's populate with some data - Ex. One parent two child's :

            treeView1.Nodes.Add("ParentKey","Parent Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");

Another Ex. two parent's first have two child's second one child:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
            treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");

Take if farther - sub child of child 2:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");

As you see you can have as many child's and parent's as you want and those can have sub child's of child's and so on.... Hope i help!

How to fix "could not find a base address that matches schema http"... in WCF

Try changing the security mode from "Transport" to "None".

      <!-- Transport security mode requires IIS to have a
           certificate configured for SSL. See readme for
           more information on how to set this up. -->
      <security mode="None">

What does the @Valid annotation indicate in Spring?

I think I know where your question is headed. And since this question is the one that pop ups in google's search main results, I can give a plain answer on what the @Valid annotation does.

I'll present 3 scenarios on how I've used @Valid

Model:

public class Employee{
private String name;
@NotNull(message="cannot be null")
@Size(min=1, message="cannot be blank")
private String lastName;
 //Getters and Setters for both fields.
 //...
}

JSP:

...
<form:form action="processForm" modelAttribute="employee">
 <form:input type="text" path="name"/>
 <br>
 <form:input type="text" path="lastName"/>
<form:errors path="lastName"/>
<input type="submit" value="Submit"/>
</form:form>
...

Controller for scenario 1:

     @RequestMapping("processForm")
        public String processFormData(@Valid @ModelAttribute("employee") Employee employee){
        return "employee-confirmation-page";
    }

In this scenario, after submitting your form with an empty lastName field, you'll get an error page since you're applying validation rules but you're not handling it whatsoever.

Example of said error: Exception page

Controller for scenario 2:

 @RequestMapping("processForm")
    public String processFormData(@Valid @ModelAttribute("employee") Employee employee,
BindingResult bindingResult){
                return bindingResult.hasErrors() ? "employee-form" : "employee-confirmation-page";
            }

In this scenario, you're passing all the results from that validation to the bindingResult, so it's up to you to decide what to do with the validation results of that form.

Controller for scenario 3:

@RequestMapping("processForm")
    public String processFormData(@Valid @ModelAttribute("employee") Employee employee){
                return "employee-confirmation-page";
            }
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> invalidFormProcessor(MethodArgumentNotValidException ex){
  //Your mapping of the errors...etc
}

In this scenario you're still not handling the errors like in the first scenario, but you pass that to another method that will take care of the exception that @Valid triggers when processing the form model. Check this see what to do with the mapping and all that.

To sum up: @Valid on its own with do nothing more that trigger the validation of validation JSR 303 annotated fields (@NotNull, @Email, @Size, etc...), you still need to specify a strategy of what to do with the results of said validation.

Hope I was able to clear something for people that might stumble with this.

Experimental decorators warning in TypeScript compilation

Not to belabor the point but be sure to add the following to

  • Workspace Settings not User Settings

under File >> Preferences >> Settings

"javascript.implicitProjectConfig.experimentalDecorators": true

this fixed the issue for me, and i tried quite a few suggestions i found here and other places.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

Hide html horizontal but not vertical scrollbar

Use CSS. It's easier and faster than javascript.

overflow-x: hidden;
overflow-y: scroll;

How to test the type of a thrown exception in Jest

I ended up writing a convenience method for our test-utils library

/**
 *  Utility method to test for a specific error class and message in Jest
 * @param {fn, expectedErrorClass, expectedErrorMessage }
 * @example   failTest({
      fn: () => {
        return new MyObject({
          param: 'stuff'
        })
      },
      expectedErrorClass: MyError,
      expectedErrorMessage: 'stuff not yet implemented'
    })
 */
  failTest: ({ fn, expectedErrorClass, expectedErrorMessage }) => {
    try {
      fn()
      expect(true).toBeFalsy()
    } catch (err) {
      let isExpectedErr = err instanceof expectedErrorClass
      expect(isExpectedErr).toBeTruthy()
      expect(err.message).toBe(expectedErrorMessage)
    }
  }

Salt and hash a password in Python

Firstly import:-

import hashlib, uuid

Then change your code according to this in your method:

uname = request.form["uname"]
pwd=request.form["pwd"]
salt = hashlib.md5(pwd.encode())

Then pass this salt and uname in your database sql query, below login is a table name:

sql = "insert into login values ('"+uname+"','"+email+"','"+salt.hexdigest()+"')"

Removing index column in pandas when reading a csv

DataFrames and Series always have an index. Although it displays alongside the column(s), it is not a column, which is why del df['index'] did not work.

If you want to replace the index with simple sequential numbers, use df.reset_index().

To get a sense for why the index is there and how it is used, see e.g. 10 minutes to Pandas.

You have not accepted the license agreements of the following SDK components

Maybe I'm late, but this helped me accept SDK licenses for OSX,

If you have android SDK tools installed, run the following command

~/Library/Android/sdk/tools/bin/sdkmanager --licenses

Accept all licenses by pressing y

Voila! You have accepted SDK licenses and are good to go..

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

I had the same problem. I called a method inside viewDidLoad inside my first UIViewController

- (void)viewDidLoad{
    [super viewDidLoad];

    [self performSelector:@selector(loadingView)
               withObject:nil afterDelay:0.5];
}

- (void)loadingView{

    [self performSegueWithIdentifier:@"loadedData" sender:self];
}

Inside the second UIViewController I did the same also with 0.5 seconds delay. After changing the delay to a higher value, it worked fine. It's like the segue can't be performed too fast after another segue.

How do I run all Python unit tests in a directory?

This is an old question, but what worked for me now (in 2019) is:

python -m unittest *_test.py

All my test files are in the same folder as the source files and they end with _test.

Convert JsonNode into POJO

In Jackson 2.4, you can convert as follows:

MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);

where jsonObjectMapper is a Jackson ObjectMapper.


In older versions of Jackson, it would be

MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);

Calling pylab.savefig without display in ipython

We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

In conclusion, if you close figure by plt.close(fig), it won't be displayed.

How do I find which program is using port 80 in Windows?

Right click on "Command prompt" or "PowerShell", in menu click "Run as Administrator" (on Windows XP you can just run it as usual).

As Rick Vanover mentions in See what process is using a TCP port in Windows Server 2008

The following command will show what network traffic is in use at the port level:

Netstat -a -n -o

or

Netstat -a -n -o >%USERPROFILE%\ports.txt

(to open the port and process list in a text editor, where you can search for information you want)

Then,

with the PIDs listed in the netstat output, you can follow up with the Windows Task Manager (taskmgr.exe) or run a script with a specific PID that is using a port from the previous step. You can then use the "tasklist" command with the specific PID that corresponds to a port in question.

Example:

tasklist /svc /FI "PID eq 1348"

Where to download visual studio express 2005?

You can still get it, from microsoft servers, see my answer on this question: Where is Visual Studio 2005 Express?

Reading values from DataTable

You can do it using the foreach loop

DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];

  foreach(DataRow row in dr_art_line_2.Rows)
  {
     QuantityInIssueUnit_value = Convert.ToInt32(row["columnname"]);
  }

ExpressJS - throw er Unhandled error event

If you want to use the same port number then type kill % in the terminal, which kills the current background process and frees up the port for further usage.

How to fix nginx throws 400 bad request headers on any header testing tools?

normally, Maxim Donnie's method can find the reason. But I encountered one 400 bad request will not log to err_log. I found the reason with the help with tcpdump

Python: How to get stdout after running os.system?

I would like to expand on the Windows solution. Using IDLE with Python 2.7.5, When I run this code from file Expts.py:

import subprocess
r = subprocess.check_output('cmd.exe dir',shell=False) 
print r

...in the Python Shell, I ONLY get the output corresponding to "cmd.exe"; the "dir" part is ignored. HOWEVER, when I add a switch such as /K or /C ...

import subprocess
r = subprocess.check_output('cmd.exe /K dir',shell=False) 
print r

...then in the Python Shell, I get all that I expect including the directory listing. Woohoo !

Now, if I try any of those same things in DOS Python command window, without the switch, or with the /K switch, it appears to make the window hang because it is running a subprocess cmd.exe and it awaiting further input - type 'exit' then hit [enter] to release. But with the /K switch it works perfectly and returns you to the python prompt. Allrightee then.

Went a step further...I thought this was cool...When I instead do this in Expts.py:

import subprocess
r = subprocess.call("cmd.exe dir",shell=False) 
print r

...a new DOS window pops open and remains there displaying only the results of "cmd.exe" not of "dir". When I add the /C switch, the DOS window opens and closes very fast before I can see anything (as expected, because /C terminates when done). When I instead add the /K switch, the DOS window pops open and remain, AND I get all the output I expect including the directory listing.

If I try the same thing (subprocess.call instead of subprocess.check_output) from a DOS Python command window; all output is within the same window, there are no popup windows. Without the switch, again the "dir" part is ignored, AND the prompt changes from the python prompt to the DOS prompt (since a cmd.exe subprocess is running in python; again type 'exit' and you will revert to the python prompt). Adding the /K switch prints out the directory listing and changes the prompt from python to DOS since /K does not terminate the subprocess. Changing the switch to /C gives us all the output expected AND returns to the python prompt since the subprocess terminates in accordance with /C.

Sorry for the long-winded response, but I am frustrated on this board with the many terse 'answers' which at best don't work (seems because they are not tested - like Eduard F's response above mine which is missing the switch) or worse, are so terse that they don't help much at all (e.g., 'try subprocess instead of os.system' ... yeah, OK, now what ??). In contrast, I have provided solutions which I tested, and showed how there are subtle differences between them. Took a lot of time but... Hope this helps.

How to Set Active Tab in jQuery Ui

Just to clarify in complete detail. This is what works with the current version of jQuery Ui

$( "#tabs" ).tabs( "option", "active", # );

where # is the index of the tab you want to make active.

How to print time in format: 2009-08-10 18:17:54.811

Use strftime().

#include <stdio.h>
#include <time.h>

int main()
{
    time_t timer;
    char buffer[26];
    struct tm* tm_info;

    timer = time(NULL);
    tm_info = localtime(&timer);

    strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
    puts(buffer);

    return 0;
}

For milliseconds part, have a look at this question. How to measure time in milliseconds using ANSI C?

Can I set max_retries for requests.request?

After struggling a bit with some of the answers here, I found a library called backoff that worked better for my situation. A basic example:

import backoff

@backoff.on_exception(
    backoff.expo,
    requests.exceptions.RequestException,
    max_tries=5,
    giveup=lambda e: e.response is not None and e.response.status_code < 500
)
def publish(self, data):
    r = requests.post(url, timeout=10, json=data)
    r.raise_for_status()

I'd still recommend giving the library's native functionality a shot, but if you run into any problems or need broader control, backoff is an option.

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

Define Principal as a dependency in your controller method and spring will inject the current authenticated user in your method at invocation.

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

Imshow: extent and aspect

You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).

By default, imshow sets the aspect of the plot to 1, as this is often what people want for image data.

In your case, you can do something like:

import matplotlib.pyplot as plt
import numpy as np

grid = np.random.random((10,10))

fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))

ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')

ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')

ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')

plt.tight_layout()
plt.show()

enter image description here

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

In a URL, should spaces be encoded using %20 or +?

This confusion is because URL is still 'broken' to this day

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+   
|      Part     |      Data         |   
+---------------+-------------------+   
|  Scheme       | http              |   
|  Host address | www.google.com    |   
+---------------+-------------------+  

If we look at a more complex URL such as "https://bob:[email protected]:8080/file;p=1?q=2#third" we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host address     | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file               |
|  Path parameters  | p=1                 |
|  Query parameters | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

The reserved characters are different for each part

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts: "http://example.com/blue+light%20blue?blue%2Blight+blue". From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

What this boils down to is

you should have %20 before the ? and + after

Source

Parameterize an SQL IN clause

Here is another answer to this problem.

(new version posted on 6/4/13).

    private static DataSet GetDataSet(SqlConnectionStringBuilder scsb, string strSql, params object[] pars)
    {
        var ds = new DataSet();
        using (var sqlConn = new SqlConnection(scsb.ConnectionString))
        {
            var sqlParameters = new List<SqlParameter>();
            var replacementStrings = new Dictionary<string, string>();
            if (pars != null)
            {
                for (int i = 0; i < pars.Length; i++)
                {
                    if (pars[i] is IEnumerable<object>)
                    {
                        List<object> enumerable = (pars[i] as IEnumerable<object>).ToList();
                        replacementStrings.Add("@" + i, String.Join(",", enumerable.Select((value, pos) => String.Format("@_{0}_{1}", i, pos))));
                        sqlParameters.AddRange(enumerable.Select((value, pos) => new SqlParameter(String.Format("@_{0}_{1}", i, pos), value ?? DBNull.Value)).ToArray());
                    }
                    else
                    {
                        sqlParameters.Add(new SqlParameter(String.Format("@{0}", i), pars[i] ?? DBNull.Value));
                    }
                }
            }
            strSql = replacementStrings.Aggregate(strSql, (current, replacementString) => current.Replace(replacementString.Key, replacementString.Value));
            using (var sqlCommand = new SqlCommand(strSql, sqlConn))
            {
                if (pars != null)
                {
                    sqlCommand.Parameters.AddRange(sqlParameters.ToArray());
                }
                else
                {
                    //Fail-safe, just in case a user intends to pass a single null parameter
                    sqlCommand.Parameters.Add(new SqlParameter("@0", DBNull.Value));
                }
                using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                {
                    sqlDataAdapter.Fill(ds);
                }
            }
        }
        return ds;
    }

Cheers.