问:
Lottery game, add css class based on numerical range
I'm making a lottery random number generator and have it working, all I want to do is change the background colour of the ball varying on what number range its called between. The second block of code is what I have come up with so far.

For example

o 1-9: White
o 10-19: Blue
o 20-29: Ping,
o 30-39: Green,
o 40-49: Yellow

```<code>    <!DOCTYPE html>
    <head>
      <!-- meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1">

      <title>NRONLINE - Buckinghamshire Web Design, Digital Marketing Workshops and Kofax Consultancy</title>

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <style>
 body {
    background: #444;
    font-family: sans-serif;
    font-size: 18px;
    font-weight: 100;
}

ul {
    position: absolute;
    padding: 0;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    list-style-type: none;
    width: 690px;
    height: 100px;
}

ul li {
    float: left;
    width: 100px;
    height: 100px;
    border-radius: 50px;
    margin-right: 10px;
    color: white;
    text-align: center;
    line-height: 100px;
    font-size: 36px;
}

ul li:nth-child(5n) {
    margin-right: 40px;
}

.ball-placeholder {
    background: #222222;
    background: -moz-linear-gradient(-45deg, #222222 0%, black 100%);
    background: -webkit-gradient(linear, left top, right bottom, color-stop(0%, #222222), color-stop(100%, black));
    background: -webkit-linear-gradient(-45deg, #222222 0%, black 100%);
    background: -o-linear-gradient(-45deg, #222222 0%, black 100%);
    background: -ms-linear-gradient(-45deg, #222222 0%, black 100%);
    background: linear-gradient(135deg, #222222 0%, black 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222222', endColorstr='#000000',GradientType=1 );
}

.next-ball, .play-again {
    position: absolute;
    right: 0;
    left: 0;
    margin: auto;
    border: 0;
    color: white;
}

.next-ball {
    bottom: 20px;
    width: 100px;
    height: 40px;
    font-size: 16px;
    background: #7ac9ed;
}

.play-again {
    display: none;
    bottom: 20px;
    width: 200px;
    height: 80px;
    font-size: 24px;
    background: #d74d2f;
}

.white-ball {
    background: #fff;
    color:#101010;
}

.blue-ball {
    background: #99ccff;
    color:#101010;
}

.pink-ball {
    background: #ffccff;
    color:#101010;
}

.green-ball {
    background: #00cc66;
    color:#101010;
}

.yellow-ball {
    background: #fac600;
    color:#101010;
}
    </style>
    </head>
    <body role="document">

        <ul class="ball-placeholders">
          <li class="ball-placeholder"></li>
          <li class="ball-placeholder"></li>
          <li class="ball-placeholder"></li>
          <li class="ball-placeholder"></li>
          <li class="ball-placeholder"></li>
          <li class="ball-placeholder"></li>
        </ul>
        <ul class="lottery"></ul>
        <button class="next-ball">Next Ball</button>
        <button class="play-again">Play Again!</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    <script>
    var arr = new Array();
    $('.next-ball').on('click', function(){
      //generate random number between 1 and 50
      var random = Math.floor(Math.random()*50 ) + 1;
      // array to store css class references
      var classList = ["white-ball", "blue-ball", "pink-ball", "green-ball", "yellow-ball"];
      console.log(random);
      //if index of random number is less than 50
      if( arr.indexOf(random) == -1){
        //generate random number
        arr.push(random);
        //add css class to lottery-ball class relevant to array value range
        $('.lottery').append('<li class="lottery-ball ' + classList[Math.floor(random/10)] + '">' + random + '</li>');
      }
      // if the number already exists ignore and generate a new number
      else {
        console.log(random);
      }
      console.log(arr);
      //if lottery number calls is greater than 5 then switch button classes and send an alert to the user
      if ( $('.lottery').children().length > 5 ) {
        $('.next-ball').hide();
        $('.play-again').show();
        alert('Did You Win?');
      }

    });
    //If once the game is finished the user chooses to play again switch button classes
    $('.play-again').on('click', function(){
      $('.lottery').children().remove();
      arr = [];
      $('.next-ball').show();
      $('.play-again').hide();
    });
    </script>
    </body>
    </html>
</code>```

答:
Another alternative could be CSS attribute selectors. We could use the 'starts with' selector ^, which will target all elements whose attribute in question... well, starts with a particular string.

Say we give each li representing a ball a data-* attribute equal to its number. Then we can style their backgrounds like so:

```<code>li[data-number^=0] {
  /*target numbers less than 10
    Need to append 0 in front of numbers  <10
    for this to work*/
  background: white;
}

li[data-number^=1] {
  /*target numbers in the teens*/
  background: blue;
}

li[data-number^=2] {
  /*target numbers in the twenties*/
  background:pink;
}
 /*...and so on...*/
</code>```

Then the JS is somewhat simplified to:

```<code>if (arr.indexOf(random) == -1) {
  arr.push(random);
  $('.lottery').append('<li class="lottery-ball" data-number="' + (random < 10 ? '0' : '') + random + '">' + random + '</li>';
}
</code>```

EDIT: here's a link for other types of attribute selectors.

Body:
I'm making a lottery random number generator and have it working, all I want to do is change the background colour of the ball varying on what number range its called between. The second block of code is what I have come up with so far.

For example

o 1-9: White
o 10-19: Blue
o 20-29: Ping,
o 30-39: Green,
o 40-49: Yellow

    <!DOCTYPE html>

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1">

      <title>NRONLINE - Buckinghamshire Web Design, Digital Marketing Workshops and Kofax Consultancy</title>

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <button class="next-ball">Next Ball</button>
        <button class="play-again">Play Again!</button>

Body:
Another alternative could be CSS attribute selectors. We could use the 'starts with' selector ^, which will target all elements whose attribute in question... well, starts with a particular string.

Say we give each li representing a ball a data-* attribute equal to its number. Then we can style their backgrounds like so:

li[data-number^=0] {
  /*target numbers less than 10
    Need to append 0 in front of numbers  <10
    for this to work*/
  background: white;
}

li[data-number^=1] {
  /*target numbers in the teens*/
  background: blue;
}

li[data-number^=2] {
  /*target numbers in the twenties*/
  background:pink;
}
 /*...and so on...*/

Then the JS is somewhat simplified to:

if (arr.indexOf(random) == -1) {
  arr.push(random);
  $('.lottery').append('<li class="lottery-ball" data-number="' + (random < 10 ? '0' : '') + random + '">' + random + '</li>';
}

EDIT: here's a link for other types of attribute selectors.


来源: stackexchange

问:
Unreachable IP Socket Close Time in Windows OS
These codes provide send data via User Datagram Protocol. There are two codes at below. When I use the first code for unreachable Ip address I got the three-second delay.

Please Look New Results Title

JUST OPEN NEW C# CONSOLE APP AND PASTE THESE CODES IN IT. (FIRST CODE)

```<code>using System;
using System.Net;
using System.Net.Sockets;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = { 1, 20, 60, 44, 244 };
            while (true)
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                try
                {
                    using (var client = new UdpClient())
                    {
                        // Please check IP Address, It must be unreachable...
                       // IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.141"), 55600);
                      //  client.Connect(ep);
                        client.Send(data, data.Length, "192.168.1.141" , 55600);
                    }
                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                    Console.WriteLine("    ");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}
</code>```

Test 1(with using): Reachable IP

  Test 2(with using): Unreachable IP

  Output:

  Test1    label1 ---> h:mm:ss         label2 ---> h:mm:ss (Same Time)

  Test2      label1 ---> h:mm:ss        label2 ---> h:mm:ss +3 second

  (No exception)

WireShark Results:

  Test 1(with using) : Reachable Ip --> Data is caught, seen.

  Test 2(with using) : Unreachable IP-> No data.

When I use without "using" blocks, I didn't get the three-second
  delay.

JUST OPEN NEW C# CONSOLE APP AND PASTE THESE CODES IN IT. (SECOND CODE)

```<code>using System;
using System.Net;
using System.Net.Sockets;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = { 1, 20, 60, 44, 244 };
            while (true)
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                try
                {
                    var client = new UdpClient();
                    //Please check IP address, It must be unreachable...
                   // IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.41"), 5600);
                   // client.Connect(ep);
                    client.Send(data, data.Length, "192.168.1.141", 55600);

                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                }
                catch (Exception xe)
                {
                    Console.WriteLine(xe.ToString());
                }
                Console.WriteLine("   ");
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}
</code>```

Test 1(without using) : Reachable Ip

  Test 2(without using) : Unreachable Ip

Output:

  Test1     label1 ---> h:mm:ss (Same Time)      label2 ---> h:mm:ss (Same Time)

  Test2     label1 ---> h:mm:ss (Same Time)      label2 ---> h:mm:ss (Same Time)

  (No exception)

WireShark Results:

  Test 1(without using) : Reachable Ip --> Data is caught, seen.

  Test 2(without using) : Unreachable IP-> No data.

What is the mean of that three-second delay?

I am not sure but I think I have to use "using" blocks because if I didn't use the blocks memory usage will increase very high stage.
What is the difference between both codes? Which one is more reliable? Is there any better way? I don't want the three-second delay.

How to decrease three-second delay to zero?

Thanks in advance...

NEW RESULTS

I have tried socket Close/Dispose for unreachable IP with Python Programming
  Language in Windows OS.  I got same result namely three-second delay for unreachable
  IP. But when I try same Python code within Ubuntu 15.10, I didn't get
  the three-second delay.

```<code>import socket
import datetime

IPADDR = '192.168.1.141'
PORTNUM = 5600
PACKETDATA = "f1a525da11f6".encode()

while(True):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    s.connect((IPADDR, PORTNUM))
    s.send(PACKETDATA)
    print(datetime.datetime.now())
    s.close()
</code>```

答:
The actual difference is that Dispose() method is not called on client in SECOND CODE. But Dispose() is called in FIRST CODE with using (var client = new UdpClient()). The Dispose() method takes 3 seconds additional time when called after attempt to connect unreachable IP Addresses.

You can SECOND CODE as below to notice the delay in printing last label. The delay is caused by Dispose. The client must be declare above try block to use it in finally block.

```<code>finally
{
    if (client != null)
        ((IDisposable)client).Dispose();
}
Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
</code>```

I have also noticed that delay is not caused if unreachable IP Address is out of the domain. For example if IP of my PC is 192.168.1.20 and I try to access 202.22.1.88 then delay is not seen.

Conclusion is: delay is caused by Dispose(). But behavior of Dispose() should be further investigated.

ContentLicense: CC BY-SA 3.0

Body:
These codes provide send data via User Datagram Protocol. There are two codes at below. When I use the first code for unreachable Ip address I got the three-second delay.

Please Look New Results Title

JUST OPEN NEW C# CONSOLE APP AND PASTE THESE CODES IN IT. (FIRST CODE)

using System;
using System.Net;
using System.Net.Sockets;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = { 1, 20, 60, 44, 244 };
            while (true)
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                try
                {
                    using (var client = new UdpClient())
                    {
                        // Please check IP Address, It must be unreachable...
                       // IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.141"), 55600);
                      //  client.Connect(ep);
                        client.Send(data, data.Length, "192.168.1.141" , 55600);
                    }
                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                    Console.WriteLine("    ");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}

Test 1(with using): Reachable IP

  Test 2(with using): Unreachable IP

  Output:

  Test1    label1 ---> h:mm:ss         label2 ---> h:mm:ss (Same Time)

  Test2      label1 ---> h:mm:ss        label2 ---> h:mm:ss +3 second

  (No exception)

WireShark Results:

  Test 1(with using) : Reachable Ip --> Data is caught, seen.

  Test 2(with using) : Unreachable IP-> No data.

When I use without "using" blocks, I didn't get the three-second
  delay.

JUST OPEN NEW C# CONSOLE APP AND PASTE THESE CODES IN IT. (SECOND CODE)

using System;
using System.Net;
using System.Net.Sockets;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = { 1, 20, 60, 44, 244 };
            while (true)
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                try
                {
                    var client = new UdpClient();
                    //Please check IP address, It must be unreachable...
                   // IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.41"), 5600);
                   // client.Connect(ep);
                    client.Send(data, data.Length, "192.168.1.141", 55600);

                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                }
                catch (Exception xe)
                {
                    Console.WriteLine(xe.ToString());
                }
                Console.WriteLine("   ");
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}

