问:
Does While loop ends when the program return value?
I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).

My question is, why does it end loop when it return value on line 5, return(int(val))?

Thank you for your attention.

```<code>def readInt():
    while True:
        val = input('Enter an integer: ')
        try:
            return(int(val))
        except ValueError:
            print(val, "is not an integer")

g = readInt()
print("The square of the number you entered is", g**2)
</code>```

答:
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:

```<code>def read_int(num1, num2):
    while True:
        return num1 + num2

print(read_int(12, 15))
</code>```

If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.

If you allow me, here are some modifications to your original code:

```<code>def read_int():  # functions must be lowercase (Python convention)
    while True:
        val = input('Enter an integer: ')
        try:
            val = int(val)  # converts the value entered to an integer

            minimum_value = 0  # There is no need to evaluate a negative number as it will be positive anyway
            maximum_value = 1000000  # Also, a number above 1 million would be pretty big

            if minimum_value <= val <= maximum_value:
                result = val ** 2
                print(f'The square of the number you entered is {result}.')
                # This print statement is equivalent to the following:
                # print('The square of the number you entered is {}.'.format(result))
                break  # exits the loop: else you input an integer forever.
            else:
                print(f'Value must be between {minimum_value} and {maximum_value}.')
        except ValueError:  # If input is not an integer, print this message and go back to the beginning of the loop.
            print(val, 'is not an integer.')

# There must be 2 blank lines before and after a function block
read_int()
</code>```

With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!

Body:
I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).

My question is, why does it end loop when it return value on line 5, return(int(val))?

Thank you for your attention.

def readInt():
    while True:
        val = input('Enter an integer: ')
        try:
            return(int(val))
        except ValueError:
            print(val, "is not an integer")

g = readInt()
print("The square of the number you entered is", g**2)

Body:
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:

def read_int(num1, num2):
    while True:
        return num1 + num2

print(read_int(12, 15))

If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.

If you allow me, here are some modifications to your original code:

def read_int():  # functions must be lowercase (Python convention)
    while True:
        val = input('Enter an integer: ')
        try:
            val = int(val)  # converts the value entered to an integer

            minimum_value = 0  # There is no need to evaluate a negative number as it will be positive anyway
            maximum_value = 1000000  # Also, a number above 1 million would be pretty big

            if minimum_value <= val <= maximum_value:
                result = val ** 2
                print(f'The square of the number you entered is {result}.')
                # This print statement is equivalent to the following:
                # print('The square of the number you entered is {}.'.format(result))
                break  # exits the loop: else you input an integer forever.
            else:
                print(f'Value must be between {minimum_value} and {maximum_value}.')
        except ValueError:  # If input is not an integer, print this message and go back to the beginning of the loop.
            print(val, 'is not an integer.')

# There must be 2 blank lines before and after a function block
read_int()

With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!


来源: stackexchange

问:
How to execute Ajax requests in JMeter?
I want to execute Ajax requests in JMeter. I record my test plan with JMeter and BlazeMeter but none can handle Ajax requests. How can I solve my problem?

Or is there any tool that can send concurrent Ajax requests?

Thanks in advance,
M.A

答:
I had this same problem after recording samplers using the JMeter Proxy. The answer was on this blog post: https://lincolnloop.com/blog/load-testing-jmeter-part-1-getting-started/ - see the Ajax Requests section.

Add an HTTP Header Manager for the ajax request and make sure you are sending the X-Requested-With:XMLHttpRequest header.

ContentLicense: CC BY-SA 3.0

Title: How to execute Ajax requests in JMeter?


问:
Facebook : You are not logged in: You are not logged in. Please log in and try again
code throws error

```<code>        $helper = $fb->getRedirectLoginHelper();
        $loginUrl = $helper->getLoginUrl("https://apps.facebook.com/{$appname}/", $permissions);
        echo "<script>window.top.location.href='".$loginUrl."'</script>";
</code>```

Error

You are not logged in: You are not logged in. Please log in and try again.

the url which throws the error is (replaced my appname with appname) :

https://www.facebook.com/v2.7/dialog/oauth?client_id=8651003434372244&state=f2ad3183f9f04355435434534776ae19688ac&response_type=code&sdk=php-sdk-5.3.1&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fappname%2F&scope=email

full script

```<code>     <?php
    require_once  '../../Facebook/autoload.php';
    $fb = new Facebook\Facebook([
      'app_id' => "$appid",
      'app_secret' => "$appsecret",
      'default_graph_version' => 'v2.7',
    ]);
    $helper = $fb->getCanvasHelper();
    $permissions = ['email']; // optionnal
    try {

            $accessToken = $helper->getAccessToken();

    } catch(Facebook\Exceptions\FacebookResponseException $e) {
        // When Graph returns an error
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
        // When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
     }
    if (isset($accessToken)) {

            $accessToken = (string) $accessToken;
            $fb->setDefaultAccessToken($accessToken);

        if (isset($_GET['code'])) {
            header('Location: ./');
        }

        // validating the access token
        try {
            $request = $fb->get('/me');
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error
            if ($e->getCode() == 190) {
                $helper = $fb->getRedirectLoginHelper();
                $loginUrl = $helper->getLoginUrl("https://apps.facebook.com/{$appname}/", $permissions);
                echo "<script>window.top.location.href='".$loginUrl."'</script>";
                exit;
            }
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
            // When validation fails or other local issues
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }
        // getting basic info about user
        try {
            $profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
            $user_profile = $profile_request->getGraphNode()->asArray();
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error
            echo 'Graph returned an error: ' . $e->getMessage();
            $url = "https://apps.facebook.com/{$appname}/";
            echo '<script>window.top.location.href='.$url.'</script>';
            exit;
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
            // When validation fails or other local issues
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }
        // priting basic info about user on the screen
        //print_r($user_profile);
        // Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token']
    } else {

        $helper = $fb->getRedirectLoginHelper();
        $loginUrl = $helper->getLoginUrl("https://apps.facebook.com/{$appname}/", $permissions);
        echo "<script>window.top.location.href='".$loginUrl."'</script>";
    }
</code>```

答:
The simple FIX for the Facebook : You are not logged in: You are not logged in. Please log in and try again

TURN OFF
Client OAuth Login
Enables the standard OAuth client token flow. Secure your application and prevent abuse by locking down which token redirect URIs are allowed with the options below. Disable globally if not used

This the the TOP button under your app settings.

Hope this helps

Body:
code throws error

        $helper = $fb->getRedirectLoginHelper();
        $loginUrl = $helper->getLoginUrl("https://apps.facebook.com/{$appname}/", $permissions);
        echo "";

Error

You are not logged in: You are not logged in. Please log in and try again.

the url which throws the error is (replaced my appname with appname) :

https://www.facebook.com/v2.7/dialog/oauth?client_id=8651003434372244&state=f2ad3183f9f04355435434534776ae19688ac&response_type=code&sdk=php-sdk-5.3.1&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fappname%2F&scope=email

full script

     <?php
    require_once  '../../Facebook/autoload.php';
    $fb = new Facebook\Facebook([
      'app_id' => "$appid",
      'app_secret' => "$appsecret",
      'default_graph_version' => 'v2.7',
    ]);
    $helper = $fb->getCanvasHelper();
    $permissions = ['email']; // optionnal
    try {

            $accessToken = $helper->getAccessToken();

    } catch(Facebook\Exceptions\FacebookResponseException $e) {
        // When Graph returns an error
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
        // When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
     }
    if (isset($accessToken)) {

            $accessToken = (string) $accessToken;
            $fb->setDefaultAccessToken($accessToken);

        if (isset($_GET['code'])) {
            header('Location: ./');
        }

        // validating the access token
        try {
            $request = $fb->get('/me');
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error
            if ($e->getCode() == 190) {
                $helper = $fb->getRedirectLoginHelper();
                $loginUrl = $helper->getLoginUrl("https://apps.facebook.com/{$appname}/", $permissions);
                echo "";
                exit;
            }
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
            // When validation fails or other local issues
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }
        // getting basic info about user
        try {
            $profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
            $user_profile = $profile_request->getGraphNode()->asArray();
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error
            echo 'Graph returned an error: ' . $e->getMessage();
            $url = "https://apps.facebook.com/{$appname}/";
            echo '';
            exit;
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
            // When validation fails or other local issues
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }
        // priting basic info about user on the screen
        //print_r($user_profile);
        // Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token']
    } else {

        $helper = $fb->getRedirectLoginHelper();
        $loginUrl = $helper->getLoginUrl("https://apps.facebook.com/{$appname}/", $permissions);
        echo "";
    }


问:
how match Timezone data of table according to GeoTime zone in .Net
According to my table I have a column like Timezone standard name in which data as Like "Indian standard time", now I want to match this name by using Geo Time Zone package so how it can be done?  while Geo time Zone Package return only time zone like "Europe/London"...
eg:-

```<code>string tz = TimeZoneLookup.GetTimeZone(52.3702157, 4.8951679).Result
SELECT TimeZoneId FROM TimeZone WHERE NodaTimeZone LIKE '" + tz + "' OR GoogleTimeZoneName LIKE '" +  + "' ";
</code>```

Actually I want Timezone name as googleTimeZoneName by GeoTimeZonePackage, now I got the output from Geotimezone package as same as TimeZoneId of google.

答:
By using NodaTime, you are able to get the corresponding windows timezone id. Check this answer please.</p>

```<code>using System;
using System.Linq;
using NodaTime.TimeZones;

namespace CodeTesting
{
    class Program
    {
        static void Main()
        {
            string zoneName = "Europe/London";

            var tz = TzdbDateTimeZoneSource.Default.WindowsMapping.MapZones.FirstOrDefault(o => o.TzdbIds.Contains(zoneName)).WindowsId;

            Console.WriteLine(tz);

            Console.ReadKey();
        }
    }
}
</code>```

Body:
According to my table I have a column like Timezone standard name in which data as Like "Indian standard time", now I want to match this name by using Geo Time Zone package so how it can be done?  while Geo time Zone Package return only time zone like "Europe/London"...
eg:-

string tz = TimeZoneLookup.GetTimeZone(52.3702157, 4.8951679).Result
SELECT TimeZoneId FROM TimeZone WHERE NodaTimeZone LIKE '" + tz + "' OR GoogleTimeZoneName LIKE '" +  + "' ";

Actually I want Timezone name as googleTimeZoneName by GeoTimeZonePackage, now I got the output from Geotimezone package as same as TimeZoneId of google.

Body:
By using NodaTime, you are able to get the corresponding windows timezone id. Check this answer please.

using System;
using System.Linq;
using NodaTime.TimeZones;

namespace CodeTesting
{
    class Program
    {
        static void Main()
        {
            string zoneName = "Europe/London";

            var tz = TzdbDateTimeZoneSource.Default.WindowsMapping.MapZones.FirstOrDefault(o => o.TzdbIds.Contains(zoneName)).WindowsId;

            Console.WriteLine(tz);

            Console.ReadKey();
        }
    }
}


问:
Building a Transition Matrix using words in Python/Numpy
Im trying to build a 3x3 transition matrix with this data

```<code>days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']
</code>```

Currently, Im doing it with some temp dictionaries and some list that calculates the probability of each weather separately. Its not a pretty solution. Can someone please guide me with a more reasonable solution to this problem?

```<code>self.transitionMatrix=np.zeros((3,3))

#the columns are today
sun_total_count = 0
temp_dict={'sun':0, 'clouds':0, 'rain':0}
total_runs = 0
for (x, y), c in Counter(zip(data, data[1:])).items():
    #if column 0 is sun
    if x is 'sun':
        #find the sum of all the numbers in this column
        sun_total_count +=  c
        total_runs += 1
        if y is 'sun':
            temp_dict['sun'] = c
        if y is 'clouds':
            temp_dict['clouds'] = c
        if y is 'rain':
            temp_dict['rain'] = c

        if total_runs is 3:
            self.transitionMatrix[0][0] = temp_dict['sun']/sun_total_count
            self.transitionMatrix[1][0] = temp_dict['clouds']/sun_total_count
            self.transitionMatrix[2][0] = temp_dict['rain']/sun_total_count

return self.transitionMatrix
</code>```

for every type of weather I need to calculate the probability for the next day

答:
Here is a "pure" numpy solution it creates 3x3 tables where the zeroth dim (row number) corresponds to today and the last dim (column number) corresponds to tomorrow.

The conversion from words to indices is done by truncating after the first letter and then using a lookup table.

For counting numpy.add.at is used.

This was written with efficiency in mind. It does a million words in less than a second.

```<code>import numpy as np

report = [
  'rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']

# create np array, keep only first letter (by forcing dtype)
# obviously, this only works because rain, sun, clouds start with different
# letters
# cast to int type so we can use for indexing
ri = np.array(report, dtype='|S1').view(np.uint8)
# create lookup
c, r, s = 99, 114, 115 # you can verify this using chr and ord
lookup = np.empty((s+1,), dtype=int)
lookup[[c, r, s]] = np.arange(3)
# translate c, r, s to 0, 1, 2
rc = lookup[ri]
# get counts (of pairs (today, tomorrow))
cnts = np.zeros((3, 3), dtype=int)
np.add.at(cnts, (rc[:-1], rc[1:]), 1)
# or as probs
probs = cnts / cnts.sum()
# or as condional probs (if today is sun how probable is rain tomorrow etc.)
cond = cnts / cnts.sum(axis=-1, keepdims=True)

print(cnts)
print(probs)
print(cond)

# [13  9 10]
#  [ 6 11  9]
#  [13  6 23]]
# [[ 0.13  0.09  0.1 ]
#  [ 0.06  0.11  0.09]
#  [ 0.13  0.06  0.23]]
# [[ 0.40625     0.28125     0.3125    ]
#  [ 0.23076923  0.42307692  0.34615385]
#  [ 0.30952381  0.14285714  0.54761905]]
</code>```

Body:
Im trying to build a 3x3 transition matrix with this data

days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']

Currently, Im doing it with some temp dictionaries and some list that calculates the probability of each weather separately. Its not a pretty solution. Can someone please guide me with a more reasonable solution to this problem?

self.transitionMatrix=np.zeros((3,3))

#the columns are today
sun_total_count = 0
temp_dict={'sun':0, 'clouds':0, 'rain':0}
total_runs = 0
for (x, y), c in Counter(zip(data, data[1:])).items():
    #if column 0 is sun
    if x is 'sun':
        #find the sum of all the numbers in this column
        sun_total_count +=  c
        total_runs += 1
        if y is 'sun':
            temp_dict['sun'] = c
        if y is 'clouds':
            temp_dict['clouds'] = c
        if y is 'rain':
            temp_dict['rain'] = c

        if total_runs is 3:
            self.transitionMatrix[0][0] = temp_dict['sun']/sun_total_count
            self.transitionMatrix[1][0] = temp_dict['clouds']/sun_total_count
            self.transitionMatrix[2][0] = temp_dict['rain']/sun_total_count

return self.transitionMatrix

for every type of weather I need to calculate the probability for the next day

Body:
Here is a "pure" numpy solution it creates 3x3 tables where the zeroth dim (row number) corresponds to today and the last dim (column number) corresponds to tomorrow.

The conversion from words to indices is done by truncating after the first letter and then using a lookup table.

For counting numpy.add.at is used.

This was written with efficiency in mind. It does a million words in less than a second.

import numpy as np

report = [
  'rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']

# create np array, keep only first letter (by forcing dtype)
# obviously, this only works because rain, sun, clouds start with different
# letters
# cast to int type so we can use for indexing
ri = np.array(report, dtype='|S1').view(np.uint8)
# create lookup
c, r, s = 99, 114, 115 # you can verify this using chr and ord
lookup = np.empty((s+1,), dtype=int)
lookup[[c, r, s]] = np.arange(3)
# translate c, r, s to 0, 1, 2
rc = lookup[ri]
# get counts (of pairs (today, tomorrow))
cnts = np.zeros((3, 3), dtype=int)
np.add.at(cnts, (rc[:-1], rc[1:]), 1)
# or as probs
probs = cnts / cnts.sum()
# or as condional probs (if today is sun how probable is rain tomorrow etc.)
cond = cnts / cnts.sum(axis=-1, keepdims=True)

print(cnts)
print(probs)
print(cond)

# [13  9 10]
#  [ 6 11  9]
#  [13  6 23]]
# [[ 0.13  0.09  0.1 ]
#  [ 0.06  0.11  0.09]
#  [ 0.13  0.06  0.23]]
# [[ 0.40625     0.28125     0.3125    ]
#  [ 0.23076923  0.42307692  0.34615385]
#  [ 0.30952381  0.14285714  0.54761905]]


问:
document.body.appendChild to add, but parentNode.removeChild to remove?
I've decided it's time for me to learn javascript in a more formal and less haphazard way than I've used it in the past.

So I went to developer.mozilla.org to take their tutorial.

One of the first teaching exercises they provide is in the article entitled,"A First splash into JavaScript" at https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/A_first_splash, in which they create a simple number guessing game.

In that game's code, the exercise creates a function called setGameOver which creates a button labeled, "Start New Game".

The code for that button is:

```<code>document.body.appendChild(resetButton);
</code>```

This is followed by another function called resetGame, in which this button is removed from the page:

```<code>resetButton.parentNode.removeChild(resetButton);
</code>```

My question is: if the code to add the button is document.body.appendChild, why isn't the code to remove the button something like document.body.removeChild?

And why do we have to use parentNode.removeChild instead?

This is the kind of thing with coding tutorials that drives me nuts. They introduce a new command and they don't explain why. They just say in effect, "This is how you remove the button" and they leave it at that. Ugh!

答:
There's a lot of ways to remove and add an element to the page, this just happens to be the way that the tutorial author chose to demonstrate that. Perhaps their intention was to demonstrate that you can in fact access document.body through resetButton.parentNode, we will never know.