Test 1(without using) : Reachable Ip

  Test 2(without using) : Unreachable Ip

Output:

  Test1     label1 ---> h:mm:ss (Same Time)      label2 ---> h:mm:ss (Same Time)

  Test2     label1 ---> h:mm:ss (Same Time)      label2 ---> h:mm:ss (Same Time)

  (No exception)

WireShark Results:

  Test 1(without using) : Reachable Ip --> Data is caught, seen.

  Test 2(without using) : Unreachable IP-> No data.

What is the mean of that three-second delay?

I am not sure but I think I have to use "using" blocks because if I didn't use the blocks memory usage will increase very high stage.
What is the difference between both codes? Which one is more reliable? Is there any better way? I don't want the three-second delay.

How to decrease three-second delay to zero?

Thanks in advance...

NEW RESULTS

I have tried socket Close/Dispose for unreachable IP with Python Programming
  Language in Windows OS.  I got same result namely three-second delay for unreachable
  IP. But when I try same Python code within Ubuntu 15.10, I didn't get
  the three-second delay.

import socket
import datetime

IPADDR = '192.168.1.141'
PORTNUM = 5600
PACKETDATA = "f1a525da11f6".encode()

while(True):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    s.connect((IPADDR, PORTNUM))
    s.send(PACKETDATA)
    print(datetime.datetime.now())
    s.close()

Body:
The actual difference is that Dispose() method is not called on client in SECOND CODE. But Dispose() is called in FIRST CODE with using (var client = new UdpClient()). The Dispose() method takes 3 seconds additional time when called after attempt to connect unreachable IP Addresses.

You can SECOND CODE as below to notice the delay in printing last label. The delay is caused by Dispose. The client must be declare above try block to use it in finally block.

finally
{
    if (client != null)
        ((IDisposable)client).Dispose();
}
Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));

I have also noticed that delay is not caused if unreachable IP Address is out of the domain. For example if IP of my PC is 192.168.1.20 and I try to access 202.22.1.88 then delay is not seen.

Conclusion is: delay is caused by Dispose(). But behavior of Dispose() should be further investigated.


问:
Prevent user to input value larger than from other input value
How do i prevent and give alert so user can't input the value of totalontarget and totalofftarget to be larger than totalofservices</p>

```<code><script>
   $(document).ready(function() {
     $('.totalofservices').keyup(function(){
       $(this).closest('tr').find(".totalontarget").val($(this).val());
       $(this).closest('tr').find(".totalofftarget").val("0");
     });
   });
</script>

for($x = 1; $x <= 3; ++$x) {
    echo "
    <tr>
      <td>Zone $x</td>
      <td><input style='text-align:center' class='form-control totalofservices' type='text' size='20' id='totalofservices[]' name='totalofservices'></td>
      <td><input style='text-align:center' class='form-control totalontarget' type='text' size='20' id='totalontarget' name='totalontarget[]'></td>
      <td><input style='text-align:center' class='form-control totalofftarget' type='text' size='20' id='totalofftarget' name='totalofftarget[]'></td>
    </tr>";
}
</code>```

答:
Check this out : https://jqueryvalidation.org/.
Anyway, even if client validation could look more user-friendly, it should be implemented also in the server side.</p>

Body:
How do i prevent and give alert so user can't input the value of totalontarget and totalofftarget to be larger than totalofservices

for($x = 1; $x <= 3; ++$x) {
    echo "

      Zone $x
      <input style='text-align:center' class='form-control totalofservices' type='text' size='20' id='totalofservices[]' name='totalofservices'>
      <input style='text-align:center' class='form-control totalontarget' type='text' size='20' id='totalontarget' name='totalontarget[]'>
      <input style='text-align:center' class='form-control totalofftarget' type='text' size='20' id='totalofftarget' name='totalofftarget[]'>

";
}


问:
How to change the mat type in openCV
I used mat1.convertTo(mat1, mat2.type())but the type ofmat1and mat2 are not the same. Why is that?

答:
Not all functions are in-place. This means that if you are calling the function on mat1, then the destination matrix must be different. So try declaring another matrix and test the function.

```<code>mat1.convertTo(mat1_new, mat2.type())
</code>```

Title: How to change the mat type in openCV

Body:
Not all functions are in-place. This means that if you are calling the function on mat1, then the destination matrix must be different. So try declaring another matrix and test the function.

mat1.convertTo(mat1_new, mat2.type())


问:
WebApp ignores patched perl pm file
I never really came in touch with perl before, so I really hope, this is a real newbie question and I can solve the problem pretty quick...

We've one perl based web application installed on a windows 2003 server environment. The installed version contains a bug and I know where to apply the patch. Basically: I have carefully changed two lines in one of the web apps pm files.

To my surprise, the file change is ignored and I still get the same error messages with references to the old version of the file - clearly identifiable by the line numbers.

I've cleared the browser caches, restarted the web application (including apache) - no luck.

Now I think/hope that this is some kind of perl feature, but I even don't know enough of that language to ask google the right questions. One tutorial said, that perl is an interpreted language and that changes to source files are effective immediately. This isn't true for my site...

Are there some more caches/files I have to touch or delete in order to make my changes effective?

答:
Problem solved and the solution was outside perl - thanks for your patience.

The web application contained some javascript / css caching. After

deleting the caches (js-chache, css-cache)

clearing the browser cache

restarting Internet Explorer (!)

it started working again. Don't ask me why...

ContentLicense: CC BY-SA 2.5

Title: WebApp ignores patched perl pm file


问:
How to find the distance between 2 points in 2 different dataframes in pandas?
I've got two dataframes, each with a set of coordinates. Dataframe 1 is a list of biomass sites, with coordinates in columns 'lat' and 'lng'. Dataframe 2 is a list of postcode coordinates, linked to sale price, with coordinates in columns 'pc_lat' and 'pc_lng'.

I've used this stackoverflow question to work out the closest biomass site to each property. This is the code I am using:

```<code>def dist(lat1, long1, lat2, long2):
return np.abs((lat1-lat2)+(long1-long2))

def find_site(lat, long):
    distances = biomass.apply(
        lambda row: dist(lat, long, row['lat'], row['lng']),
        axis=1)
    return biomass.loc[distances.idxmin(),'Site Name']

hp1995['BiomassSite'] = hp1995.apply(
    lambda row: find_site(row['pc_lat'], row['pc_long']),
    axis=1)

print(hp1995.head())
</code>```

This has worked well, in that I've got the name of the closest Biomass generation site, however I want to know the distance calculated between these two sites.

How would I calculate the distance?

What metric would the output distance be in? I am trying to find properties within 2km from the biomass site.

答:
To calculate distance between two global coordinates you should use the Haversine Formula, based on this page I have implemented the following method:

```<code>import math
def distanceBetweenCm(lat1, lon1, lat2, lon2):
    dLat = math.radians(lat2-lat1)
    dLon = math.radians(lon2-lon1)

    lat1 = math.radians(lat1)
    lat2 = math.radians(lat2)

    a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLon/2) * math.sin(dLon/2) * math.cos(lat1) * math.cos(lat2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    return c * 6371 * 100000 #multiply by 100k to get distance in cm
</code>```

You can also modify it  to return different units, by multiplying by different powers of 10. In the example a multiplication by 100k results in units in centimeters. Without multiplying the method returns distance in km. From there you could perform more unit conversions if necessary .

Edit: As suggested in the comments, one possible optimization for this would be using power operators instead of regular multiplication, like this:

```<code>a = math.sin(dLat/2)**2 + math.sin(dLon/2)**2 * math.cos(lat1) * math.cos(lat2)
</code>```

Take a look at this question to read more about different speed complexities of calculating powers in python.

Body:
I've got two dataframes, each with a set of coordinates. Dataframe 1 is a list of biomass sites, with coordinates in columns 'lat' and 'lng'. Dataframe 2 is a list of postcode coordinates, linked to sale price, with coordinates in columns 'pc_lat' and 'pc_lng'.

I've used this stackoverflow question to work out the closest biomass site to each property. This is the code I am using:

def dist(lat1, long1, lat2, long2):
return np.abs((lat1-lat2)+(long1-long2))