The main point here is that you can remove the button by accessing it's parent node. In this case, we know for a fact that document.body is its parent node (we added the button to that element, so it must be the parent), so in this case resetButton.parentNode and document.body refer to the same object, and are functionally equivalent.

```<code>var node1 = document.body;
node1.appendChild(resetButton);
// resetButton is now a child of node1 (and document.body, its the same object)
var node2 = resetButton.parentNode;
// we now know that node2 == node1 so we could do either of the following:
node1.removeChild(resetButton);
// -- or --
node2.removeChild(resetButton);
</code>```

If you have the reference to a specific html node (in this case, resetButton) and don't know what the parent node is, then using .parentNode to find the parent would be the right way to do it. If you do know the parent (because you just added it) then it doesn't really matter which way you do it.

Body:
I've decided it's time for me to learn javascript in a more formal and less haphazard way than I've used it in the past.

So I went to developer.mozilla.org to take their tutorial.

One of the first teaching exercises they provide is in the article entitled,"A First splash into JavaScript" at https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/A_first_splash, in which they create a simple number guessing game.

In that game's code, the exercise creates a function called setGameOver which creates a button labeled, "Start New Game".

The code for that button is:

document.body.appendChild(resetButton);

This is followed by another function called resetGame, in which this button is removed from the page:

resetButton.parentNode.removeChild(resetButton);

My question is: if the code to add the button is document.body.appendChild, why isn't the code to remove the button something like document.body.removeChild?

And why do we have to use parentNode.removeChild instead?

This is the kind of thing with coding tutorials that drives me nuts. They introduce a new command and they don't explain why. They just say in effect, "This is how you remove the button" and they leave it at that. Ugh!

Body:
There's a lot of ways to remove and add an element to the page, this just happens to be the way that the tutorial author chose to demonstrate that. Perhaps their intention was to demonstrate that you can in fact access document.body through resetButton.parentNode, we will never know.

The main point here is that you can remove the button by accessing it's parent node. In this case, we know for a fact that document.body is its parent node (we added the button to that element, so it must be the parent), so in this case resetButton.parentNode and document.body refer to the same object, and are functionally equivalent.

var node1 = document.body;
node1.appendChild(resetButton);
// resetButton is now a child of node1 (and document.body, its the same object)
var node2 = resetButton.parentNode;
// we now know that node2 == node1 so we could do either of the following:
node1.removeChild(resetButton);
// -- or --
node2.removeChild(resetButton);

If you have the reference to a specific html node (in this case, resetButton) and don't know what the parent node is, then using .parentNode to find the parent would be the right way to do it. If you do know the parent (because you just added it) then it doesn't really matter which way you do it.


问:
Oracle / SQL - Count number of occurrences of values in a single column
Okay, I probably could have come up with a better title, but wasn't sure how to word it so let me explain.

Say I have a table with the column 'CODE'.  Each record in my table will have either 'A', 'B', or 'C' as it's value in the 'CODE' column.  What I would like is to get a count of how many 'A's, 'B's, and 'C's I have.

I know I could accomplish this with 3 different queries, but I'm wondering if there is a way to do it with just 1.

答:
Use:

```<code>  SELECT t.code,
         COUNT(*) AS numInstances
    FROM YOUR_TABLE t
GROUP BY t.code
</code>```

The output will resemble:

```<code>code   numInstances
--------------------
A      3
B      5
C      1
</code>```

If a code exists that has not been used, it will not show up.  You'd need to LEFT JOIN to the table containing the list of codes in order to see those that don't have any references.

Body:
Use:

  SELECT t.code,
         COUNT(*) AS numInstances
    FROM YOUR_TABLE t
GROUP BY t.code

The output will resemble:

code   numInstances
--------------------
A      3
B      5
C      1

If a code exists that has not been used, it will not show up.  You'd need to LEFT JOIN to the table containing the list of codes in order to see those that don't have any references.

ContentLicense: CC BY-SA 2.5


问:
TypeScript compilation of RequireJS module generates line Object.defineProperty(exports, "__esModule", { value: true }); How to get rid of it?
This is how my tsconfig.json file looks:

```<code>{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "amd",
        "noImplicitAny": false,
        "removeComments": false,
        "preserveConstEnums": true,
        "strictNullChecks": true,
        "sourceMap": false
    }
}
</code>```

I have a typescript file named a.ts which is an AMD module (I'm using requirejs), which looks like:

```<code>export function a() {
    var a = {
        b: 5
    };
    return a;
}
</code>```

The compiled Javascript files looks like:

```<code> define(["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function a() {
        var a = {
            b: 5
        };
        return a;
    }
    exports.a = a;
 });
</code>```

I need my generated JavaScript file to be:

```<code>define(function () {
    "use strict";
    var a = {
        b: 5
    };
    return a;
});
</code>```

So I need to

a) Remove the  Object.defineProperty(exports, "__esModule", { value: true }); line

b) Remove the require and exports dependencies from define

c) Not having an internal function "a" and then expose "a" on exports, but rather simply return "a" object in the a.js file

What changes do I need to make to tsconfig.json and a.ts files to get the desired Javascript file or something closer to it, any improvements from current a.js towards what I need would be great, even 1 or 2 out of 3 requirements.

One way is to make a.ts exactly like my desired a.js file and then compile, but I must use export statement way of making amd module due to another unrelated requirement. Thanks for reading till here. Please help.

答:
Your export issue can easily be fixed by using the export = syntax. If you code your module with this:

```<code>var a = {
  b: 5
};

export = a;
</code>```

It is transpiled to this:

```<code>define(["require", "exports"], function (require, exports) {
    "use strict";
    var a = {
        b: 5
    };
    return a;
});
</code>```

Note that you also lose the creation of the __esModule property.

The rest of your question duplicates another question. In brief, the TypeScript compiler provides no option to avoid emitting the require and exports dependencies. You have to process the emitted code on your own if you want to remove them.

Body:
This is how my tsconfig.json file looks:

{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "amd",
        "noImplicitAny": false,
        "removeComments": false,
        "preserveConstEnums": true,
        "strictNullChecks": true,
        "sourceMap": false
    }
}

I have a typescript file named a.ts which is an AMD module (I'm using requirejs), which looks like:

export function a() {
    var a = {
        b: 5
    };
    return a;
}

The compiled Javascript files looks like:

 define(["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function a() {
        var a = {
            b: 5
        };
        return a;
    }
    exports.a = a;
 });

I need my generated JavaScript file to be:

define(function () {
    "use strict";
    var a = {
        b: 5
    };
    return a;
});

So I need to

a) Remove the  Object.defineProperty(exports, "__esModule", { value: true }); line

b) Remove the require and exports dependencies from define

c) Not having an internal function "a" and then expose "a" on exports, but rather simply return "a" object in the a.js file

What changes do I need to make to tsconfig.json and a.ts files to get the desired Javascript file or something closer to it, any improvements from current a.js towards what I need would be great, even 1 or 2 out of 3 requirements.

One way is to make a.ts exactly like my desired a.js file and then compile, but I must use export statement way of making amd module due to another unrelated requirement. Thanks for reading till here. Please help.

Body:
Your export issue can easily be fixed by using the export = syntax. If you code your module with this:

var a = {
  b: 5
};

export = a;

It is transpiled to this:

define(["require", "exports"], function (require, exports) {
    "use strict";
    var a = {
        b: 5
    };
    return a;
});

Note that you also lose the creation of the __esModule property.

The rest of your question duplicates another question. In brief, the TypeScript compiler provides no option to avoid emitting the require and exports dependencies. You have to process the emitted code on your own if you want to remove them.


问:
Android onAnimationEnd remove View (self) not removing
I'm trying to animate a card flip and then fling it away with an animation. For the most part I've completed that. The problem is I can't get the card to reliably be removed.

Question: How can I reliably delete a View after animation on it is complete? (also I'm using AnimationSet, so this may change things)

Here is what my code looks like.

flingCardAway(the problem area)

```<code>private void flingCardAway(){
    final View cardContainer = findViewById(R.id.card_container);
    ViewCompat.setTranslationZ(cardContainer, 1.0f);

    AnimationSet anim = new AnimationSet(true);

    RotateAnimation rotate1 = new RotateAnimation(0,-45, Animation.RELATIVE_TO_SELF,0.5f , Animation.RELATIVE_TO_SELF,0.5f );
    rotate1.setStartOffset(100);
    rotate1.setDuration(500);
    anim.addAnimation(rotate1);

    TranslateAnimation trans1 =  new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
    trans1.setDuration(600);
    anim.addAnimation(trans1);

    AlphaAnimation opacity1 = new AlphaAnimation(1.0f, 0.0f);
    opacity1.setDuration(400);
    opacity1.setStartOffset(200);
    anim.addAnimation(opacity1);

    cardContainer.setAnimation(anim);
    cardContainer.setVisibility(View.VISIBLE);

    anim.setAnimationListener(new Animation.AnimationListener(){
        @Override
        public void onAnimationStart(Animation arg0) {
        }
        @Override
        public void onAnimationRepeat(Animation arg0) {
        }
        @Override
        public void onAnimationEnd(Animation arg0) {
            final View cardContainer2 = findViewById(R.id.card_container);
            ((ViewGroup)cardContainer2.getParent()).removeView(cardContainer2);
        }
    });
}
</code>```

Full class for reference
Study.java

```<code>package com.example.trevorwood.biggles.study;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.example.trevorwood.biggles.R;

public class Study extends AppCompatActivity {
    LinearLayout mFlipCardLinearLayout;
    LinearLayout mCardFlippedButtons;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_study);
        Intent intent = getIntent();
        // String value = intent.getStringExtra("key");
        Toolbar toolbar = (Toolbar) findViewById(R.id.study_toolbar);
        toolbar.setTitleTextColor(Color.WHITE);//0xAARRGGBB
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mFlipCardLinearLayout = (LinearLayout) findViewById(R.id.flip_card_linear_layout);
        mCardFlippedButtons = (LinearLayout) findViewById(R.id.card_flipped_buttons);

        final Drawable upArrow = getResources().getDrawable(R.drawable.ic_back_arrow);
        upArrow.setColorFilter(getResources().getColor(R.color.colorWhite), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(upArrow);

        makeNewCard();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    public void onCardClick(View view) {
        flipCard();
    }

    public void onCardFlippedButtonsClick(View view) {
        Integer numberPressed;
        switch (view.getId()){
            case R.id.color_button_1:numberPressed = 1;break;
            case R.id.color_button_2:numberPressed = 2;break;
            case R.id.color_button_3:numberPressed = 3;break;
            case R.id.color_button_4:numberPressed = 4;break;
            case R.id.color_button_5:numberPressed = 5;break;
            default:numberPressed = 0;
        }

        saveCardStats(numberPressed);
        flingCardAway();
        resetForNewCard();
        makeNewCard();
    }

    private void flipCard() {
        FrameLayout cardFrame = (FrameLayout) findViewById(R.id.card_frame);
        Integer childCount = cardFrame.getChildCount();
        Log.d("Simple","childCount: "+childCount);

        View cardContainer = findViewById(R.id.card_container);
        View cardFace = findViewById(R.id.card_front);
        View cardBack = findViewById(R.id.card_back);

        FlipAnimation flipAnimation = new FlipAnimation(cardFace, cardBack);

        if (cardFace.getVisibility() == View.GONE) {
            mFlipCardLinearLayout.setVisibility(View.VISIBLE);
            mCardFlippedButtons.setVisibility(View.GONE);
            flipAnimation.reverse();
        }else{
            mFlipCardLinearLayout.setVisibility(View.GONE);
            mCardFlippedButtons.setVisibility(View.VISIBLE);
        }
        cardContainer.startAnimation(flipAnimation);
    }

    private void saveCardStats(Integer numberPressed){

    }

    private void flingCardAway(){
        final View cardContainer = findViewById(R.id.card_container);
        ViewCompat.setTranslationZ(cardContainer, 1.0f);

        AnimationSet anim = new AnimationSet(true);

        RotateAnimation rotate1 = new RotateAnimation(0,-45, Animation.RELATIVE_TO_SELF,0.5f , Animation.RELATIVE_TO_SELF,0.5f );
        rotate1.setStartOffset(100);
        rotate1.setDuration(500);
        anim.addAnimation(rotate1);

        TranslateAnimation trans1 =  new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
        trans1.setDuration(600);
        anim.addAnimation(trans1);

        AlphaAnimation opacity1 = new AlphaAnimation(1.0f, 0.0f);
        opacity1.setDuration(400);
        opacity1.setStartOffset(200);
        anim.addAnimation(opacity1);

        cardContainer.setAnimation(anim);
        cardContainer.setVisibility(View.VISIBLE);

        anim.setAnimationListener(new Animation.AnimationListener(){
            @Override
            public void onAnimationStart(Animation arg0) {
            }
            @Override
            public void onAnimationRepeat(Animation arg0) {
            }
            @Override
            public void onAnimationEnd(Animation arg0) {
                final View cardContainer2 = findViewById(R.id.card_container);
                ((ViewGroup)cardContainer2.getParent()).removeView(cardContainer2);
            }
        });
    }

    private void resetForNewCard(){
        mFlipCardLinearLayout.setVisibility(View.VISIBLE);
        mCardFlippedButtons.setVisibility(View.GONE);
    }

    private void makeNewCard(){
        FrameLayout cardFrame = (FrameLayout) findViewById(R.id.card_frame);
        Integer childCount = cardFrame.getChildCount();
        Log.d("Simple","childCount: "+childCount);
        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.study_card, cardFrame);
    }

}
</code>```

FlipAnimation.java (not as important, just a reference)

```<code>package com.example.trevorwood.biggles.study;

import android.graphics.Camera;
import android.graphics.Matrix;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class FlipAnimation extends Animation {
    private Camera camera;
    private View fromView;
    private View toView;

    private float centerX;
    private float centerY;

    private boolean forward = true;

    /**
     * Creates a 3D flip animation between two views.
     *
     * @param fromView First view in the transition.
     * @param toView   Second view in the transition.
     */
    public FlipAnimation(View fromView, View toView) {
        this.fromView = fromView;
        this.toView = toView;

        setDuration(300);
        setFillAfter(false);
        setInterpolator(new AccelerateDecelerateInterpolator());
    }

    public void reverse() {
        forward = false;
        View switchView = toView;
        toView = fromView;
        fromView = switchView;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        centerX = width / 2;
        centerY = height / 2;
        camera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        // Angle around the y-axis of the rotation at the given time
        // calculated both in radians and degrees.
        final double radians = Math.PI * interpolatedTime;
        float degrees = (float) (180.0 * radians / Math.PI);

        // Once we reach the midpoint in the animation, we need to hide the
        // source view and show the destination view. We also need to change
        // the angle by 180 degrees so that the destination does not come in
        // flipped around
        if (interpolatedTime >= 0.5f) {
            degrees -= 180.f;
            fromView.setVisibility(View.GONE);
            toView.setVisibility(View.VISIBLE);
        }

        if (forward)
            degrees = -degrees; //determines direction of rotation when flip begins

        final Matrix matrix = t.getMatrix();
        camera.save();
        camera.translate(0, 0, Math.abs(degrees)*6);
        camera.getMatrix(matrix);
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();
        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}
</code>```

I saw this, it helped but didn't solve my problem. End animation event android

I saw this too, but am not sure how to implement it into my own project. android animation is not finished in onAnimationEnd

The google docs all point to this link but this isn't reliable under rapid clicks.

答:
This worked for me. Even though if you were to think about it, it probably shouldn't work. (It 100% would not work if converted to JavaScript, as the view is being removed before the animation has ended.) Perhaps somebody with more Android experience can explain why this works.

My hypothesis on why this works (please keep in mind, this is just a guess): is that Android's animations actually turn the view into something else entirely, while the original view is turned transparent. Then when the animation is ended, the animation view is deleted and the original view is turned back to visible.

```<code>private void flingCardAway(){

    View cardContainer = findViewById(R.id.card_container);
    ViewCompat.setTranslationZ(cardContainer, 1.0f);

    AnimationSet anim = new AnimationSet(true);

    RotateAnimation rotate1 = new RotateAnimation(0,-45, Animation.RELATIVE_TO_SELF,0.5f , Animation.RELATIVE_TO_SELF,0.5f );
    rotate1.setStartOffset(10);
    rotate1.setDuration(500);
    anim.addAnimation(rotate1);

    TranslateAnimation trans1 =  new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -0.2f, Animation.RELATIVE_TO_PARENT, -0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
    trans1.setDuration(100);
    anim.addAnimation(trans1);

    TranslateAnimation trans2 =  new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
    trans2.setStartOffset(100);
    trans2.setDuration(100);
    anim.addAnimation(trans2);

    AlphaAnimation opacity1 = new AlphaAnimation(1.0f, 0.0f);
    opacity1.setDuration(300);
    opacity1.setStartOffset(300);
    anim.addAnimation(opacity1);

    cardContainer.setAnimation(anim);

    mCardFrame.removeAllViews();

}
</code>```

Body:
I'm trying to animate a card flip and then fling it away with an animation. For the most part I've completed that. The problem is I can't get the card to reliably be removed.

Question: How can I reliably delete a View after animation on it is complete? (also I'm using AnimationSet, so this may change things)

Here is what my code looks like.

flingCardAway(the problem area)

private void flingCardAway(){
    final View cardContainer = findViewById(R.id.card_container);
    ViewCompat.setTranslationZ(cardContainer, 1.0f);

    AnimationSet anim = new AnimationSet(true);

    RotateAnimation rotate1 = new RotateAnimation(0,-45, Animation.RELATIVE_TO_SELF,0.5f , Animation.RELATIVE_TO_SELF,0.5f );
    rotate1.setStartOffset(100);
    rotate1.setDuration(500);
    anim.addAnimation(rotate1);

    TranslateAnimation trans1 =  new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
    trans1.setDuration(600);
    anim.addAnimation(trans1);

    AlphaAnimation opacity1 = new AlphaAnimation(1.0f, 0.0f);
    opacity1.setDuration(400);
    opacity1.setStartOffset(200);
    anim.addAnimation(opacity1);

    cardContainer.setAnimation(anim);
    cardContainer.setVisibility(View.VISIBLE);

    anim.setAnimationListener(new Animation.AnimationListener(){
        @Override
        public void onAnimationStart(Animation arg0) {
        }
        @Override
        public void onAnimationRepeat(Animation arg0) {
        }
        @Override
        public void onAnimationEnd(Animation arg0) {
            final View cardContainer2 = findViewById(R.id.card_container);
            ((ViewGroup)cardContainer2.getParent()).removeView(cardContainer2);
        }
    });
}

Full class for reference
Study.java

package com.example.trevorwood.biggles.study;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.example.trevorwood.biggles.R;

public class Study extends AppCompatActivity {
    LinearLayout mFlipCardLinearLayout;
    LinearLayout mCardFlippedButtons;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_study);
        Intent intent = getIntent();
        // String value = intent.getStringExtra("key");
        Toolbar toolbar = (Toolbar) findViewById(R.id.study_toolbar);
        toolbar.setTitleTextColor(Color.WHITE);//0xAARRGGBB
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mFlipCardLinearLayout = (LinearLayout) findViewById(R.id.flip_card_linear_layout);
        mCardFlippedButtons = (LinearLayout) findViewById(R.id.card_flipped_buttons);

        final Drawable upArrow = getResources().getDrawable(R.drawable.ic_back_arrow);
        upArrow.setColorFilter(getResources().getColor(R.color.colorWhite), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(upArrow);

        makeNewCard();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    public void onCardClick(View view) {
        flipCard();
    }

    public void onCardFlippedButtonsClick(View view) {
        Integer numberPressed;
        switch (view.getId()){
            case R.id.color_button_1:numberPressed = 1;break;
            case R.id.color_button_2:numberPressed = 2;break;
            case R.id.color_button_3:numberPressed = 3;break;
            case R.id.color_button_4:numberPressed = 4;break;
            case R.id.color_button_5:numberPressed = 5;break;
            default:numberPressed = 0;
        }

        saveCardStats(numberPressed);
        flingCardAway();
        resetForNewCard();
        makeNewCard();
    }

    private void flipCard() {
        FrameLayout cardFrame = (FrameLayout) findViewById(R.id.card_frame);
        Integer childCount = cardFrame.getChildCount();
        Log.d("Simple","childCount: "+childCount);

        View cardContainer = findViewById(R.id.card_container);
        View cardFace = findViewById(R.id.card_front);
        View cardBack = findViewById(R.id.card_back);

        FlipAnimation flipAnimation = new FlipAnimation(cardFace, cardBack);

        if (cardFace.getVisibility() == View.GONE) {
            mFlipCardLinearLayout.setVisibility(View.VISIBLE);
            mCardFlippedButtons.setVisibility(View.GONE);
            flipAnimation.reverse();
        }else{
            mFlipCardLinearLayout.setVisibility(View.GONE);
            mCardFlippedButtons.setVisibility(View.VISIBLE);
        }
        cardContainer.startAnimation(flipAnimation);
    }

    private void saveCardStats(Integer numberPressed){

    }

    private void flingCardAway(){
        final View cardContainer = findViewById(R.id.card_container);
        ViewCompat.setTranslationZ(cardContainer, 1.0f);

        AnimationSet anim = new AnimationSet(true);

        RotateAnimation rotate1 = new RotateAnimation(0,-45, Animation.RELATIVE_TO_SELF,0.5f , Animation.RELATIVE_TO_SELF,0.5f );
        rotate1.setStartOffset(100);
        rotate1.setDuration(500);
        anim.addAnimation(rotate1);

        TranslateAnimation trans1 =  new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
        trans1.setDuration(600);
        anim.addAnimation(trans1);

        AlphaAnimation opacity1 = new AlphaAnimation(1.0f, 0.0f);
        opacity1.setDuration(400);
        opacity1.setStartOffset(200);
        anim.addAnimation(opacity1);

        cardContainer.setAnimation(anim);
        cardContainer.setVisibility(View.VISIBLE);

        anim.setAnimationListener(new Animation.AnimationListener(){
            @Override
            public void onAnimationStart(Animation arg0) {
            }
            @Override
            public void onAnimationRepeat(Animation arg0) {
            }
            @Override
            public void onAnimationEnd(Animation arg0) {
                final View cardContainer2 = findViewById(R.id.card_container);
                ((ViewGroup)cardContainer2.getParent()).removeView(cardContainer2);
            }
        });
    }

    private void resetForNewCard(){
        mFlipCardLinearLayout.setVisibility(View.VISIBLE);
        mCardFlippedButtons.setVisibility(View.GONE);
    }

    private void makeNewCard(){
        FrameLayout cardFrame = (FrameLayout) findViewById(R.id.card_frame);
        Integer childCount = cardFrame.getChildCount();
        Log.d("Simple","childCount: "+childCount);
        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.study_card, cardFrame);
    }

}

FlipAnimation.java (not as important, just a reference)

package com.example.trevorwood.biggles.study;

import android.graphics.Camera;
import android.graphics.Matrix;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class FlipAnimation extends Animation {
    private Camera camera;
    private View fromView;
    private View toView;

    private float centerX;
    private float centerY;

    private boolean forward = true;

    /**
     * Creates a 3D flip animation between two views.
     *
     * @param fromView First view in the transition.
     * @param toView   Second view in the transition.
     */
    public FlipAnimation(View fromView, View toView) {
        this.fromView = fromView;
        this.toView = toView;

        setDuration(300);
        setFillAfter(false);
        setInterpolator(new AccelerateDecelerateInterpolator());
    }

    public void reverse() {
        forward = false;
        View switchView = toView;
        toView = fromView;
        fromView = switchView;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        centerX = width / 2;
        centerY = height / 2;
        camera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        // Angle around the y-axis of the rotation at the given time
        // calculated both in radians and degrees.
        final double radians = Math.PI * interpolatedTime;
        float degrees = (float) (180.0 * radians / Math.PI);

        // Once we reach the midpoint in the animation, we need to hide the
        // source view and show the destination view. We also need to change
        // the angle by 180 degrees so that the destination does not come in
        // flipped around
        if (interpolatedTime >= 0.5f) {
            degrees -= 180.f;
            fromView.setVisibility(View.GONE);
            toView.setVisibility(View.VISIBLE);
        }

        if (forward)
            degrees = -degrees; //determines direction of rotation when flip begins

        final Matrix matrix = t.getMatrix();
        camera.save();
        camera.translate(0, 0, Math.abs(degrees)*6);
        camera.getMatrix(matrix);
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();
        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}

I saw this, it helped but didn't solve my problem. End animation event android

I saw this too, but am not sure how to implement it into my own project. android animation is not finished in onAnimationEnd

The google docs all point to this link but this isn't reliable under rapid clicks.

Body:
This worked for me. Even though if you were to think about it, it probably shouldn't work. (It 100% would not work if converted to JavaScript, as the view is being removed before the animation has ended.) Perhaps somebody with more Android experience can explain why this works.

My hypothesis on why this works (please keep in mind, this is just a guess): is that Android's animations actually turn the view into something else entirely, while the original view is turned transparent. Then when the animation is ended, the animation view is deleted and the original view is turned back to visible.

private void flingCardAway(){

    View cardContainer = findViewById(R.id.card_container);
    ViewCompat.setTranslationZ(cardContainer, 1.0f);

    AnimationSet anim = new AnimationSet(true);

    RotateAnimation rotate1 = new RotateAnimation(0,-45, Animation.RELATIVE_TO_SELF,0.5f , Animation.RELATIVE_TO_SELF,0.5f );
    rotate1.setStartOffset(10);
    rotate1.setDuration(500);
    anim.addAnimation(rotate1);

    TranslateAnimation trans1 =  new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -0.2f, Animation.RELATIVE_TO_PARENT, -0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
    trans1.setDuration(100);
    anim.addAnimation(trans1);

    TranslateAnimation trans2 =  new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
    trans2.setStartOffset(100);
    trans2.setDuration(100);
    anim.addAnimation(trans2);

    AlphaAnimation opacity1 = new AlphaAnimation(1.0f, 0.0f);
    opacity1.setDuration(300);
    opacity1.setStartOffset(300);
    anim.addAnimation(opacity1);

    cardContainer.setAnimation(anim);

    mCardFrame.removeAllViews();

}


问:
When App Engine (Java) spins up new instances, how do I ensure that Task Queue Memcache crons are shared across them?
This is a problem where my app experiences occasional CPU limit peaks on a site in which almost all of the work is done as a result of a cron task which runs frequently every hour to call a task queue which repopulates the memcache.

Recently the site received a large spike in traffic resulting in multiple instances being spun up.

However, to my surprise, I had to reduce the frequency of the Memcache task during those days even though less than 1% of the CPU usage was related to the traffic spike. (99% of the work done in this app is (a) in the memcache task queue and (b) in client-side JavaScript/JSON logic).

What I'm wondering is whether the additional instances that were spun up all require their own Memcache task queues and perhaps this is why I saw a much higher CPU usage related to the task queue that repopulates the memcache during those days - the task was actually being executed separately for each of the instances?

If so, how can I ensure that the task queue - and the Memcache that it populates - is shared across the instances - if this is possible at all?

答: The task queue and memcache are both global. It's likely that you were enqueueing the task in some fashion that depended on the number of instances, so you were starting more tasks than you should've - it's impossible to say without seeing your code.</p>


问:
ERROR TypeError: _co.onCLk is not a function
Trying one code in Angular 2 its HTML is running but angular code is not executing it says the value which i am passing from html is not a function. Please help!

HTML: app.html - i am trying to show the student details. I have a list of items in angular app.component.ts file which i am calling on HTML page which is working fine. But when i am passing a value on a click event to app.component.ts fine its giving error and showing on console that this is not a function.

 Student Directory

     Search
        for: {{ name }}
        <input class = "search-input" #newStudent>
        <button class ="btn"
        (click)="addstudent(newstudent.value)"
        >Add</button>

{{ stud.name }}

{{ stud.Empname }}

```
</div>
</div>
</p>

<p>Angular component.app.ts: Here i am defining variables and add click event to show name i am clicking from the html to show on UI. At the same time i have given a ability to add more names to the already added list on the UI.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './partials/app.html'
})

export class AppComponent {
  name: string;
  students: any;
  event: any;

  onClk(event){
   this.name = event.target.innerHTML;
  }

  addstudent(value){
    if(value!=' '){
      this.students.push({
        name: value,
        Empname: 'xyz'
      });
    }
  }

  constructor(){
  this.students = [
    {
      name: 'Robin',
      Empname: 'abc'
    },{
      name: 'Jack',
      Empname: 'Bcd'
    },{
      name: 'John',
      Empname: 'Cde'
    }
  ]
  }

}</code>```

Getting error message on console when i run the code: Type error i am getting here is onCLK is not a function. Its a function which is returning value form HTML to app.component.ts file and from there we are getting the value we clicked. Also getting many other errors not sure what does that mean?

```<code>app.html:12 ERROR TypeError: _co.onCLk is not a function
at Object.eval [as handleEvent] (app.html:12)
at handleEvent (view.ts:142)
at callWithDebugContext (services.ts:815)
at Object.debugHandleEvent [as handleEvent] (services.ts:411)
at dispatchEvent (util.ts:185)
at eval (element.ts:238)
at HTMLLIElement.eval (dom_renderer.ts:75)
at ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (ng_zone.ts:288)
at ZoneDelegate.invokeTask (zone.js:424)
</code>```

答:
You have named the function wrong in your template, Change "L" to "l"

From

```<code> (click)="onCLk($event)"
</code>```

To

```<code> (click)="onClk($event)"
</code>```

Body:
Trying one code in Angular 2 its HTML is running but angular code is not executing it says the value which i am passing from html is not a function. Please help!

HTML: app.html - i am trying to show the student details. I have a list of items in angular app.component.ts file which i am calling on HTML page which is working fine. But when i am passing a value on a click event to app.component.ts fine its giving error and showing on console that this is not a function.

 Student Directory

     Search
        for: {{ name }}
        <input class = "search-input" #newStudent>
        <button class ="btn"
        (click)="addstudent(newstudent.value)"
        >Add</button>

{{ stud.name }}

{{ stud.Empname }}

Angular component.app.ts: Here i am defining variables and add click event to show name i am clicking from the html to show on UI. At the same time i have given a ability to add more names to the already added list on the UI.

import { Component } from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './partials/app.html'
})