def find_site(lat, long):
    distances = biomass.apply(
        lambda row: dist(lat, long, row['lat'], row['lng']),
        axis=1)
    return biomass.loc[distances.idxmin(),'Site Name']

hp1995['BiomassSite'] = hp1995.apply(
    lambda row: find_site(row['pc_lat'], row['pc_long']),
    axis=1)

print(hp1995.head())

This has worked well, in that I've got the name of the closest Biomass generation site, however I want to know the distance calculated between these two sites.

How would I calculate the distance?

What metric would the output distance be in? I am trying to find properties within 2km from the biomass site.

Body:
To calculate distance between two global coordinates you should use the Haversine Formula, based on this page I have implemented the following method:

import math
def distanceBetweenCm(lat1, lon1, lat2, lon2):
    dLat = math.radians(lat2-lat1)
    dLon = math.radians(lon2-lon1)

    lat1 = math.radians(lat1)
    lat2 = math.radians(lat2)

    a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLon/2) * math.sin(dLon/2) * math.cos(lat1) * math.cos(lat2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    return c * 6371 * 100000 #multiply by 100k to get distance in cm

You can also modify it  to return different units, by multiplying by different powers of 10. In the example a multiplication by 100k results in units in centimeters. Without multiplying the method returns distance in km. From there you could perform more unit conversions if necessary .

Edit: As suggested in the comments, one possible optimization for this would be using power operators instead of regular multiplication, like this:

a = math.sin(dLat/2)**2 + math.sin(dLon/2)**2 * math.cos(lat1) * math.cos(lat2)

Take a look at this question to read more about different speed complexities of calculating powers in python.


问:
Aggregate rows of Spark DataFrame to String after groupby
I'm quite new both Spark and Scale and could really need a hint to solve my problem. So I have two DataFrames A (columns id and name) and B (columns id and text) would like to join them, group by id and combine all rows of text into a single String:

A

```<code>+--------+--------+
|      id|    name|
+--------+--------+
|       0|       A|
|       1|       B|
+--------+--------+
</code>```

B

```<code>+--------+ -------+
|      id|    text|
+--------+--------+
|       0|     one|
|       0|     two|
|       1|   three|
|       1|    four|
+--------+--------+
</code>```

desired result:

```<code>+--------+--------+----------+
|      id|    name|     texts|
+--------+--------+----------+
|       0|       A|   one two|
|       1|       B|three four|
+--------+--------+----------+
</code>```

So far I'm trying the following:

```<code>var C = A.join(B, "id")
var D = C.groupBy("id", "name").agg(collect_list("text") as "texts")
</code>```

This works quite well besides that my texts column is an Array of Strings instead of a String. I would appreciate some help very much.

答:
I am just adding some minor functions in yours to give the right solution, which is </p>

```<code>A.join(B, Seq("id"), "left").orderBy("id").groupBy("id", "name").agg(concat_ws(" ", collect_list("text")) as "texts")
</code>```

Body:
I'm quite new both Spark and Scale and could really need a hint to solve my problem. So I have two DataFrames A (columns id and name) and B (columns id and text) would like to join them, group by id and combine all rows of text into a single String:

A

+--------+--------+
|      id|    name|
+--------+--------+
|       0|       A|
|       1|       B|
+--------+--------+

B

+--------+ -------+
|      id|    text|
+--------+--------+
|       0|     one|
|       0|     two|
|       1|   three|
|       1|    four|
+--------+--------+

desired result:

+--------+--------+----------+
|      id|    name|     texts|
+--------+--------+----------+
|       0|       A|   one two|
|       1|       B|three four|
+--------+--------+----------+

So far I'm trying the following:

var C = A.join(B, "id")
var D = C.groupBy("id", "name").agg(collect_list("text") as "texts")

This works quite well besides that my texts column is an Array of Strings instead of a String. I would appreciate some help very much.

Body:
I am just adding some minor functions in yours to give the right solution, which is

A.join(B, Seq("id"), "left").orderBy("id").groupBy("id", "name").agg(concat_ws(" ", collect_list("text")) as "texts")


问:
Lambda S3 Put function not triggering for larger files
I am currently exploring storing the attachments of an email separately from the .eml file itself. I have an SES rule set that delivers an inbound email to a bucket. When the bucket retrieves the email, an S3 Put Lambda function parses the raw email (MIME format), base64 decodes the attachment buffers, and does a putObject for each attachment and the original .eml file to a new bucket.

My problem is that this Lambda function does not trigger for emails with attachments exceeding ~3-4 MB. The email is received and stored in the initial bucket, but the function does not trigger when it is received. Also, the event does not appear in CloudWatch. However, the function works perfectly fine when manually testing it with a hardcoded S3 Put payload, and also when manually uploading a .eml file to the assigned bucket.

Do you have any idea why there is this limitation? Perhaps this is a permission issue with the bucket or maybe an issue with the assigned Lambda role? When manually testing I’ve found this is by no means a timeout or exceeding max memory used issue.

答: I faced the same issue.If the Etag of the file you uploaded to S3 ends with a hyphen followed by a number then it denotes the file was uploaded using Multipart. Subscribing to CompleteMultipartUpload Event resolved the issue.</p>


问:
How to add angular material design to jhipster
I am trying to add material desing to jhipster generated gateway. Although it seems it is working I am getting this warning on console;

```<code>Could not find Angular Material core theme. Most Material components may not work as expected. For more info refer to the theming guide: https://material.angular.io/guide/theming
Could not find HammerJS. Certain Angular Material components may not work correctly.
</code>```

Below lines are added to package.json dependencies

```<code>"@angular/material": "^2.0.0-beta.7",
"hammerjs": "^2.0.8",
</code>```

Below lines are added to global.scss

```<code>@import url('https://fonts.googleapis.com/css?family=Roboto:300,400,400i,500,700');
@import '~@angular/material/prebuilt-themes/indigo-pink.css';
</code>```

Just note that if I comment out indigo-pink.css line UI becomes uglier so I conclude that this css is imported successfully when not commented.

Jhipster version is  4.5.6

What can be the reason for the warning

Edit 1: this solves the hammerjs warning https://stackoverflow.com/a/41322757/795168 , but still theme warning and problem on UI is continues

答:
Install the @angular/material library and add the dependency to package.json

```<code>npm install --save @angular/material
</code>```

Import the Angular Material NgModule into your app module...

```<code>import { MaterialModule } from '@angular/material';

@NgModule({
  imports: [
  ...
  MaterialModule
 ],
  ...
})
</code>```

Now that the project is set up, it must be configured to include the CSS for a theme. Angular Material ships with some prebuilt theming, which is located in node_modules/@angular/material/prebuilt-themes/.

To add an angular CSS theme and material icons to your app

```<code>@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';
@import '~https://fonts.googleapis.com/icon?family=Material+Icons';
</code>```

please check with the link Install Angular Material

Body:
I am trying to add material desing to jhipster generated gateway. Although it seems it is working I am getting this warning on console;

Could not find Angular Material core theme. Most Material components may not work as expected. For more info refer to the theming guide: https://material.angular.io/guide/theming
Could not find HammerJS. Certain Angular Material components may not work correctly.

Below lines are added to package.json dependencies

"@angular/material": "^2.0.0-beta.7",
"hammerjs": "^2.0.8",

Below lines are added to global.scss

@import url('https://fonts.googleapis.com/css?family=Roboto:300,400,400i,500,700');
@import '~@angular/material/prebuilt-themes/indigo-pink.css';

Just note that if I comment out indigo-pink.css line UI becomes uglier so I conclude that this css is imported successfully when not commented.

Jhipster version is  4.5.6

What can be the reason for the warning

Edit 1: this solves the hammerjs warning https://stackoverflow.com/a/41322757/795168 , but still theme warning and problem on UI is continues

Body:
Install the @angular/material library and add the dependency to package.json

npm install --save @angular/material

Import the Angular Material NgModule into your app module...

import { MaterialModule } from '@angular/material';

@NgModule({
  imports: [
  ...
  MaterialModule
 ],
  ...
})

Now that the project is set up, it must be configured to include the CSS for a theme. Angular Material ships with some prebuilt theming, which is located in node_modules/@angular/material/prebuilt-themes/.

To add an angular CSS theme and material icons to your app

@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';
@import '~https://fonts.googleapis.com/icon?family=Material+Icons';

please check with the link Install Angular Material


问:
Linq to SQL: .FirstOrDefault() not applicable to select new { ... }
I just asked this question. Which lead me to a new question :)

Up until this point, I have used the following pattern of selecting stuff with Linq to SQL, with the purpose of being able to handle 0 "rows" returned by the query:

```<code>var person = (from p in [DataContextObject].Persons
              where p.PersonsID == 1
              select new p).FirstOrDefault();

if (person == null)
{
    // handle 0 "rows" returned.
}
</code>```

But I can't use FirstOrDefault() when I do:

```<code>var person = from p in [DataContextObject].Persons
             where p.PersonsID == 1
             select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode };

// Under the hood, this pattern generates a query which selects specific
// columns which will be faster than selecting all columns as the above
// snippet of code does. This results in a performance-boost on large tables.
</code>```

How do I check for 0 "rows" returned by the query, using the second pattern?

UPDATE:

I think my build fails because I am trying to assign the result of the query to a variable (this._user) declared with the type of [DataContext].User.

```<code>this._user = (from u in [DataContextObject].Users
              where u.UsersID == [Int32]
              select new { u.UsersID }).FirstOrDefault();
</code>```

Compilation error: Cannot implicitly convert type "AnonymousType#1" to "[DataContext].User".

Any thoughts on how I can get around this? Would I have to make my own object?

答:
Update:

I see now what you were actually asking!  Sorry, my answer no longer applies.  I thought you were not getting a null value when it was empty. The accepted response is correct, if you want to use the object out of scope, you need to create a new type and just use New MyType(...).  I know DevEx's RefactorPro has a refactoring for this, and I think resharper does as well.

Call .FirstOrDefault(null) like this:

```<code>string[] names = { "jim", "jane", "joe", "john", "jeremy", "jebus" };
var person = (
    from p in names where p.StartsWith("notpresent") select
        new { Name=p, FirstLetter=p.Substring(0,1) }
    )
    .DefaultIfEmpty(null)
    .FirstOrDefault();

MessageBox.Show(person==null?"person was null":person.Name + "/" + person.FirstLetter);
</code>```