export class AppComponent {
  name: string;
  students: any;
  event: any;

  onClk(event){
   this.name = event.target.innerHTML;
  }

  addstudent(value){
    if(value!=' '){
      this.students.push({
        name: value,
        Empname: 'xyz'
      });
    }
  }

  constructor(){
  this.students = [
    {
      name: 'Robin',
      Empname: 'abc'
    },{
      name: 'Jack',
      Empname: 'Bcd'
    },{
      name: 'John',
      Empname: 'Cde'
    }
  ]
  }

}

Getting error message on console when i run the code: Type error i am getting here is onCLK is not a function. Its a function which is returning value form HTML to app.component.ts file and from there we are getting the value we clicked. Also getting many other errors not sure what does that mean?

app.html:12 ERROR TypeError: _co.onCLk is not a function
at Object.eval [as handleEvent] (app.html:12)
at handleEvent (view.ts:142)
at callWithDebugContext (services.ts:815)
at Object.debugHandleEvent [as handleEvent] (services.ts:411)
at dispatchEvent (util.ts:185)
at eval (element.ts:238)
at HTMLLIElement.eval (dom_renderer.ts:75)
at ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (ng_zone.ts:288)
at ZoneDelegate.invokeTask (zone.js:424)

Body:
You have named the function wrong in your template, Change "L" to "l"