That does the trick for me.

OwnerDisplayName: roosteronacid

Body:
I just asked this question. Which lead me to a new question :)

Up until this point, I have used the following pattern of selecting stuff with Linq to SQL, with the purpose of being able to handle 0 "rows" returned by the query:

var person = (from p in [DataContextObject].Persons
              where p.PersonsID == 1
              select new p).FirstOrDefault();

if (person == null)
{
    // handle 0 "rows" returned.
}

But I can't use FirstOrDefault() when I do:

var person = from p in [DataContextObject].Persons
             where p.PersonsID == 1
             select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode };

// Under the hood, this pattern generates a query which selects specific
// columns which will be faster than selecting all columns as the above
// snippet of code does. This results in a performance-boost on large tables.

How do I check for 0 "rows" returned by the query, using the second pattern?

UPDATE:

I think my build fails because I am trying to assign the result of the query to a variable (this._user) declared with the type of [DataContext].User.

this._user = (from u in [DataContextObject].Users
              where u.UsersID == [Int32]
              select new { u.UsersID }).FirstOrDefault();

Compilation error: Cannot implicitly convert type "AnonymousType#1" to "[DataContext].User".

Any thoughts on how I can get around this? Would I have to make my own object?

LastEditorDisplayName: roosteronacid

Body:
Update:

I see now what you were actually asking!  Sorry, my answer no longer applies.  I thought you were not getting a null value when it was empty. The accepted response is correct, if you want to use the object out of scope, you need to create a new type and just use New MyType(...).  I know DevEx's RefactorPro has a refactoring for this, and I think resharper does as well.

Call .FirstOrDefault(null) like this:

string[] names = { "jim", "jane", "joe", "john", "jeremy", "jebus" };
var person = (
    from p in names where p.StartsWith("notpresent") select
        new { Name=p, FirstLetter=p.Substring(0,1) }
    )
    .DefaultIfEmpty(null)
    .FirstOrDefault();

MessageBox.Show(person==null?"person was null":person.Name + "/" + person.FirstLetter);

That does the trick for me.

OwnerDisplayName: Andrew

LastEditorDisplayName: Andrew


问:
recover lost C# pages
I had a problem I lost all my source(CS) of web site pages but I had only published pages on server ,so please if there is any way to recover theses published pages to orignal pages with code,bin folder</p>

答: try to use reflector. it help you to restore all your code</p>

Title: recover lost C# pages


问:
functions in functions nodejs
I want to get the klout score using a screen name (twitter).

I did this. I know it doesn't work like that, but I don't know how it should work.

```<code>function get_klout(screenName){
  klout.getKloutIdentity(screenName, function(error, klout_user) {
    klout.getUserScore(klout_user.id, function(error, klout_response) {
       return Math.round(klout_response.score);
    });
  });
}
</code>```

I want my function to return this number Math.round(klout_response.score);

答:
Because this is an asynchronous function you cannot use return, in order to return result from asynchronous code pass to your function callback and return the result on the callback. you should handle errors in your callbacks.    </p>

```<code>  function get_klout(screenName, callback){
  klout.getKloutIdentity(screenName, function(error, klout_user) {
    if (err){
      callback(error);
      return
    }
    klout.getUserScore(klout_user.id, function(error, klout_response) {
      if (err){
        callback(error);
        return
      }
      callback(null, klout_response.score);
    });
  });
}

get_klout(screenName, function(err, res){
  if (err){
    console.log(err);
    return
  }
  console.log(res);
});
</code>```

Title: functions in functions nodejs

Body:
I want to get the klout score using a screen name (twitter).

I did this. I know it doesn't work like that, but I don't know how it should work.

function get_klout(screenName){
  klout.getKloutIdentity(screenName, function(error, klout_user) {
    klout.getUserScore(klout_user.id, function(error, klout_response) {
       return Math.round(klout_response.score);
    });
  });
}

I want my function to return this number Math.round(klout_response.score);

Body:
Because this is an asynchronous function you cannot use return, in order to return result from asynchronous code pass to your function callback and return the result on the callback. you should handle errors in your callbacks.

  function get_klout(screenName, callback){
  klout.getKloutIdentity(screenName, function(error, klout_user) {
    if (err){
      callback(error);
      return
    }
    klout.getUserScore(klout_user.id, function(error, klout_response) {
      if (err){
        callback(error);
        return
      }
      callback(null, klout_response.score);
    });
  });
}

get_klout(screenName, function(err, res){
  if (err){
    console.log(err);
    return
  }
  console.log(res);
});


问:
Errors not being recorded to php error log
No matter what I do I cannot get php to log errors to a log file.

All the error parameters are set as follows (taken from phpinfo read out):

```<code>display_errors =    On
error_append_string = no value
error_log = C:\inetpub\logs\php-error.log
error_prepend_string =  no value
error_reporting = 22519
html_errors = On
ignore_repeated_errors = Off
track_errors = On
xmlrpc_error_number = 0
xmlrpc_errors = Off
</code>```

Am I missing something?

答:
The problem appears to have been:

The specified location for the error-log could not be written to by php. I have specified a new location for the log file and it now works.

In terms of screen display of errors I had display_errors set to "On" in the php.ini file and even though phpinfo showed display_errors as being on, it appears they weren't. Changing "On" to "1" in the ini file seems to have done the trick.

Body:
No matter what I do I cannot get php to log errors to a log file.

All the error parameters are set as follows (taken from phpinfo read out):

display_errors =    On
error_append_string = no value
error_log = C:\inetpub\logs\php-error.log
error_prepend_string =  no value
error_reporting = 22519
html_errors = On
ignore_repeated_errors = Off
track_errors = On
xmlrpc_error_number = 0
xmlrpc_errors = Off

Am I missing something?


问:
C# Convert an image from color to a black and white
I've tried several examples from here but have not found anything that works.

I need to be able to convert a color image to black and white so that I can take that data and send it to a thermal printer.

Getting the image from color to black and white seems to be the trouble as I've found no methods in the C# libraries.

The image I'm testing with is a PixelFormat.Format32bppArgb and I believe I want to covert that down to PixelFormat.Format1bppIndexed

EDIT: Not sure how I can make it any clearer.  I don't want greyscale I want black and white which is what "PixelFormst.Format1bppIndexed"

答:
enter image description here

You can use this codes for converting image to black and white.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Converting_Image_to__Black_and_White
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public static int siyahbeyazsinirnoktasi=0;
    public static string DosyaYolu = "";

    #region resim üzerinde işlemler yapma (siyah beyaz)

    Bitmap BlackandWhite(Bitmap Goruntu)

    {

        Bitmap yeniGoruntu = new Bitmap(Goruntu.Width,
     Goruntu.Height);//Bitmap sınıfımızı oluşturduk.

        double toplampikselsayisi = Goruntu.Width * Goruntu.Height;
        int GriTonlama;

        for (int i = 0; i < Goruntu.Width; i++)//resmi yatay olarak
taramak için

        {

            for (int j = 0; j < Goruntu.Height; j++)//resmi dikey olarak
taramak için

            {

                Color Pixel = Goruntu.GetPixel(i, j);//color sınıfını ile
pixel rengini alıyoruz.

                GriTonlama = (Pixel.R + Pixel.G + Pixel.B) / 3;//almış
olduğumuz renk değerini gri tona çevirmek için kullanmamız gereken
formül.

                if (GriTonlama < siyahbeyazsinirnoktasi)
                {

                    yeniGoruntu.SetPixel(i, j, Color.FromArgb(0, 0,
0));//yeni görüntümüze gri tonlamadaki pixel değerini veriyoruz.
                }

                if (GriTonlama >= siyahbeyazsinirnoktasi)
                {

                    yeniGoruntu.SetPixel(i, j, Color.FromArgb(255, 255,
255));//yeni görüntümüze gri tonlamadaki pixel değerini veriyoruz.
                }

            }

        }

        return yeniGoruntu;
    }
    #endregion

    private void btnLoadImage_Click(object sender, EventArgs e)
    {

        FolderBrowserDialog Klasor = new FolderBrowserDialog();
        openFileDialog1.Title = "Resimdosyası seçiniz.";
        openFileDialog1.Filter = "Image files (*.jpg)|*.jpg|Tüm
dosyalar(*.*)|*.*";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
             DosyaYolu = openFileDialog1.FileName;
            var dosyaboyutu = new FileInfo(DosyaYolu).Length;

            if (dosyaboyutu <= 500000)
            {
                pictureBox1.Image = new
Bitmap(openFileDialog1.OpenFile());
                btnConvertBlackandWhite.Enabled = true;
                label1.Visible = true;
                label2.Visible= true;
                label3.Visible = true;
                label4.Visible = true;
                label5.Visible = true;
                label6.Visible = true;
                trackBar1.Visible = true;

            }

            else
            {
                MessageBox.Show("Seçtiğiniz resim boyutu 500 KB'nın
altında olmalıdır.");
            }

        }

    }

    private void btnConvertBlackandWhite_Click(object sender, EventArgs
 e)
    {
        pictureBox1.Image = BlackandWhite(new Bitmap(DosyaYolu));
        btnSave.Enabled = true;

    }

    private void trackBar1_Scroll(object sender, EventArgs e)
    {
        siyahbeyazsinirnoktasi = trackBar1.Value ;
        label3.Text = Convert.ToString(siyahbeyazsinirnoktasi);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        label3.Text = "130";
        siyahbeyazsinirnoktasi = 130;
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        {

            Image pngoptikform = new Bitmap(pictureBox1.Image);
            SaveFileDialog sf = new SaveFileDialog();//yeni bir kaydetme
diyaloğu oluşturuyoruz.

            sf.Filter = "Image file (Jpg dosyası (*.jpg)|*.jpg  ";//.bmp
veya .jpg olarak kayıt imkanı sağlıyoruz.

            sf.Title = "Kayıt";//diğaloğumuzun başlığını belirliyoruz.

            sf.CheckPathExists = true;
            sf.DefaultExt = "jpg";
            sf.FilterIndex = 1;

            DialogResult sonuc = sf.ShowDialog();

            if (sonuc == DialogResult.OK)
            {

                if (sf.FilterIndex == 1)
                {
                    pngoptikform.Save(sf.FileName);
                    System.Diagnostics.Process.Start(sf.FileName);
                }

            }

        }
    }

}
}
</code>```

Body:
enter image description here

You can use this codes for converting image to black and white.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Converting_Image_to__Black_and_White
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public static int siyahbeyazsinirnoktasi=0;
    public static string DosyaYolu = "";

    #region resim üzerinde işlemler yapma (siyah beyaz)

    Bitmap BlackandWhite(Bitmap Goruntu)

    {

        Bitmap yeniGoruntu = new Bitmap(Goruntu.Width,
     Goruntu.Height);//Bitmap sınıfımızı oluşturduk.

        double toplampikselsayisi = Goruntu.Width * Goruntu.Height;
        int GriTonlama;

        for (int i = 0; i < Goruntu.Width; i++)//resmi yatay olarak
taramak için

        {

            for (int j = 0; j < Goruntu.Height; j++)//resmi dikey olarak
taramak için

            {

                Color Pixel = Goruntu.GetPixel(i, j);//color sınıfını ile
pixel rengini alıyoruz.

                GriTonlama = (Pixel.R + Pixel.G + Pixel.B) / 3;//almış
olduğumuz renk değerini gri tona çevirmek için kullanmamız gereken
formül.

                if (GriTonlama < siyahbeyazsinirnoktasi)
                {

                    yeniGoruntu.SetPixel(i, j, Color.FromArgb(0, 0,
0));//yeni görüntümüze gri tonlamadaki pixel değerini veriyoruz.
                }

                if (GriTonlama >= siyahbeyazsinirnoktasi)
                {

                    yeniGoruntu.SetPixel(i, j, Color.FromArgb(255, 255,
255));//yeni görüntümüze gri tonlamadaki pixel değerini veriyoruz.
                }

            }

        }

        return yeniGoruntu;
    }
    #endregion

    private void btnLoadImage_Click(object sender, EventArgs e)
    {

        FolderBrowserDialog Klasor = new FolderBrowserDialog();
        openFileDialog1.Title = "Resimdosyası seçiniz.";
        openFileDialog1.Filter = "Image files (*.jpg)|*.jpg|Tüm
dosyalar(*.*)|*.*";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
             DosyaYolu = openFileDialog1.FileName;
            var dosyaboyutu = new FileInfo(DosyaYolu).Length;

            if (dosyaboyutu <= 500000)
            {
                pictureBox1.Image = new
Bitmap(openFileDialog1.OpenFile());
                btnConvertBlackandWhite.Enabled = true;
                label1.Visible = true;
                label2.Visible= true;
                label3.Visible = true;
                label4.Visible = true;
                label5.Visible = true;
                label6.Visible = true;
                trackBar1.Visible = true;

            }

            else
            {
                MessageBox.Show("Seçtiğiniz resim boyutu 500 KB'nın
altında olmalıdır.");
            }

        }

    }

    private void btnConvertBlackandWhite_Click(object sender, EventArgs
 e)
    {
        pictureBox1.Image = BlackandWhite(new Bitmap(DosyaYolu));
        btnSave.Enabled = true;

    }

    private void trackBar1_Scroll(object sender, EventArgs e)
    {
        siyahbeyazsinirnoktasi = trackBar1.Value ;
        label3.Text = Convert.ToString(siyahbeyazsinirnoktasi);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        label3.Text = "130";
        siyahbeyazsinirnoktasi = 130;
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        {

            Image pngoptikform = new Bitmap(pictureBox1.Image);
            SaveFileDialog sf = new SaveFileDialog();//yeni bir kaydetme
diyaloğu oluşturuyoruz.

            sf.Filter = "Image file (Jpg dosyası (*.jpg)|*.jpg  ";//.bmp
veya .jpg olarak kayıt imkanı sağlıyoruz.

            sf.Title = "Kayıt";//diğaloğumuzun başlığını belirliyoruz.

            sf.CheckPathExists = true;
            sf.DefaultExt = "jpg";
            sf.FilterIndex = 1;

            DialogResult sonuc = sf.ShowDialog();

            if (sonuc == DialogResult.OK)
            {

                if (sf.FilterIndex == 1)
                {
                    pngoptikform.Save(sf.FileName);
                    System.Diagnostics.Process.Start(sf.FileName);
                }

            }

        }
    }

}
}


问:
How many endpoint and topic need for Direct ,Group,Channel in Spring Websocket?
I want to write application that make messaging between users,
Messages that send  between users is in 3 types

Direct

Channel: just send from admin

Group

My application will save messages in RDBMS. When new message send and receiver user is online ,my app will notify to user that new message receive , I decided to write my application using Spring Websocket and Stomp .My application using spring security and and i want show online users in group and direct for each other member
my question is  know how many endpoint and broker i need ? and how can do that.

Update:

My application is similar gitter and slack , when user login  messages may receive from direct or group or channel. when i switch between users and group or channel i will unsubscribe from last and subscribe to user or group that i chat in .i dont know subscribe and unsubscribe is correct or just one subscribe for all .
is this usage correct or not?

```<code>chatSocket.subscribe("/user/exchange/direct/chat.message/{userId}", function(message) {});

chatSocket.subscribe("/topic/group/chat.message/{groupId}", function(message) {});
</code>```

答:
For direct messages, use user destinations.

For messages that can only be sent by admins, restrict publishing to users with that role and allow other users to subscribe (with Spring Security)

If you want to broadcast messages, use broker destinations (or app destinations if you need to add some login)

An option to store messages could be adding a channel interceptor. Make users subscribe to an app destination when the websocket connection is established and send the stored messages sent while he was online.

This sample application could give you some hints: https://github.com/salmar/spring-websocket-chat

Body:
I want to write application that make messaging between users,
Messages that send  between users is in 3 types

Direct

Channel: just send from admin

Group

My application will save messages in RDBMS. When new message send and receiver user is online ,my app will notify to user that new message receive , I decided to write my application using Spring Websocket and Stomp .My application using spring security and and i want show online users in group and direct for each other member
my question is  know how many endpoint and broker i need ? and how can do that.

Update:

My application is similar gitter and slack , when user login  messages may receive from direct or group or channel. when i switch between users and group or channel i will unsubscribe from last and subscribe to user or group that i chat in .i dont know subscribe and unsubscribe is correct or just one subscribe for all .
is this usage correct or not?

chatSocket.subscribe("/user/exchange/direct/chat.message/{userId}", function(message) {});

chatSocket.subscribe("/topic/group/chat.message/{groupId}", function(message) {});


问:
How to chain JavaScript methods natively from an iterator?
Say I'm using js methods that have the 'this' returned, so one can chain like such:

```<code>something.add({a: 'xyz', b: 123}).add({a: 'abc', b: 456});
</code>```

How can I chain these on something from an iterator? For example:

```<code>$scope.bindings = [
     {
            key: 'up',
            func: function() {
                $scope.scroll(1)
            }
        },{
            key: 'down',
            func: function() {
                $scope.scroll(-1);
            }
        },
];
</code>```

---EDIT---

The library I was using is Angular hotkeys. I wanted to ask in a generic way to help anyone else in a similar position.

I have:

```<code>var hotBindings = hotkeys.bindTo(scope);

  for (var bind of scope.bindings) {
      hotBindings = hotBindings.add({
        combo: bind.key,
        callback: function(e) {
            e.preventDefault();
            bind.func();
         }
      })
 }
</code>```

This assigns the 'down' method to both keypresses. If I write out the code without the loop, using scope.bindings[index].key (for example) and chain the .add() method then it works. I also tried without "hotBindings =".

Please don't mention the scopve vs $scope as this is being passed into a link function in a angular directive - angular almost certainly has nothing to do with it.

答:
If you do this a lot (perhaps using different methods than just "add"), you might consider using a helper function:</p>

```<code>function chain(obj, ...calls) {
  for(let {method, args} of calls) {
    obj = obj[method](...args)
  }
  return obj
}
chain(new Somthing(), [
  {meth: 'add', args: [
    {x: 'hi', func: () => console.log('hi')}]},
  {meth: 'add', args: [
    {x: 'bye', func: () => console.log('bye')}]}
  ]})
</code>```

Body:
Say I'm using js methods that have the 'this' returned, so one can chain like such:

something.add({a: 'xyz', b: 123}).add({a: 'abc', b: 456});

How can I chain these on something from an iterator? For example:

$scope.bindings = [
     {
            key: 'up',
            func: function() {
                $scope.scroll(1)
            }
        },{
            key: 'down',
            func: function() {
                $scope.scroll(-1);
            }
        },
];

---EDIT---

The library I was using is Angular hotkeys. I wanted to ask in a generic way to help anyone else in a similar position.

I have:

var hotBindings = hotkeys.bindTo(scope);

  for (var bind of scope.bindings) {
      hotBindings = hotBindings.add({
        combo: bind.key,
        callback: function(e) {
            e.preventDefault();
            bind.func();
         }
      })
 }

This assigns the 'down' method to both keypresses. If I write out the code without the loop, using scope.bindings[index].key (for example) and chain the .add() method then it works. I also tried without "hotBindings =".

Please don't mention the scopve vs $scope as this is being passed into a link function in a angular directive - angular almost certainly has nothing to do with it.

Body:
If you do this a lot (perhaps using different methods than just "add"), you might consider using a helper function:

function chain(obj, ...calls) {
  for(let {method, args} of calls) {
    obj = obj[method](...args)
  }
  return obj
}
chain(new Somthing(), [
  {meth: 'add', args: [
    {x: 'hi', func: () => console.log('hi')}]},
  {meth: 'add', args: [
    {x: 'bye', func: () => console.log('bye')}]}
  ]})


问:
Swift - Sort a subset of an array
I currently have a tableview with a lot of users, but I would like to sort the users in a specific order, not just ascending or descending. Let's say I have an array with the following users.

```<code>"User1", "1st grade"
"User2", "1st grade"
"User3", "kids"
"User4", "6th grade"
"User5", "5th grade"
"User6", "2nd grade"
"User7", "kids"
"User8", "juniors"
</code>```

How can I order my array so that all the students who are in kids class are the first to be displayed, followed by all the classes with numbers (in order) and then all the Juniors.

I want an array that can display this

```<code>"User3", "kids"
"User7", "kids"
"User1", "1st grade"
"User2", "1st grade"
"User6", "2nd grade"
"User5", "5th grade"
"User4", "6th grade"
"User8", "juniors"
</code>```

Edit:
Updated the text to make clear that the array has two columns, not just one string.

Was able to achieve it by using the line below

```<code>let sortedArray =
self.userArray.sorted(by: { $0.SchoolGrade!.gradeLongName().contains("Kids") ||
$1.SchoolGrade!.gradeLongName().contains("Juniors") })
</code>```

答:
What you are trying to sort is not common sort routine. So firstly, check your data structure for better sort solution.

But if you insist use your string list to sort, then you can try the following code (very ugly) which can be run on the playground:

```<code>import UIKit