From

 (click)="onCLk($event)"

To

 (click)="onClk($event)"

ContentLicense: CC BY-SA 4.0


问:
best practice to add git workflow on existing websites
Up until now I worked on my websites alone and without any kind of version control right on my server (basically opened and modified files stored in each /var/www/vhosts/domain.tld/httpdocs-Folder directly over sftp with an IDE/over ssh) since it was sufficient for my needs.

Now I'm searching for the best way to collaborate with other developers and use git for all of these already existing websites.

Is it recommendable to create multiple bare repositories like

/home/git/domain_1.git,   /home/git/domain_2.git, ...

with e.g. git init --bare domain_1.git in some folder like /home/git/
with my root-Account and then somehow** add each already existing /var/www/vhosts/domain/httpdocs-Folder to each of these bare git repos and then add an hook (post-receive?) to each repo to overwrite it's specific /var/www/vhosts/domain.tld/httpdocs-Folder at every push. And then give every developer access via the git-User with URL like ssh://git@1.2.3.4:/home/git/domain_1.git for each single repo.

If that way should be fine: Is there any kind of walkthrough out there? I couldn't find anything and I'm searching for a proper solution since days, no kidding...

Or is there any better/best practice to solve this kind of issue?

** = (how?! since no git command like git add works on these bare repos...)

答:
You don't want to use a bare repo (since it won't have a working directory).

To create your repos, you can use git init in the root of whatever directory has your files. Even better, use github/bitbucket and it will create the repo for you. Then you can clone it, do your initial commit, and push.

The key point here is that the "main" place you are storing your code is not on the live server and not on your development machine. This also makes it so everyone doesn't have to ssh to your live server to do a push.

You then clone your repos wherever you need them, probably on your development machine to make changes. commit and push back to bitbucket. Then you'd have another clone on your live server (for you at /var/www/vhosts/domain.tld/httpdocs-Folder) where your "deploy" process is to git pull to get the latest changes that have been pushed to bitbucket.

Other options include having a process watch your bitbucket repo for any commit to your master branch and automatically pulling.

For this to be safe, you'll need to research branching strategies. Pick one and make sure all committers know how to follow it.

A simple one is to have the master branch be "what is live in prod" and develop be where you make change. So changes flow from developer machine develop branch to master branch to bitbucket to live server. Using pull requests (with code reviews) for merging code to master will help keep master stable.


问:
how to copy lines 10 to 15 of a file into another file, in unix?
I want to copy lines 10 to 15 of a file into another file in Unix.

I am having files file1.txt and file2.txt.

I want to copy lines 10 to 15 from file1.txt to file2.txt.

答:
Open a terminal with a shell then

```<code>sed -n '10,15p' file1.txt > file2.txt
</code>```

Simple & easy.

If you want to append to the end instead of wiping file2.txt, use >> for redirection.

```<code>sed -n '10,15p' file1.txt >> file2.txt
                          ^^
</code>```

AWK is also a powerful command line text manipulator:

```<code>awk 'NR>=10 && NR<=15' file1.txt > file2.txt
</code>```

Body:
Open a terminal with a shell then

sed -n '10,15p' file1.txt > file2.txt

Simple & easy.

If you want to append to the end instead of wiping file2.txt, use >> for redirection.

sed -n '10,15p' file1.txt >> file2.txt
                          ^^

AWK is also a powerful command line text manipulator:

awk 'NR>=10 && NR<=15' file1.txt > file2.txt


问:
SQL-Identify and fix criss cross records
I have a table of program members with incorrect data I am trying to fix programmatically.
The following query exposes the records that need to be fixed.

```<code>select a.*
from Table a
join Table b
on a.BillingMemberID = b.MemberID
where a.MemberID = b.BillingMemberID
and a.MemberID != a.BillingMemberID
</code>```