var array = [String]()
array.append("User1, 1st grade")
array.append("User2, 1st grade")
array.append("User3, kids")
array.append("User4, 6th grade")
array.append("User5, 5th grade")
array.append("User6, 2nd grade")
array.append("User7, kids")
array.append("User8, Juniors")

let kidsArray = array.filter { $0.lowercased().contains("kids") }.sorted()
let gradeArray = array.filter { $0.lowercased().contains("grade") }.sorted { $0.components(separatedBy: ",").last! < $1.components(separatedBy: ",").last! }
let juniorArray = array.filter { $0.lowercased().contains("juniors") }.sorted()

var finalArray = [String]()
finalArray.append(contentsOf: kidsArray)
finalArray.append(contentsOf: gradeArray)
finalArray.append(contentsOf: juniorArray)

print(finalArray)
</code>```

Print:

["User3, kids", "User7, kids", "User1, 1st grade", "User2, 1st grade", "User6, 2nd grade", "User5, 5th grade", "User4, 6th grade", "User8, Juniors"]

Title: Swift - Sort a subset of an array

Body:
I currently have a tableview with a lot of users, but I would like to sort the users in a specific order, not just ascending or descending. Let's say I have an array with the following users.

"User1", "1st grade"
"User2", "1st grade"
"User3", "kids"
"User4", "6th grade"
"User5", "5th grade"
"User6", "2nd grade"
"User7", "kids"
"User8", "juniors"

How can I order my array so that all the students who are in kids class are the first to be displayed, followed by all the classes with numbers (in order) and then all the Juniors.

I want an array that can display this

"User3", "kids"
"User7", "kids"
"User1", "1st grade"
"User2", "1st grade"
"User6", "2nd grade"
"User5", "5th grade"
"User4", "6th grade"
"User8", "juniors"

Edit:
Updated the text to make clear that the array has two columns, not just one string.

Was able to achieve it by using the line below

let sortedArray =
self.userArray.sorted(by: { $0.SchoolGrade!.gradeLongName().contains("Kids") ||
$1.SchoolGrade!.gradeLongName().contains("Juniors") })

Body:
What you are trying to sort is not common sort routine. So firstly, check your data structure for better sort solution.

But if you insist use your string list to sort, then you can try the following code (very ugly) which can be run on the playground:

import UIKit

var array = [String]()
array.append("User1, 1st grade")
array.append("User2, 1st grade")
array.append("User3, kids")
array.append("User4, 6th grade")
array.append("User5, 5th grade")
array.append("User6, 2nd grade")
array.append("User7, kids")
array.append("User8, Juniors")

let kidsArray = array.filter { $0.lowercased().contains("kids") }.sorted()
let gradeArray = array.filter { $0.lowercased().contains("grade") }.sorted { $0.components(separatedBy: ",").last! < $1.components(separatedBy: ",").last! }
let juniorArray = array.filter { $0.lowercased().contains("juniors") }.sorted()

var finalArray = [String]()
finalArray.append(contentsOf: kidsArray)
finalArray.append(contentsOf: gradeArray)
finalArray.append(contentsOf: juniorArray)

print(finalArray)

Print:

["User3, kids", "User7, kids", "User1, 1st grade", "User2, 1st grade", "User6, 2nd grade", "User5, 5th grade", "User4, 6th grade", "User8, Juniors"]


问:
Simple python script. Input and output do not match
Short version:
The number of lines in the input and output files are not equal. I don't understand why as I am not adding or subtracting any lines i.e. input file has 12327 lines but output only has 11903.

I can't seem to find any fault with my code. I was hoping someone with more experience could? Thank you.

Detailed version:
I have a simple python script made up of 3 functions.

Function 1 takes a list of numbers from a .txt file (infile), converts all of them into floats, and changes any negative numbers to 0. It then adds them to a list (orginal list). Each element of this list is then printed to an output file. It also tells you the number of lines in the input file.

Function 2 essentially checks the number of lines in the output file.

Function 3 is just runs functions 1 and 2.

The input file has 12327 lines whilst the output file only has 11903.

I made another input file to test the script. This .txt input file has 10 lines a few of which are negative numbers. However the output file is completely empty.

I don't understand why the input and output number of lines are different? I have included the code below.

I would appreciate any advice. Thank you.

```<code>def thelist():  #FUNCTION 1
    original_list = []
    for line in infile:
        newline = float(line)
        if newline < 0:
            newline = 0
        original_list.append(newline)
    print('The input file has', len(original_list), 'lines.')
    for element in original_list:
        print(element, file = outfile)

def outfilelinenumber():    #FUNCTION 2
    outfile = open('outfile.txt')
    improved_list = []
    for line in outfile:
        improved_list.append(line)
    if not improved_list:
        print('Output file is empty.')
    else:
        print('The output file has', len(improved_list), 'lines.')

def main(): #FUNCTION 3
    thelist()
    outfilelinenumber()
    print('\n', '*** Finished ***')

infile = open('infile.txt')
outfile = open('outfile.txt', 'w')

main()
</code>```

答:
I can see some lines are not fully pushed to outfile.txt by the time the second method reads outfile, and finds it empty. This is because of the write operation not getting completed. As suggested in the previous answer by Rory, it is suggested to close the files after use for proper file handling. Even using flush() to complete any pending write operations will help here.

Please use below main() for proper results.

```<code> def main(): #FUNCTION 3
    thelist()
    infile.flush()
    outfile.flush()
    outfilelinenumber()
    infile.flush()
    outfile.flush()
    print('\n', '*** Finished ***')
</code>```

Using this the output was:

```<code> The input file has 13 lines.
 The output file has 13 lines.

  *** Finished ***
</code>```

Body:
Short version:
The number of lines in the input and output files are not equal. I don't understand why as I am not adding or subtracting any lines i.e. input file has 12327 lines but output only has 11903.

I can't seem to find any fault with my code. I was hoping someone with more experience could? Thank you.

Detailed version:
I have a simple python script made up of 3 functions.

Function 1 takes a list of numbers from a .txt file (infile), converts all of them into floats, and changes any negative numbers to 0. It then adds them to a list (orginal list). Each element of this list is then printed to an output file. It also tells you the number of lines in the input file.

Function 2 essentially checks the number of lines in the output file.

Function 3 is just runs functions 1 and 2.

The input file has 12327 lines whilst the output file only has 11903.

I made another input file to test the script. This .txt input file has 10 lines a few of which are negative numbers. However the output file is completely empty.

I don't understand why the input and output number of lines are different? I have included the code below.

I would appreciate any advice. Thank you.

def thelist():  #FUNCTION 1
    original_list = []
    for line in infile:
        newline = float(line)
        if newline < 0:
            newline = 0
        original_list.append(newline)
    print('The input file has', len(original_list), 'lines.')
    for element in original_list:
        print(element, file = outfile)

def outfilelinenumber():    #FUNCTION 2
    outfile = open('outfile.txt')
    improved_list = []
    for line in outfile:
        improved_list.append(line)
    if not improved_list:
        print('Output file is empty.')
    else:
        print('The output file has', len(improved_list), 'lines.')

def main(): #FUNCTION 3
    thelist()
    outfilelinenumber()
    print('\n', '*** Finished ***')

infile = open('infile.txt')
outfile = open('outfile.txt', 'w')

main()

Body:
I can see some lines are not fully pushed to outfile.txt by the time the second method reads outfile, and finds it empty. This is because of the write operation not getting completed. As suggested in the previous answer by Rory, it is suggested to close the files after use for proper file handling. Even using flush() to complete any pending write operations will help here.

Please use below main() for proper results.

 def main(): #FUNCTION 3
    thelist()
    infile.flush()
    outfile.flush()
    outfilelinenumber()
    infile.flush()
    outfile.flush()
    print('\n', '*** Finished ***')

Using this the output was:

 The input file has 13 lines.
 The output file has 13 lines.

  *** Finished ***


问:
What are .kotlin_builtins files and can I omit them from my uberjars?
I'm working on integrating proguard to my gradle build for an application written in Kotlin.  I'm finding that proguard is stripping out the Kotlin standard library (as it should in my simple Hello World program) but it's leaving a bunch of files in my jar that have the file extension .kotlin_builtins.  When I configure my gradle task to exclude those files, the program still appears to work fine.  What are those files and must they ship with my executable uberjar?

Here's my build.gradle file's contents for reference:

```<code>buildscript {
   ext.kotlin_version = '1.0.5'
   ext.shadow_version = '1.2.4'

   repositories {
    mavenCentral()
    maven {
        url "https://plugins.gradle.org/m2/"
    }
    flatDir dirs: "gradle/proguard"
   }

   dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath "com.github.jengelman.gradle.plugins:shadow:$shadow_version"
    classpath ":proguard:"
   }
}

apply plugin: 'kotlin'
apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'

mainClassName = 'namespace.MainKt'

defaultTasks 'run'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    testCompile "junit:junit:4.12"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
}

shadowJar {
    exclude 'kotlin/**/*.kotlin_builtins'
    exclude '.keep'
}

task minify(type: proguard.gradle.ProGuardTask, dependsOn: 'shadowJar') {
    libraryjars "${System.getProperty('java.home')}/lib/rt.jar"

    injars  'build/libs/artful-all.jar'
    outjars 'build/libs/artful-all.out.jar'

    printmapping 'build/libs/out.map'

    keepclasseswithmembers 'public class * { \
        public static void main(java.lang.String[]); \
    }'

    assumenosideeffects 'class kotlin.jvm.internal.Intrinsics { \
        static void checkParameterIsNotNull(java.lang.Object, java.lang.String); \
    }'
}
</code>```

答:
You can optimize/omit these from yours JARs/APKs:

```<code>packagingOptions {
  exclude "/META-INF/*.kotlin_module"
  exclude "**/kotlin/**"
}
</code>```

Even better:

```<code>packagingOptions {
  exclude "/META-INF/*.kotlin_module"
  exclude "**/kotlin/**"
  exclude "**/*.txt"
  exclude "**/*.xml"
  exclude "**/*.properties"
}
</code>```

Source: https://github.com/jaredsburrows/android-gif-example/blob/master/build.gradle.kts#L127

Body:
I'm working on integrating proguard to my gradle build for an application written in Kotlin.  I'm finding that proguard is stripping out the Kotlin standard library (as it should in my simple Hello World program) but it's leaving a bunch of files in my jar that have the file extension .kotlin_builtins.  When I configure my gradle task to exclude those files, the program still appears to work fine.  What are those files and must they ship with my executable uberjar?

Here's my build.gradle file's contents for reference:

buildscript {
   ext.kotlin_version = '1.0.5'
   ext.shadow_version = '1.2.4'

   repositories {
    mavenCentral()
    maven {
        url "https://plugins.gradle.org/m2/"
    }
    flatDir dirs: "gradle/proguard"
   }

   dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath "com.github.jengelman.gradle.plugins:shadow:$shadow_version"
    classpath ":proguard:"
   }
}

apply plugin: 'kotlin'
apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'

mainClassName = 'namespace.MainKt'

defaultTasks 'run'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    testCompile "junit:junit:4.12"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
}

shadowJar {
    exclude 'kotlin/**/*.kotlin_builtins'
    exclude '.keep'
}

task minify(type: proguard.gradle.ProGuardTask, dependsOn: 'shadowJar') {
    libraryjars "${System.getProperty('java.home')}/lib/rt.jar"

    injars  'build/libs/artful-all.jar'
    outjars 'build/libs/artful-all.out.jar'

    printmapping 'build/libs/out.map'

    keepclasseswithmembers 'public class * { \
        public static void main(java.lang.String[]); \
    }'

    assumenosideeffects 'class kotlin.jvm.internal.Intrinsics { \
        static void checkParameterIsNotNull(java.lang.Object, java.lang.String); \
    }'
}

Body:
You can optimize/omit these from yours JARs/APKs:

packagingOptions {
  exclude "/META-INF/*.kotlin_module"
  exclude "**/kotlin/**"
}

Even better:

packagingOptions {
  exclude "/META-INF/*.kotlin_module"
  exclude "**/kotlin/**"
  exclude "**/*.txt"
  exclude "**/*.xml"
  exclude "**/*.properties"
}

Source: https://github.com/jaredsburrows/android-gif-example/blob/master/build.gradle.kts#L127

ContentLicense: CC BY-SA 4.0


答: If your project was a website, you should be able to ftp each file from the server 1 for 1. If your file was a web application project, you're hosed. The code files are compiled into a binary, and if you lost the source code it's gone.</p>

Title: recover lost C# pages

Body: I had a problem I lost all my source(CS) of web site pages but I had only published pages on server ,so please if there is any way to recover theses published pages to orignal pages with code,bin folder


问:
How to stop threads created by org.asynchttpclient to prevent memory leak?
I am using org.asynchttpclient to post async request.

While shutting down tomcat, I am getting below logs:

SEVERE: The web application [/test] appears to have started a thread named [pool-1-thread-1] but has failed to stop it. This is very likely to create a memory leak.

  Jul 04, 2017 10:53:00 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads

SEVERE: The web application [/test] appears to have started a thread named [AsyncHttpClient-2-1] but has failed to stop it. This is very likely to create a memory leak.

  Jul 04, 2017 10:53:00 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads

SEVERE: The web application [/test] appears to have started a thread named [AsyncHttpClient-2-2] but has failed to stop it. This is very likely to create a memory leak.

  Jul 04, 2017 10:53:00 AM org.apache.catalina.loader.WebappClassLoaderBase checkThreadLocalMapForLeaks

SEVERE: The web application [/test] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@71513074]) and a value of type [io.netty.util.internal.InternalThreadLocalMap] (value [io.netty.util.internal.InternalThreadLocalMap@4aecc2e8]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.

How to close these threads to prevent memory leak.

答:
This is really more of a warning and in most times can be ignored. You will see this error when the context is reloaded or shut down. If you are shutting down the server then the JVM will be shutdown also and the os will clean up any memory.

If you want to try and call close on the AsyncHttpClient which implements Closable it may stop this issue. You will probably have to put a wait in there to let it fully close the connection factory. You can look at the tomcat Lifecycle to add a shutdown handler to handle closing the client.


问:
Keep getting [$injector:modulerr] Error in AngularJS
I am following the phoneCat tutorial[https://docs.angularjs.org/tutorial/] and decide to create a similar structured app. but I keep getting $injector:modulerr Error when I try to include a module I created.
files are arranged like this

The way I started my app is use npm package http-sever with command http-server ...\app.

Another thing I noticed is that if I use http-server command directly(rather than npm start suggested in tutorial) to start app in the app folder it also gives me error message. I am now pretty confused about this.

This is my app.module.js

```<code>'use strict';

angular.module('dota2Hero', [
  'ngRoute',
  'core'
]);
</code>```

If I remove 'core' from dependency array, the code compiles.

Here is my index.html

```<code><!doctype html>
<html lang="en" ng-app="dota2Hero">

<head>
    <meta charset="utf-8">
    <title>Dota2 Database</title>

    <script src="//code.angularjs.org/1.6.1/angular.min.js"></script>
    <script src="//code.angularjs.org/1.6.1/angular-route.min.js"></script>
    <script src="core/hero/hero.module.js"></script>
    <script src="core/core.module.js"></script>
    <script src="app.module.js"></script>
    <script src="core/hero/hero.service.js"></script>
    <script src="app.config.js"></script>
</head>

<body>

    <div ng-view></div>

</body>

</html>
</code>```

and my core.module.js

```<code>'use strict';

angular.module('core',['core.hero']);
</code>```

答:
You need to change the order in which you load the references, load the core.module.js before loading app.module.js</p>

```<code>   <script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
     <script src="https://code.angularjs.org/1.6.1/angular-route.min.js"></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.1/angular-resource.min.js"></script>
     <script src="core/hero/hero.module.js"></script>
    <script src="hero-grid/hero-grid.module.js"></script>
    <script src="core/core.module.js"></script>
    <script src="app.module.js"></script>
    <script src="app.config.js"></script>
    <script src="core/hero/hero.service.js"></script>
    <script src="hero-grid/hero-grid.component.js"></script>
</code>```

Body:
I am following the phoneCat tutorial[https://docs.angularjs.org/tutorial/] and decide to create a similar structured app. but I keep getting $injector:modulerr Error when I try to include a module I created.
files are arranged like this

The way I started my app is use npm package http-sever with command http-server ...\app.

Another thing I noticed is that if I use http-server command directly(rather than npm start suggested in tutorial) to start app in the app folder it also gives me error message. I am now pretty confused about this.

This is my app.module.js

'use strict';

angular.module('dota2Hero', [
  'ngRoute',
  'core'
]);

If I remove 'core' from dependency array, the code compiles.

Here is my index.html

<!doctype html>

    <meta charset="utf-8">
    <title>Dota2 Database</title>

and my core.module.js

'use strict';

angular.module('core',['core.hero']);

Body:
You need to change the order in which you load the references, load the core.module.js before loading app.module.js

   <script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
     <script src="https://code.angularjs.org/1.6.1/angular-route.min.js"></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.1/angular-resource.min.js"></script>
     <script src="core/hero/hero.module.js"></script>
    <script src="hero-grid/hero-grid.module.js"></script>
    <script src="core/core.module.js"></script>
    <script src="app.module.js"></script>
    <script src="app.config.js"></script>
    <script src="core/hero/hero.service.js"></script>
    <script src="hero-grid/hero-grid.component.js"></script>


问:
Converting from for loops to forEach/map/some .. etc
Is it possible to not use for loops in the following snippet?

```<code>const states = [
  { a: 1 },
  { b: 1 },
  { b: 2, c: 1 }
];

const defaultState = {
  a: 0,
  b: 0,
  c: 0
};

const getRange = prop => {
  const range = [];

  for (let i = 0; i < states.length; i += 1) {
    let prevState;

    for (let j = i - 1; j >= 0; j -= 1) {
      prevState = states[j] && states[j][prop];
      if (prevState) break;
    }

    range[i] = states[i][prop] || (prevState || defaultState[prop]);
  }

  return range;
};