Example data would be:

```<code>MemberID | BillingMemberID
1        | 1
2        | 7               <== MemberID and BillingMemberID of 2 & 7 criss cross
3        | 4               <== MemberID and BillingMemberID of 3 & 4 criss cross
4        | 3
5        | 6               <== MemberID and BillingMemberID of 5 & 6 criss cross
6        | 5
7        | 2
8        | 8
</code>```

The fixed data would look like:

```<code>MemberID | BillingMemberID
1        | 1
2        | 2
3        | 3
4        | 3
5        | 5
6        | 5
7        | 2
8        | 8
</code>```

Taking the lowest ID number of the crossed pairs and changing the BillingMemberID of the other record.
How would I write a SQL script to go through a table of 5K+ records, find these crossed pairs and fix them as shown?

答:
From your description I believe that you need to update the rows where MemberID< BillingMemberID. Below script will do the work for you.(I believe it is just one table)</p>

```<code>UPDATE <table_Name>
   SET BillingMemberID=MemberID
 WHERE MemberID<BillingMemberID
</code>```

Body:
I have a table of program members with incorrect data I am trying to fix programmatically.
The following query exposes the records that need to be fixed.

select a.*
from Table a
join Table b
on a.BillingMemberID = b.MemberID
where a.MemberID = b.BillingMemberID
and a.MemberID != a.BillingMemberID

Example data would be:

MemberID | BillingMemberID
1        | 1
2        | 7               <== MemberID and BillingMemberID of 2 & 7 criss cross
3        | 4               <== MemberID and BillingMemberID of 3 & 4 criss cross
4        | 3
5        | 6               <== MemberID and BillingMemberID of 5 & 6 criss cross
6        | 5
7        | 2
8        | 8

The fixed data would look like:

MemberID | BillingMemberID
1        | 1
2        | 2
3        | 3
4        | 3
5        | 5
6        | 5
7        | 2
8        | 8

Taking the lowest ID number of the crossed pairs and changing the BillingMemberID of the other record.
How would I write a SQL script to go through a table of 5K+ records, find these crossed pairs and fix them as shown?

Body:
From your description I believe that you need to update the rows where MemberID< BillingMemberID. Below script will do the work for you.(I believe it is just one table)

UPDATE <table_Name>
   SET BillingMemberID=MemberID
 WHERE MemberID<BillingMemberID


问:
mysql select all table names except
Alright, I know you can do the following to get all column names.

```<code>SHOW COLUMNS FROM person;
</code>```

However, it does not allow where statements.

Is there any way to get the full list and just say not this one?

So I am basically looking for something like this:

```<code>select (show columns from person where Field <> 'id') from person
</code>```

答:
USe SHOW [FULL] COLUMNS {FROM | IN} tbl_name [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr]

Example:

SHOW CHARACTER SET WHERE `Default collation` LIKE '%japanese%';

More about show here

Try something like SHOW COLUMNS FROM person WHERE column != 'value';

Title: mysql select all table names except

Body:
Alright, I know you can do the following to get all column names.

SHOW COLUMNS FROM person;

However, it does not allow where statements.

Is there any way to get the full list and just say not this one?

So I am basically looking for something like this:

select (show columns from person where Field <> 'id') from person


问:
D3 Adding arrowheads to edges, directed graph
I would like to add directionality to my D3 graph. The json will have an attribute called "direction" and it will either be "--", "<-", or "->"
meaning:

```<code>source <- target (arrow from target to source)
source -> target (arrow from source to target)
source -- target (no direction)
</code>```

I would like it to match the color of the links if possible (not crucial)
Any assistance would be welcome!

My script below

```<code><!DOCTYPE html>
<meta charset="utf-8">
<style>
    .node {
        stroke: #fff;
        stroke-width: 1.5px;
    }

    .link {
        stroke: #999;
        stroke-opacity: .6;
    }

    .axis {
        opacity: 0.5;
        font: 10px sans-serif;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
    }

    .axis .domain {
        fill: none;
        stroke: #000;
        stroke-opacity: .3;
        stroke-width: 4px;
        stroke-linecap: round;
    }

    .axis .halo {
        fill: none;
        stroke: #ddd;
        stroke-width: 3px;
        stroke-linecap: round;
    }

    text {
        pointer-events: none;
        font: 8px sans-serif;
        stroke: none;
        fill: black;
    }

    .slider .handle {
        fill: #fff;
        stroke: #000;
        stroke-opacity: .5;
        stroke-width: 1.25px;
        cursor: grab;
    }

    div.tooltip {
        position: absolute;
        text-align: center;
        width: 60px;
        height: 28px;
        padding: 2px;
        font: 12px sans-serif;
        background: lightsteelblue;
        border: 0px;
        border-radius: 8px;
        pointer-events: none;
    }
</style>

<body>
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script>
        var width = 960,
            height = 500;

        var color = d3.scale.category20();

        var force = d3.layout.force()
            .charge(-120)
            .linkDistance(30)
            .size([width, height]);

        var x = d3.scale.linear()
            .domain([0, 20])
            .range([250, 80])
            .clamp(true);

        var brush = d3.svg.brush()
            .y(x)
            .extent([0, 0]);

        var svg = d3.select("body").append("svg")
            .attr("width", width)
            .attr("height", height);

        var links_g = svg.append("g");

        var nodes_g = svg.append("g");

        // Define the div for the tooltip
        var div = d3.select("body").append("div")
            .attr("class", "tooltip")
            .style("opacity", 0);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(" + (width - 20) + ",0)")
            .call(d3.svg.axis()
                .scale(x)
                .orient("left")
                .tickFormat(function(d) {
                    return d;
                })
                .tickSize(0)
                .tickPadding(12))
            .select(".domain")
            .select(function() {
                return this.parentNode.appendChild(this.cloneNode(true));
            })
            .attr("class", "halo");

        var slider = svg.append("g")
            .attr("class", "slider")
            .call(brush);

        slider.selectAll(".extent,.resize")
            .remove();

        var handle = slider.append("circle")
            .attr("class", "handle")
            .attr("transform", "translate(" + (width - 20) + ",0)")
            .attr("r", 5);

        svg.append("text")
            .attr("x", width - 15)
            .attr("y", 60)
            .attr("text-anchor", "end")
            .attr("font-size", "12px")
            .style("opacity", 0.5)
            .text("degree threshold")

        d3.json("test.json", function(error, graph) {
            if (error) throw error;

            graph.links.forEach(function(d, i) {d.i = i;});
            graph.nodes.forEach(function(d, i) {d.i = i;});

            function brushed() {
                var value = brush.extent()[0];

                if (d3.event.sourceEvent) {
                    value = x.invert(d3.mouse(this)[1]);
                    brush.extent([value, value]);
                }

                handle.attr("cy", x(value));
                var threshold = value;

                var thresholded_links = graph.links.filter(function(d) {
                    return (d.max_degree > threshold);
                });

                force
                    .links(thresholded_links);

                var link = links_g.selectAll(".link")
                    .data(thresholded_links, function(d) {
                        return d.i;
                    });

                link.enter().append("line")
                    .attr("class", "link")
                    .style("stroke-width", function(d) {
                        return Math.sqrt(d.value);
                    });

                link.exit().remove();

                force.on("tick", function() {
                    link.attr("x1", function(d) {return d.source.x;})
                        .attr("y1", function(d) {return d.source.y;})
                        .attr("x2", function(d) {return d.target.x;})
                        .attr("y2", function(d) {return d.target.y;});

                    node.attr("transform", function(d) {
                        return "translate(" + d.x + "," + d.y + ")";
                    });

                });

                force.start();
                //console.log(link);
                link.each(function(d) {
                    d3.select(this).style("stroke", d.min_degree >= value ? "#3182bd" : "#ccc")
                });

                node.each(function(d) {
                    d3.select(this).select("circle").style("fill", d.degree > value ? color(1) : d.weight > 0 ? color(2) : "#ccc")
                });

                node.each(function(d) {
                    d3.select(this).select("text").style("fill", d.degree > value ? color(1) : d.weight > 0 ? color(2) : "#ccc")
                });

            }

            force
                .nodes(graph.nodes);

            var node = nodes_g.selectAll(".node")
                .data(graph.nodes)
                .enter()
                .append('g')
                .attr("class", "node")
                .call(force.drag);

            node.append("circle")
                .attr("r", 5)
                .style("fill", function(d) {
                    return color(1);
                })
                .on("mouseover", function(d) {
                    div.transition()
                        .duration(200)
                        .style("opacity", .9);
                    div.html(d.name + "\ndegree:" + d.degree)
                        .style("left", (d3.event.pageX) + "px")
                        .style("top", (d3.event.pageY - 28) + "px");
                })
                .on("mouseout", function(d) {
                    div.transition()
                        .duration(500)
                        .style("opacity", 0);
                });

            node.append("text")
                .attr("dx", 4)
                .attr("dy", ".35em")
                .text(function(d) {
                    return d.name;
                });

            brush.on("brush", brushed);

            slider
                .call(brush.extent([16.5, 16.5]))
                .call(brush.event);
        });
    </script>
</code>```

Here is a sample json: test.json

答:
I implemented something like what I think you're trying to achieve in a geojson sankey. Maybe you can use some of the code. Here's a link to the block.

And part of the relevant code:

```<code>       var arrow = L.polylineDecorator(line, { patterns: [{
                offset: '55%',
                symbol: L.Symbol.arrowHead({
                    polygon: true,
                    pathOptions: {
                        weight: lineWeight,
                        color: lineColor
                    }
                })
            }]});
</code>```

Hope this helps.

Body:
I would like to add directionality to my D3 graph. The json will have an attribute called "direction" and it will either be "--", "<-", or "->"
meaning:

source <- target (arrow from target to source)
source -> target (arrow from source to target)
source -- target (no direction)

I would like it to match the color of the links if possible (not crucial)
Any assistance would be welcome!

My script below

<!DOCTYPE html>
<meta charset="utf-8">

Here is a sample json: test.json

Body:
I implemented something like what I think you're trying to achieve in a geojson sankey. Maybe you can use some of the code. Here's a link to the block.

And part of the relevant code:

       var arrow = L.polylineDecorator(line, { patterns: [{
                offset: '55%',
                symbol: L.Symbol.arrowHead({
                    polygon: true,
                    pathOptions: {
                        weight: lineWeight,
                        color: lineColor
                    }
                })
            }]});

Hope this helps.


问:
How to restart an Azure appservice from Azure Powershell
How can you restart an AppService from Azure's Powershell running in a Runbook in an Automation Account in an ARM subscription in Azure?

I thought the approach would be:

```<code>Restart-AzureWebsite -Name "your-appservice-name"
</code>```

but that gets:

```<code>Restart-AzureWebsite : No default subscription has been designated.
Use select-AzureSubscription -Default #<subscriptionName> to set the default subscription.
</code>```

There is no Restart-AzureRmWebApp available in Azure PowerShell.

All combinations of the following lead to just a bunch of other error messages:

```<code>$Cred = Get-AutomationPSCredential -Name 'your-credentials-name'
Add-AzureAccount -Credential $Cred
Add-AzureRMAccount -Credential $Cred
Get-AzureSubscription –SubscriptionName 'your-subscription-name' | Select-AzureSubscription -Default
Restart-AzureWebsite -Name "your-appservice-name"
</code>```

答:
There is no Restart-AzureRmWebApp available in Azure PowerShell.

As  Walter - MSFT mentioned that we could import AzureRM.Websites, before that we need to update AzureRM.Profile to 4.0, more detail you could refer to the screenshot.

Before to do that we could create Azure AD service principal locally.
How to create service principal we could refer to this document

```<code> Login-AzureRmAccount
 $sp = New-AzureRmADServicePrincipal -DisplayName exampleapp -Password "password"
 Sleep 20
 New-AzureRmRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $sp.ApplicationId
</code>```

Run Restart-AzureRmWebApp command in the Runbook.

```<code>$azureAplicationId ="Application Id"
$azureTenantId= "tenant Id"
$azurePassword = ConvertTo-SecureString "password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId $azureTenantId  -ServicePrincipal
Restart-AzureRmWebApp -ResourceGroupName "ResourceGroup" -Name "WebApp Name"
</code>```

Body:
How can you restart an AppService from Azure's Powershell running in a Runbook in an Automation Account in an ARM subscription in Azure?

I thought the approach would be:

Restart-AzureWebsite -Name "your-appservice-name"

but that gets:

Restart-AzureWebsite : No default subscription has been designated.
Use select-AzureSubscription -Default #<subscriptionName> to set the default subscription.

There is no Restart-AzureRmWebApp available in Azure PowerShell.

All combinations of the following lead to just a bunch of other error messages:

$Cred = Get-AutomationPSCredential -Name 'your-credentials-name'
Add-AzureAccount -Credential $Cred
Add-AzureRMAccount -Credential $Cred
Get-AzureSubscription –SubscriptionName 'your-subscription-name' | Select-AzureSubscription -Default
Restart-AzureWebsite -Name "your-appservice-name"

Body:
There is no Restart-AzureRmWebApp available in Azure PowerShell.

As  Walter - MSFT mentioned that we could import AzureRM.Websites, before that we need to update AzureRM.Profile to 4.0, more detail you could refer to the screenshot.

Before to do that we could create Azure AD service principal locally.
How to create service principal we could refer to this document

 Login-AzureRmAccount
 $sp = New-AzureRmADServicePrincipal -DisplayName exampleapp -Password "password"
 Sleep 20
 New-AzureRmRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $sp.ApplicationId

Run Restart-AzureRmWebApp command in the Runbook.

$azureAplicationId ="Application Id"
$azureTenantId= "tenant Id"
$azurePassword = ConvertTo-SecureString "password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId $azureTenantId  -ServicePrincipal
Restart-AzureRmWebApp -ResourceGroupName "ResourceGroup" -Name "WebApp Name"


问:
Where exactly(!) does the stack pointer point to on x86-CPUs? TO the top element or RIGHT BEHIND it?
In some tutorials it is said that the stack pointer points TO the top element of the stack:

```<code>+-------------+
|    stack    |
+-------------+
| top element |  <-- esp
+-------------+
</code>```

In others it is said that it points RIGHT BEHIND it, so to the first memory address which can be written to when the stack grows.

```<code>+-------------+
|    stack    |
+-------------+
| top element |
+-------------+  <-- esp
</code>```

On this german Wickipedia site
https://de.wikipedia.org/wiki/Register_(Computer)#Stapelregister
it is said that both versions exist and that it depends on the CPU architecture.

My question is, how is it on x86-CPUs? And does it also depend on the operating system?

答:
Let's say you are in 32b x86 mode, and you have memory from address 100 to 200 reserved as stack (unreal, too low, would clash with IVT, but will do for this example). There are already some values in stack, so esp is 160.

Now the "top of the stack value" occupies memory at addresses 160, 161, 162 and 163 (four bytes, because in 32b mode the single value in stack is 32b = 4B big), let's say there's stored value 0xaabbccdd.

If you now do push 0x12345678, the CPU will first subtract 4 from esp -> new esp = 156; (160-4). And then it will write the 32b value, broken down in little-endian way as four bytes: mem[156] = 0x78, mem[157] = 0x56, mem[158] = 0x34, mem[159] = 0x12.

Now if you will execute mov eax,[esp], it will load 32 bit value from address 156, which means it will compose 32b value from four bytes at addresses 156, 157, 158, 159 into dword value 0x12345678.

Finally when you will view the memory in debugger after the push, viewing it from ss:esp address, it will contain these bytes (hexa):

```<code>0000009C:  78 56 34 12 DD CC BB AA ....
</code>```

(0x9C = 156 = address where the memory view starts). The esp points at the first byte of the value, which is considered to be "top of stack".

Or when you switch memory view to display dword values, to avoid the little-endian composing in head, it will show:

```<code>0000009C:  12345678 AABBCCDD ....
</code>```

Body:
In some tutorials it is said that the stack pointer points TO the top element of the stack:

+-------------+
|    stack    |
+-------------+
| top element |  <-- esp
+-------------+

In others it is said that it points RIGHT BEHIND it, so to the first memory address which can be written to when the stack grows.

+-------------+
|    stack    |
+-------------+
| top element |
+-------------+  <-- esp

On this german Wickipedia site
https://de.wikipedia.org/wiki/Register_(Computer)#Stapelregister
it is said that both versions exist and that it depends on the CPU architecture.

My question is, how is it on x86-CPUs? And does it also depend on the operating system?

Body:
Let's say you are in 32b x86 mode, and you have memory from address 100 to 200 reserved as stack (unreal, too low, would clash with IVT, but will do for this example). There are already some values in stack, so esp is 160.

Now the "top of the stack value" occupies memory at addresses 160, 161, 162 and 163 (four bytes, because in 32b mode the single value in stack is 32b = 4B big), let's say there's stored value 0xaabbccdd.

If you now do push 0x12345678, the CPU will first subtract 4 from esp -> new esp = 156; (160-4). And then it will write the 32b value, broken down in little-endian way as four bytes: mem[156] = 0x78, mem[157] = 0x56, mem[158] = 0x34, mem[159] = 0x12.

Now if you will execute mov eax,[esp], it will load 32 bit value from address 156, which means it will compose 32b value from four bytes at addresses 156, 157, 158, 159 into dword value 0x12345678.

Finally when you will view the memory in debugger after the push, viewing it from ss:esp address, it will contain these bytes (hexa):

0000009C:  78 56 34 12 DD CC BB AA ....

(0x9C = 156 = address where the memory view starts). The esp points at the first byte of the value, which is considered to be "top of stack".

Or when you switch memory view to display dword values, to avoid the little-endian composing in head, it will show:

0000009C:  12345678 AABBCCDD ....