getRange('a') // [1, 1, 1]
getRange('b') // [0, 1, 2]
getRange('c') // [0, 0, 1]
</code>```

It should be in JavaScript only without depending on any other libs, I've tried to play a little with forEach() and some(), but couldn't replicate the current behavior. This is for exploration of the language purposes.

答:
A quite literal translation - every loop becomes a method call - of the code would be</p>

```<code>const getRange = defaultStats => state => prop => {
  return states.map((state, i) => {
    const prev = state.slice(0, i-1).reverse().find(s => s[prop]);
    return state[prop] || prev[prop] || defaultState[prop];
  });
};
</code>```

Body:
Is it possible to not use for loops in the following snippet?

const states = [
  { a: 1 },
  { b: 1 },
  { b: 2, c: 1 }
];

const defaultState = {
  a: 0,
  b: 0,
  c: 0
};

const getRange = prop => {
  const range = [];

  for (let i = 0; i < states.length; i += 1) {
    let prevState;

    for (let j = i - 1; j >= 0; j -= 1) {
      prevState = states[j] && states[j][prop];
      if (prevState) break;
    }

    range[i] = states[i][prop] || (prevState || defaultState[prop]);
  }

  return range;
};

getRange('a') // [1, 1, 1]
getRange('b') // [0, 1, 2]
getRange('c') // [0, 0, 1]

It should be in JavaScript only without depending on any other libs, I've tried to play a little with forEach() and some(), but couldn't replicate the current behavior. This is for exploration of the language purposes.

Body:
A quite literal translation - every loop becomes a method call - of the code would be

const getRange = defaultStats => state => prop => {
  return states.map((state, i) => {
    const prev = state.slice(0, i-1).reverse().find(s => s[prop]);
    return state[prop] || prev[prop] || defaultState[prop];
  });
};


问:
How to avoid adding field change handling methods and other boilerplates in react form?
I have a react based form with more than 10 fields in it, I have states for those ten form fields (controlled component).

Most of these input fields are of type text only but other types fields will be added later.

Problem is that I need to write 10 change handlers for them to set state correctly and then add method bindings for each of them in constructor.

I am quite new to react and may be not aware about correct
  methodologies and techniques.

Please guide me to how to improve my current code structure and avoid writing boiler plates and repetitive error prone code.

My current Registration component is like below -

```<code>export default class Register extends Component {

    constructor(props){
        super(props);
        this.state = {
            regName              : '',
            regAdd1              : '',
            regAdd2              : '',
            regState             : '',
            regZipCode           : '',
            regCity              : '',
            regPhone             : ''
        };
        // add bindings .... ugh..
        this.changeRegAdd1 = this.changeRegAdd1.bind(this);
        this.changeRegAdd2 = this.changeRegAdd2.bind(this);
        //Similary binding for other handlers...
    }

    // add individual field change handlers ... ugh...
    changeRegName(e) {
        this.setState({regName:e.target.value});
    }

    changeRegAdd1(e) {
        this.setState({regAdd1:e.target.value});
    }

    changeRegAdd2(e) {
        this.setState({regAdd2:e.target.value});
    }

    changeRegState(e) {
        this.setState({regState:e.target.value});
    }

    // Similary for other change handler ....

    handleSubmit(e) {
        e.preventDefault();
        // validate then do other stuff
    }

    render(){

        let registrationComp = (
                <div className="row">
                    <div className="col-md-12">
                        <h3>Registration Form</h3>
                        <fieldset>
                              <div className="form-group">
                                <div className="col-xs-12">
                                    <label htmlFor="regName">Name</label>
                                    <input type="text" placeholder="Name"
                                        onChange={this.changeregName} value = {this.state.regName} className="form-control" required autofocus/>
                                </div>
                              </div>

                              <div className="form-group">
                                <div className="col-xs-12">
                                    <label htmlFor="regAdd1">Address Line1</label>

                                    <input
                                        type        = "text"
                                        placeholder = "Address Line1"
                                        onChange    = {this.changeregAdd1}
                                        value       = {this.state.regAdd1}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                                    <input
                                        type        = "text"
                                        placeholder = "Address Line2"
                                        onChange    = {this.changeregAdd2}
                                        value       = {this.state.regAdd2}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />
                                </div>
                              </div>

                              <div className="form-group">
                                <div className="col-xs-6">
                                    <label htmlFor="regState">State</label>
                                    <input
                                        type        = "text"
                                        placeholder = "State"
                                        onChange    = {this.changeregState}
                                        value       = {this.state.regState}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />
                                </div>
                                <div className="col-xs-6">
                                    <label htmlFor="regZipCode">Zip Code</label>
                                    <input
                                        type        = "text"
                                        placeholder = "Zip Code"
                                        onChange    = {this.changeregZipCode}
                                        value       = {this.state.regZipCode}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />
                                </div>
                              </div>

                              <div className="form-group">
                                <div className="col-xs-12">
                                    <label htmlFor="regCity">City</label>
                                    <input
                                        type        = "text"
                                        placeholder = "City"
                                        title       = "City"
                                        onChange    = {this.changeregCity}
                                        value       = {this.state.regCity}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />
                                </div>
                              </div>
                              {/* other form fields */}
                          </fieldset>
                      </div>
                    </div>
            );

            return  registrationComp;
    }
}
</code>```

答:
You could create a higher order component to handle a lot of that for you. Redux Form has a pretty good pattern you could model it after if you wanted.

You would essentially end up with something like the following (I have not tested this at all, but it should work pretty well):

```<code>export class Field extends Component {
  handleChange = (event) => this.props.onChange(this.props.name, event.target.value)

  render() {
    const InputComponent = this.props.component
    const value = this.props.value || ''

    return (
      <InputComponent
        {...this.props}
        onChange={this.handleChange}
        value={value}
      />
  }
}

export default function createForm(WrappedComponent) {
  class Form extends Component {
    constructor() {
      super()

      this.state = this.props.initialValues || {}
      this.handleChange = this.handleChange.bind(this)
    }

    handleChange(name, value) {
      this.setState({
        [name]: value,
      })
    }

    render() {
      return (
        <WrappedComponent
          {...this.state}
          {...this.props}
          // pass anything you want to add here
          onChange={this.handleChange}
          values={this.state}
        />
      )
    }
  }

  return Form
}
</code>```

Then you can augment this one component as necessary (add focus, blur, submit handlers, etc). You would use it something like this:

```<code>import createForm, { Field } from './createForm'

// simplified Registration component
export class Registration extends Component {
  render() {
    return (
      <form>
        <Field
          component="input"
          name="name"
          onChange={this.props.onChange}
          type="text"
          value={this.props.values.name}
        />
      </form>
    )
  }
}

export default createForm(Registration)
</code>```

You could go crazy and get into context so you don't have to manually pass values and function around, but I would stay away at least until you're more familiar with React.

Also, if you don't want to manually bind functions, you could use the class properties transform if you're using babel. Then the Form component would just look like the following:

```<code>class Form extends Component {
  state = this.props.initialValues || {}

  handleChange = (name, value) => this.setState({
    [name]: value,
  })

  render() {
    return (
      <WrappedComponent
        {...this.state}
        {...this.props}
        onChange={this.handleChange}
        values={this.state}
      />
    )
  }
}
</code>```

Body:
I have a react based form with more than 10 fields in it, I have states for those ten form fields (controlled component).

Most of these input fields are of type text only but other types fields will be added later.

Problem is that I need to write 10 change handlers for them to set state correctly and then add method bindings for each of them in constructor.

I am quite new to react and may be not aware about correct
  methodologies and techniques.

Please guide me to how to improve my current code structure and avoid writing boiler plates and repetitive error prone code.

My current Registration component is like below -

export default class Register extends Component {

    constructor(props){
        super(props);
        this.state = {
            regName              : '',
            regAdd1              : '',
            regAdd2              : '',
            regState             : '',
            regZipCode           : '',
            regCity              : '',
            regPhone             : ''
        };
        // add bindings .... ugh..
        this.changeRegAdd1 = this.changeRegAdd1.bind(this);
        this.changeRegAdd2 = this.changeRegAdd2.bind(this);
        //Similary binding for other handlers...
    }

    // add individual field change handlers ... ugh...
    changeRegName(e) {
        this.setState({regName:e.target.value});
    }

    changeRegAdd1(e) {
        this.setState({regAdd1:e.target.value});
    }

    changeRegAdd2(e) {
        this.setState({regAdd2:e.target.value});
    }

    changeRegState(e) {
        this.setState({regState:e.target.value});
    }

    // Similary for other change handler ....

    handleSubmit(e) {
        e.preventDefault();
        // validate then do other stuff
    }

    render(){

        let registrationComp = (

Registration Form

                        <fieldset>

                                    Name
                                    <input type="text" placeholder="Name"
                                        onChange={this.changeregName} value = {this.state.regName} className="form-control" required autofocus/>

                                    Address Line1

                                    <input
                                        type        = "text"
                                        placeholder = "Address Line1"
                                        onChange    = {this.changeregAdd1}
                                        value       = {this.state.regAdd1}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                                    <input
                                        type        = "text"
                                        placeholder = "Address Line2"
                                        onChange    = {this.changeregAdd2}
                                        value       = {this.state.regAdd2}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                                    State
                                    <input
                                        type        = "text"
                                        placeholder = "State"
                                        onChange    = {this.changeregState}
                                        value       = {this.state.regState}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                                    Zip Code
                                    <input
                                        type        = "text"
                                        placeholder = "Zip Code"
                                        onChange    = {this.changeregZipCode}
                                        value       = {this.state.regZipCode}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                                    City
                                    <input
                                        type        = "text"
                                        placeholder = "City"
                                        title       = "City"
                                        onChange    = {this.changeregCity}
                                        value       = {this.state.regCity}
                                        className   = "form-control"
                                        required
                                        autofocus
                                    />

                              {/* other form fields */}
                          </fieldset>

            );

            return  registrationComp;
    }
}

Body:
You could create a higher order component to handle a lot of that for you. Redux Form has a pretty good pattern you could model it after if you wanted.

You would essentially end up with something like the following (I have not tested this at all, but it should work pretty well):

export class Field extends Component {
  handleChange = (event) => this.props.onChange(this.props.name, event.target.value)

  render() {
    const InputComponent = this.props.component
    const value = this.props.value || ''

    return (
      <InputComponent
        {...this.props}
        onChange={this.handleChange}
        value={value}
      />
  }
}

export default function createForm(WrappedComponent) {
  class Form extends Component {
    constructor() {
      super()

      this.state = this.props.initialValues || {}
      this.handleChange = this.handleChange.bind(this)
    }

    handleChange(name, value) {
      this.setState({
        [name]: value,
      })
    }

    render() {
      return (
        <WrappedComponent
          {...this.state}
          {...this.props}
          // pass anything you want to add here
          onChange={this.handleChange}
          values={this.state}
        />
      )
    }
  }

  return Form
}

Then you can augment this one component as necessary (add focus, blur, submit handlers, etc). You would use it something like this:

import createForm, { Field } from './createForm'

// simplified Registration component
export class Registration extends Component {
  render() {
    return (
      <form>
        <Field
          component="input"
          name="name"
          onChange={this.props.onChange}
          type="text"
          value={this.props.values.name}
        />
      </form>
    )
  }
}

export default createForm(Registration)

You could go crazy and get into context so you don't have to manually pass values and function around, but I would stay away at least until you're more familiar with React.

Also, if you don't want to manually bind functions, you could use the class properties transform if you're using babel. Then the Form component would just look like the following:

class Form extends Component {
  state = this.props.initialValues || {}

  handleChange = (name, value) => this.setState({
    [name]: value,
  })

  render() {
    return (
      <WrappedComponent
        {...this.state}
        {...this.props}
        onChange={this.handleChange}
        values={this.state}
      />
    )
  }
}