问:
My angular controller doesnt send data to c# controller
Hello everyone,
                I couldn't send data from my angular controller to my c# controller.Whenever the controller is called it throws out error callback.I have tried different ways,but i couldn't rectify it.Am i making any mistake in defining correct url.I am really clueless.

Angular controller

```<code> var httpTimeout = 1800000;
                var httpTimeoutSearch = 3600000;
                angular.module('MyApp', [])
                var app = angular.module('myApp', []);
                app.controller('LoginController', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {
                    alert("in");
                    $scope.Username = "";
                    $scope.Password = "";

                    $scope.Login = function () {
                        if ($scope.Username != null && $scope.username != "") {
                            if ($scope.Password != null && $scope.password != "") {
                                try {
                                    var obj = { UserName: $scope.Username, Password: $scope.Password };
                                    alert(obj.Username);
                                    $http({
                                        method: 'POST',
                                        data: obj,
                                        url: '/Account/Maxi',
                                        timeout: httpTimeout,
                                    }).then(function successCallback(response) {
                                        alert("sucess");
                                    }, function errorCallback(response) {
                                        alert("error");
                                    });
                                }
                                catch (ex)
                                { alert(ex); }
                            }
                        }

                    }
                }]);
</code>```

C# controller

```<code> [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Maxi(LoginModel data)
        {
            string strReturn = "";
            string ConStr = "";
            string Code = "";
            if (data.UserName != null)
           {
               if (data.Password != null)
               {

                   DataSet ds = new DataSet();
                   SqlParameter[] parameters =
                    {

                     new SqlParameter( "@name", SqlDbType.VarChar, 20) { Value = data.UserName } ,
                     new SqlParameter("@Roll_No", SqlDbType.Int) { Value = data.Password  } ,

                    };
                   ConStr = "Data Source=" + "192.168.1.9" + ";Initial Catalog=" + "MyFistDataBase" + ";User id=" + "sa" + ";Password=" + "123" + ";";
                   using (SqlConnection con = new SqlConnection(ConStr))
                   {
                       using (SqlCommand cmd = new SqlCommand("Maxi", con))
                       {
                           cmd.CommandType = CommandType.StoredProcedure;
                           SqlDataAdapter da = new SqlDataAdapter();
                           cmd.Parameters.AddRange(parameters);
                           da.SelectCommand = cmd;
                           da.Fill(ds);
                       }
                   }

                   string errmsg = "";

                   if (errmsg != "")
                   {
                       Code = "0"; strReturn = errmsg;
                   }
                   else
                   {
                       if (ds.Tables.Count > 0)
                       {
                           if (ds.Tables[0].Rows.Count > 0)
                           {
                               Code = "1";

                               foreach (DataRow dr in ds.Tables[0].Rows)
                               {
                                   strReturn += dr[0].ToString();
                               }
                               if (strReturn == "1")
                               {
                                   Console.Write("Updated");
                               }

                           }
                           //TripDT = TripDT.ToShortDateString();
                       }

                   }
               }
           }
            return View(data);
        }
</code>```

Object Model

```<code> public class LoginModel
    {
         [Key]
        public string UserName { get; set; }
        public string Password { get; set; }
    }
</code>```

答:
You are misspelling the sending KVP data.

```<code>var obj = { Username: $scope.Username, Passord: $scope.Password };
</code>```

should be

```<code>var obj = { UserName: $scope.Username, Password: $scope.Password };
</code>```

for verificationToken error need to add this data to json also

```<code> "__RequestVerificationToken" : your_html_value
</code>```

see how to add this key data HERE in Detail

Body:
Hello everyone,
                I couldn't send data from my angular controller to my c# controller.Whenever the controller is called it throws out error callback.I have tried different ways,but i couldn't rectify it.Am i making any mistake in defining correct url.I am really clueless.

Angular controller

 var httpTimeout = 1800000;
                var httpTimeoutSearch = 3600000;
                angular.module('MyApp', [])
                var app = angular.module('myApp', []);
                app.controller('LoginController', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {
                    alert("in");
                    $scope.Username = "";
                    $scope.Password = "";

                    $scope.Login = function () {
                        if ($scope.Username != null && $scope.username != "") {
                            if ($scope.Password != null && $scope.password != "") {
                                try {
                                    var obj = { UserName: $scope.Username, Password: $scope.Password };
                                    alert(obj.Username);
                                    $http({
                                        method: 'POST',
                                        data: obj,
                                        url: '/Account/Maxi',
                                        timeout: httpTimeout,
                                    }).then(function successCallback(response) {
                                        alert("sucess");
                                    }, function errorCallback(response) {
                                        alert("error");
                                    });
                                }
                                catch (ex)
                                { alert(ex); }
                            }
                        }

                    }
                }]);

C# controller

 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Maxi(LoginModel data)
        {
            string strReturn = "";
            string ConStr = "";
            string Code = "";
            if (data.UserName != null)
           {
               if (data.Password != null)
               {

                   DataSet ds = new DataSet();
                   SqlParameter[] parameters =
                    {

                     new SqlParameter( "@name", SqlDbType.VarChar, 20) { Value = data.UserName } ,
                     new SqlParameter("@Roll_No", SqlDbType.Int) { Value = data.Password  } ,

                    };
                   ConStr = "Data Source=" + "192.168.1.9" + ";Initial Catalog=" + "MyFistDataBase" + ";User id=" + "sa" + ";Password=" + "123" + ";";
                   using (SqlConnection con = new SqlConnection(ConStr))
                   {
                       using (SqlCommand cmd = new SqlCommand("Maxi", con))
                       {
                           cmd.CommandType = CommandType.StoredProcedure;
                           SqlDataAdapter da = new SqlDataAdapter();
                           cmd.Parameters.AddRange(parameters);
                           da.SelectCommand = cmd;
                           da.Fill(ds);
                       }
                   }

                   string errmsg = "";

                   if (errmsg != "")
                   {
                       Code = "0"; strReturn = errmsg;
                   }
                   else
                   {
                       if (ds.Tables.Count > 0)
                       {
                           if (ds.Tables[0].Rows.Count > 0)
                           {
                               Code = "1";

                               foreach (DataRow dr in ds.Tables[0].Rows)
                               {
                                   strReturn += dr[0].ToString();
                               }
                               if (strReturn == "1")
                               {
                                   Console.Write("Updated");
                               }

                           }
                           //TripDT = TripDT.ToShortDateString();
                       }

                   }
               }
           }
            return View(data);
        }

Object Model

 public class LoginModel
    {
         [Key]
        public string UserName { get; set; }
        public string Password { get; set; }
    }

Body:
You are misspelling the sending KVP data.

var obj = { Username: $scope.Username, Passord: $scope.Password };

should be

var obj = { UserName: $scope.Username, Password: $scope.Password };

for verificationToken error need to add this data to json also

 "__RequestVerificationToken" : your_html_value

see how to add this key data HERE in Detail


来源: stackexchange

问:
Undefined Input Error in Basic Handling Form ReactJs
I am working on ReactJs form with React Bootstrap Library, I got error Undefined when running the form in browser. In Terminal, I have no error.

```<code>constructor(props){
    super(props);

    this.state = {
        username: '',
        password: '',
        fullname: ''
    }

    this.handleUsername = this.handleUsername.bind(this);
    this.handlePassword = this.handlePassword.bind(this);
    this.handleFullname = this.handleFullname.bind(this);
    this.submitUser = this.submitUser.bind(this);
}

handleUsername = (event) => {
    this.setState({
        username : event.target.value
    }, () => console.log(this.setState))

}

handlePassword = (event) => {
    this.setState({
        password: event.target.value
    })
}

handleFullname = (event) => {
    this.setState({
        fullname: event.target.value
    })
}
</code>```

I tried some suggestion in handling form but still not working. here is the form i coded :

```<code><Form className="salesUser text-left " variant="success" onSubmit={this.submitUser}>
    <Form.Group>
         <Form.Label>Username</Form.Label>
         <Form.Control type="text" value={this.state.username} onChange={this.handleUsername}></Form.Control>
    </Form.Group>
    <Form.Group>
        <Form.Label>Password</Form.Label>
        <Form.Control type="password" value={this.state.password} onChange={this.handlePassword}></Form.Control>
    </Form.Group>
    <Form.Group>
        <Form.Label>Full Name</Form.Label>
        <Form.Control type="text" value={this.state.fullname} onChange={this.handleFullname}></Form.Control>
    </Form.Group>
    <Row>
        <Col>
            <Button type="submit" value="Submit" block>Submit</Button>
        </Col>
    </Row>
</Form>
</code>```

I tried to put console.log in handleUsername to find the error, and this is the error message when I type something in form username.

hopefully I ask the rigth question this time

答:
```<code>handleUsername = (event) => {
    this.setState({
        username : event.target.value
    })
    console.log(this.setState) //**invlaid code** should be this.state but still you won't get the updated state. Instead try this as below

    this.setState({
        username : event.target.value
    }, () => console.log(this.state)) //this callback function will log your updated state in console.
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on ReactJs form with React Bootstrap Library, I got error Undefined when running the form in browser. In Terminal, I have no error.

constructor(props){
    super(props);

    this.state = {
        username: '',
        password: '',
        fullname: ''
    }

    this.handleUsername = this.handleUsername.bind(this);
    this.handlePassword = this.handlePassword.bind(this);
    this.handleFullname = this.handleFullname.bind(this);
    this.submitUser = this.submitUser.bind(this);
}

handleUsername = (event) => {
    this.setState({
        username : event.target.value
    }, () => console.log(this.setState))

}

handlePassword = (event) => {
    this.setState({
        password: event.target.value
    })
}

handleFullname = (event) => {
    this.setState({
        fullname: event.target.value
    })
}

I tried some suggestion in handling form but still not working. here is the form i coded :

<Form className="salesUser text-left " variant="success" onSubmit={this.submitUser}>
    <Form.Group>
         <Form.Label>Username</Form.Label>
         <Form.Control type="text" value={this.state.username} onChange={this.handleUsername}></Form.Control>
    </Form.Group>
    <Form.Group>
        <Form.Label>Password</Form.Label>
        <Form.Control type="password" value={this.state.password} onChange={this.handlePassword}></Form.Control>
    </Form.Group>
    <Form.Group>
        <Form.Label>Full Name</Form.Label>
        <Form.Control type="text" value={this.state.fullname} onChange={this.handleFullname}></Form.Control>
    </Form.Group>
    <Row>
        <Col>
            <Button type="submit" value="Submit" block>Submit</Button>
        </Col>
    </Row>
</Form>

I tried to put console.log in handleUsername to find the error, and this is the error message when I type something in form username.

hopefully I ask the rigth question this time


问:
from Eclipse to Android phone
I have made a program on eclipse. But how can I get the program from eclipse to my phone? I have a cable because it probably wont make a QR code like appinventor does huh. How do i install my app on there? </p>

答: You can simply export the apk file and copy it to your phone. Email it to yourself, bluetooth transfer, upload to a server then download on your phone.... come on.</p>

ContentLicense: CC BY-SA 3.0

Title: from Eclipse to Android phone


问:
Force the source url to download automatically by adding the url headers
I have a source URL that displays the pdf document in the browser. It supposes to download automatically.

Sample URL : http://doc.local.com/storage/temporary/2020-02-19/c3e175b4706492be8c0d90e497c86ea7/test.pdf

Exactly I want to implement how amazon s3 temporary url works (they added all the headers in the url)

response-content-disposition=attachment

Please don't suggest me to use the following code, as front-end expect an URL

```<code>header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);
</code>```

答:
I have a little hack to achieve the task -

Let's assume you URL is something -

```<code>https://somedomain.com/somepath/file.pdf
</code>```

Create an api as below -

```<code>https://somedomain.com/somepath/file.pdf?signature=signature&ttl=some-ttl
</code>```

signature to validate the request it is authentic or not

ttl is to validate if the URL is still active for that signature

Then after validating the API request, you can return the download response as below -

```<code>public function getDownload()
{
    //PDF file is stored under project/public/download/info.pdf
    $file= public_path(). "/download/info.pdf";

    $headers = array(
              'Content-Type: application/pdf',
            );

    return Response::download($file, 'filename.pdf', $headers);
}
</code>```

ref - Download files in laravel using Response::download

Body:
I have a source URL that displays the pdf document in the browser. It supposes to download automatically.

Sample URL : http://doc.local.com/storage/temporary/2020-02-19/c3e175b4706492be8c0d90e497c86ea7/test.pdf

Exactly I want to implement how amazon s3 temporary url works (they added all the headers in the url)

response-content-disposition=attachment

Please don't suggest me to use the following code, as front-end expect an URL

header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);

Body:
I have a little hack to achieve the task -

Let's assume you URL is something -

https://somedomain.com/somepath/file.pdf

Create an api as below -

https://somedomain.com/somepath/file.pdf?signature=signature&ttl=some-ttl

signature to validate the request it is authentic or not

ttl is to validate if the URL is still active for that signature

Then after validating the API request, you can return the download response as below -

public function getDownload()
{
    //PDF file is stored under project/public/download/info.pdf
    $file= public_path(). "/download/info.pdf";

    $headers = array(
              'Content-Type: application/pdf',
            );

    return Response::download($file, 'filename.pdf', $headers);
}

ref - Download files in laravel using Response::download


问:
Identical values generated from random samples from a uniform distribution in dplyr
This is a follow up to previous question. My question was not fully formulated and therefore not fully answered in my last post. Forgive me, I'm new to using stack overflow.

My professor has assigned a problem set, and we are required to use dplyr and other tidyverse packages. I'm very aware that most (if not all) the tasks that I'm trying to execute are possible in base r, but that's not in agreement with my instructions.

First we are asked to generate a tibble of 1000 random samples from a uniform distribution:

```<code>2a.  Create a new tibble called uniformDf containing a variable called unifSamples that contains 10000 random samples from a uniform distribution.  You should use the runif() function to create the uniform samples. {r 2a}

uniformDf <- tibble(unifSamples = runif(1000))
</code>```

This goes well.

Then we are asked to loop thru this tibble 1000 times, each time choosing 20 random samples and computing the mean and saving it to a tibble:

```<code>2c.  Now let's loop through 1000 times, sampling 20 values from a uniform distribution and computing the mean of the sample, saving this mean to a variable called sampMean within a tibble called uniformSampleMeans. {r 2c}

unif_sample_size = 20 # sample size
n_samples = 1000 # number of samples

# set up q data frame to contain the results
uniformSampleMeans <- tibble(sampMean=rep(NA,n_samples))

# loop through all samples.  for each one, take a new random sample,
# compute the mean, and store it in the data frame

for (i in 1:n_samples){
  uniformSampleMeans$sampMean[i] <- uniformDf %>%
  sample_n(unif_sample_size) %>%
  summarize(sampMean = mean(sampMean))
}
</code>```

This all runs, well, I believe until I look at my uniformSampleMeans tibble. Which looks like this:

```<code>1   0.471271611726843
2   0.471271611726843
3   0.471271611726843
4   0.471271611726843
5   0.471271611726843
6   0.471271611726843
7   0.471271611726843
...
1000    0.471271611726843
</code>```

All the values are identical! Does anyone have any insight as to why my output is like this? I'd be less concerned if they varied by +/- 0.000x values seeing as how this is from a distribution that ranges from 0 to 1 but the values are all identical even out to the 15th decimal place! Any help is much appreciated!

答:
The following selects random unif_sample_size rows and gives it's mean

```<code>library(dplyr)
uniformDf %>% sample_n(unif_sample_size) %>% pull(unifSamples) %>% mean
#[1] 0.5563638
</code>```

If you want to do this n times use replicate and repeat it n times

```<code>n <- 10
replicate(n, uniformDf %>%
               sample_n(unif_sample_size) %>%
               pull(unifSamples) %>% mean)
#[1] 0.5070833 0.5259541 0.5617969 0.4695862 0.5030998 0.5745950 0.4688153 0.4914363 0.4449804 0.5202964
</code>```

Body:
This is a follow up to previous question. My question was not fully formulated and therefore not fully answered in my last post. Forgive me, I'm new to using stack overflow.

My professor has assigned a problem set, and we are required to use dplyr and other tidyverse packages. I'm very aware that most (if not all) the tasks that I'm trying to execute are possible in base r, but that's not in agreement with my instructions.

First we are asked to generate a tibble of 1000 random samples from a uniform distribution:

2a.  Create a new tibble called uniformDf containing a variable called unifSamples that contains 10000 random samples from a uniform distribution.  You should use the runif() function to create the uniform samples. {r 2a}

uniformDf <- tibble(unifSamples = runif(1000))

This goes well.

Then we are asked to loop thru this tibble 1000 times, each time choosing 20 random samples and computing the mean and saving it to a tibble:

2c.  Now let's loop through 1000 times, sampling 20 values from a uniform distribution and computing the mean of the sample, saving this mean to a variable called sampMean within a tibble called uniformSampleMeans. {r 2c}

unif_sample_size = 20 # sample size
n_samples = 1000 # number of samples

# set up q data frame to contain the results
uniformSampleMeans <- tibble(sampMean=rep(NA,n_samples))

# loop through all samples.  for each one, take a new random sample,
# compute the mean, and store it in the data frame

for (i in 1:n_samples){
  uniformSampleMeans$sampMean[i] <- uniformDf %>%
  sample_n(unif_sample_size) %>%
  summarize(sampMean = mean(sampMean))
}

This all runs, well, I believe until I look at my uniformSampleMeans tibble. Which looks like this:

1   0.471271611726843
2   0.471271611726843
3   0.471271611726843
4   0.471271611726843
5   0.471271611726843
6   0.471271611726843
7   0.471271611726843
...
1000    0.471271611726843

All the values are identical! Does anyone have any insight as to why my output is like this? I'd be less concerned if they varied by +/- 0.000x values seeing as how this is from a distribution that ranges from 0 to 1 but the values are all identical even out to the 15th decimal place! Any help is much appreciated!

Body:
The following selects random unif_sample_size rows and gives it's mean

library(dplyr)
uniformDf %>% sample_n(unif_sample_size) %>% pull(unifSamples) %>% mean
#[1] 0.5563638

If you want to do this n times use replicate and repeat it n times

n <- 10
replicate(n, uniformDf %>%
               sample_n(unif_sample_size) %>%
               pull(unifSamples) %>% mean)
#[1] 0.5070833 0.5259541 0.5617969 0.4695862 0.5030998 0.5745950 0.4688153 0.4914363 0.4449804 0.5202964


问:
Insert 1 million records using Laravel DB Seed
I'm using faker to get dummy data and trying to add 1million records. Somehow I only can reach around 100000 rows only, Following is my code

```<code>$no_of_rows = 1000000;

for( $i=1; $i <= $no_of_rows; $i++ ){
        $user_data[] = [
            'status' => 'ACTIVE',
            'username' => $faker->userName,
            'email' => $faker->email,
            'password' => $password,
            'firstname' => $faker->firstName,
            'surname' => $faker->lastName,
            'mobilenumber' => $faker->phoneNumber,
            'confirmed' => (int)$faker->boolean(50),
            'gender' => $faker->boolean(50) ? 'MALE' : 'FEMALE',
            'dob' => $faker->date(),
            'address_line_1' => $faker->address,
            'address_line_2' => '',
            'post_code' => $faker->postcode,
        ];

}

User::insert($user_data);
</code>```

I'm getting following error message

```<code>PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted
</code>```

I already set ini_set('memory_limit', '1024M');

Any useful thoughts or solutions?

答:
Hello: Here is very good and very Fast Insert data solution</p>

```<code>$no_of_data = 1000000;
$test_data = array();
for ($i = 0; $i < $no_of_data; $i++){
  $test_data[$i]['number'] = "1234567890";
  $test_data[$i]['message'] = "Test Data";
  $test_data[$i]['status'] = "Delivered";
}
$chunk_data = array_chunk($test_data, 1000);
if (isset($chunk_data) && !empty($chunk_data)) {
  foreach ($chunk_data as $chunk_data_val) {
     DB::table('messages')->insert($chunk_data_val);
  }
}
</code>```

Body:
I'm using faker to get dummy data and trying to add 1million records. Somehow I only can reach around 100000 rows only, Following is my code

$no_of_rows = 1000000;

for( $i=1; $i <= $no_of_rows; $i++ ){
        $user_data[] = [
            'status' => 'ACTIVE',
            'username' => $faker->userName,
            'email' => $faker->email,
            'password' => $password,
            'firstname' => $faker->firstName,
            'surname' => $faker->lastName,
            'mobilenumber' => $faker->phoneNumber,
            'confirmed' => (int)$faker->boolean(50),
            'gender' => $faker->boolean(50) ? 'MALE' : 'FEMALE',
            'dob' => $faker->date(),
            'address_line_1' => $faker->address,
            'address_line_2' => '',
            'post_code' => $faker->postcode,
        ];

}

User::insert($user_data);

I'm getting following error message

PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted

I already set ini_set('memory_limit', '1024M');

Any useful thoughts or solutions?

Body:
Hello: Here is very good and very Fast Insert data solution

$no_of_data = 1000000;
$test_data = array();
for ($i = 0; $i < $no_of_data; $i++){
  $test_data[$i]['number'] = "1234567890";
  $test_data[$i]['message'] = "Test Data";
  $test_data[$i]['status'] = "Delivered";
}
$chunk_data = array_chunk($test_data, 1000);
if (isset($chunk_data) && !empty($chunk_data)) {
  foreach ($chunk_data as $chunk_data_val) {
     DB::table('messages')->insert($chunk_data_val);
  }
}


问:
Find mean of list in F#
I'm trying to find the average of a list

Here's what I have so far

```<code>let rec avg aList =
    match aList with
    | head::tail -> head+avg(tail)
    | [] -> 0

</code>```

This obtains the sum. I've tried head+avg(tail)/aList.Length, but it gives me an incorrect result as I don't know exactly what that's doing

Any help would be appreciated

答:
For an average, you'd want two things, the sum and the number of items. Using List.length would mean traversing the list again.
We can do those two things at the same time - by using a tuple.

This operation is known as folding (or sometimes aggregation). We apply the folding function, gathering our state as we traverse the list without mutating anything.

```<code>let avg aList =
    let rec accumulate (sum, count) list =
        match list with
        | head::tail -> accumulate (sum + head, count + 1) tail
        | [] -> (sum, count)
    let sum, count = accumulate (0, 0) aList
    let average = sum / count
    average
</code>```

You can generalize this using fold.

```<code>let avg aList =
    let sum, count =
        List.fold (fun (sum, count) current -> (sum + current, count + 1)) (0,0) aList
    let average = sum / count
    average
</code>```

The generic math version:

```<code>let inline avg (list: 'a list) =
    let rec accumulate (sum, count) list =
           match list with
           | head::tail -> accumulate (Checked.(+) sum head, count + 1) tail
           | [] -> (sum, count)
    let sum, count = accumulate (LanguagePrimitives.GenericZero<'a>, 0) list
    let average = LanguagePrimitives.DivideByInt sum count
    average
</code>```

Title: Find mean of list in F#

Body:
I'm trying to find the average of a list

Here's what I have so far

let rec avg aList =
    match aList with
    | head::tail -> head+avg(tail)
    | [] -> 0

This obtains the sum. I've tried head+avg(tail)/aList.Length, but it gives me an incorrect result as I don't know exactly what that's doing

Any help would be appreciated

Body:
For an average, you'd want two things, the sum and the number of items. Using List.length would mean traversing the list again.
We can do those two things at the same time - by using a tuple.

This operation is known as folding (or sometimes aggregation). We apply the folding function, gathering our state as we traverse the list without mutating anything.

let avg aList =
    let rec accumulate (sum, count) list =
        match list with
        | head::tail -> accumulate (sum + head, count + 1) tail
        | [] -> (sum, count)
    let sum, count = accumulate (0, 0) aList
    let average = sum / count
    average

You can generalize this using fold.

let avg aList =
    let sum, count =
        List.fold (fun (sum, count) current -> (sum + current, count + 1)) (0,0) aList
    let average = sum / count
    average

The generic math version:

let inline avg (list: 'a list) =
    let rec accumulate (sum, count) list =
           match list with
           | head::tail -> accumulate (Checked.(+) sum head, count + 1) tail
           | [] -> (sum, count)
    let sum, count = accumulate (LanguagePrimitives.GenericZero<'a>, 0) list
    let average = LanguagePrimitives.DivideByInt sum count
    average


问:
ViewPager2/Tabs problem with ViewModel state
I am following the MVVM pattern - meaning I have a ViewModel for each Fragment.

I added two tabs by using ViewPager2.

My adapter looks like this:

```<code>@Override
public Fragment createFragment(int position) {
    switch (position) {
        case 0:
            return new MergedItemsFragment();
        case 1:
            return new ValidatedMergedItemsFragment();
    }
    return new MergedItemsFragment();
}
</code>```

The tabs are working. However, I noticed that the ViewModel of my MergedItemsFragment is behaving weirdly.
Before I added tabs I navigated to the Fragment like this:

```<code>NavHostFragment.findNavController(this).navigate(R.id.action_roomFragment_to_itemsFragment);
</code>```

When I left that fragment with NavHostFragment.findNavController(this).popBackStack() and later on returned to that fragment I would get a new empty ViewModel. This was intended.

With the new approach I am navigating with return new MergedItemsFragment(). When I leave that fragment and later on return I am getting a ViewModel that contains the old data. That is an issue because the old data is not relevant anymore because the User selected different data in another fragment.

Update #1

I realized that he actually keeps all the old Fragments in memory because the same print statements gets called multiple times. The times it is called increases with the amount of times I leave and return to that screen. So if I leave and return 10 times and rotate my device he will actually execute one line 10 times. Any guesses how to implement Tabs/ViewPagers with Navigation Components in a manner that works with ViewModels?

Update #2

I set my ViewModels like this:

viewModel = new ViewModelProvider(this, providerFactory).get(MergedItemViewModel.class)
```

<p>I get the same results with:</p>

<pre class="lang-java prettyprint-override"><code>viewModel = ViewModelProviders.of(this).get(MergedItemViewModel.class);
</code>```

I bind the ViewModel in the Fragment itself. Therefore, this is the Fragment.

答:
As per your comment, you are using Fragment and inside that Fragment there is your viewpager.
So while creating your Adapter for ViewPager you need to pass childFragmentManager instead of getActivity()

Below is a sample Adapter for your viewPager that you can use

```<code>class NewViewPagerAdapter(fm: FragmentManager, behavior: Int) : FragmentStatePagerAdapter(fm, behavior) {
    private val mFragmentList: MutableList<Fragment> = ArrayList()
    private val mFragmentTitleList: MutableList<String> = ArrayList()

    override fun getItem(position: Int): Fragment {
        return mFragmentList[position]
    }

    override fun getCount(): Int {
        return mFragmentList.size
    }

    fun addFragment(fragment: Fragment, title: String) {
        mFragmentList.add(fragment)
        mFragmentTitleList.add(title)
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return mFragmentTitleList[position]
    }
}
</code>```

and while creating your adapter call it like

```<code>   val adapter = NewViewPagerAdapter(
        childFragmentManager,
        FragmentPagerAdapter.POSITION_UNCHANGED
    )
</code>```

as if you see the documentation for FragmentStatePagerAdapter it states that you should pass (FragmentManager, int) inside your adapter's constructor

I hope this will solve your issue as I was facing the same issue one day.

Happy coding.

Body:
I am following the MVVM pattern - meaning I have a ViewModel for each Fragment.

I added two tabs by using ViewPager2.

My adapter looks like this:

@Override
public Fragment createFragment(int position) {
    switch (position) {
        case 0:
            return new MergedItemsFragment();
        case 1:
            return new ValidatedMergedItemsFragment();
    }
    return new MergedItemsFragment();
}

The tabs are working. However, I noticed that the ViewModel of my MergedItemsFragment is behaving weirdly.
Before I added tabs I navigated to the Fragment like this:

NavHostFragment.findNavController(this).navigate(R.id.action_roomFragment_to_itemsFragment);

When I left that fragment with NavHostFragment.findNavController(this).popBackStack() and later on returned to that fragment I would get a new empty ViewModel. This was intended.

With the new approach I am navigating with return new MergedItemsFragment(). When I leave that fragment and later on return I am getting a ViewModel that contains the old data. That is an issue because the old data is not relevant anymore because the User selected different data in another fragment.

Update #1

I realized that he actually keeps all the old Fragments in memory because the same print statements gets called multiple times. The times it is called increases with the amount of times I leave and return to that screen. So if I leave and return 10 times and rotate my device he will actually execute one line 10 times. Any guesses how to implement Tabs/ViewPagers with Navigation Components in a manner that works with ViewModels?

Update #2

I set my ViewModels like this:

viewModel = new ViewModelProvider(this, providerFactory).get(MergedItemViewModel.class)

I get the same results with:

viewModel = ViewModelProviders.of(this).get(MergedItemViewModel.class);

I bind the ViewModel in the Fragment itself. Therefore, this is the Fragment.

Body:
As per your comment, you are using Fragment and inside that Fragment there is your viewpager.
So while creating your Adapter for ViewPager you need to pass childFragmentManager instead of getActivity()

Below is a sample Adapter for your viewPager that you can use

class NewViewPagerAdapter(fm: FragmentManager, behavior: Int) : FragmentStatePagerAdapter(fm, behavior) {
    private val mFragmentList: MutableList<Fragment> = ArrayList()
    private val mFragmentTitleList: MutableList<String> = ArrayList()

    override fun getItem(position: Int): Fragment {
        return mFragmentList[position]
    }

    override fun getCount(): Int {
        return mFragmentList.size
    }

    fun addFragment(fragment: Fragment, title: String) {
        mFragmentList.add(fragment)
        mFragmentTitleList.add(title)
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return mFragmentTitleList[position]
    }
}

and while creating your adapter call it like

   val adapter = NewViewPagerAdapter(
        childFragmentManager,
        FragmentPagerAdapter.POSITION_UNCHANGED
    )

as if you see the documentation for FragmentStatePagerAdapter it states that you should pass (FragmentManager, int) inside your adapter's constructor

I hope this will solve your issue as I was facing the same issue one day.

Happy coding.


问:
Authorize.net payment gateway Charge a Credit Card API for iOS swift
hello everyone as i am using payment gateway charge credit api but i am getting error while passing json object to api.and here my original JSON object which pass to charge credit api.

```<code>{
    "createTransactionRequest": {
        "merchantAuthentication": {
            "name": "XXXXXX",
            "transactionKey": "XXXXXXXX"
        },
        "refId": "123456",
        "transactionRequest": {
            "transactionType": "authCaptureTransaction",
            "amount": "5",
            "payment": {
                "creditCard": {
                    "cardNumber": "5424000000000015",
                    "expirationDate": "2020-12",
                    "cardCode": "999"
                }
            }
        }
    }
}
</code>```

this is original  json request
but in iOS while making JSON we get below JSON object and sequence of JSON object are change that's why we getting error from api.

```<code>{
    "createTransactionRequest": {
        "merchantAuthentication": {
            "name": "XXXXXX",
            "transactionKey": "XXXXXXX"
        },
        "refId": "123456",
        "transactionRequest": {
            "amount": "5",
            "payment": {
                "creditCard": {
                    "cardCode": "999",
                    "cardNumber": "5424000000000015",
                    "expirationDate": "2020-12"
                }
            },
            "transactionType": "authCaptureTransaction"
        }
    }
}
</code>```

after passing this JSON object to API, we will get bellow error

```<code>{
    "messages": {
        "resultCode": "Error",
        "message": [
            {
                "code": "E00003",
                "text": "The element 'transactionRequest' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' has invalid child element 'amount' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'. List of possible elements expected: 'transactionType' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'."
            }
        ]
    }
}
</code>```

here is my code for creating JSON object in app

```<code>var dict = Dictionary<String, Any>()
 dict=[
  "merchantAuthentication": [
    "name": "xxxxxxx",
    "transactionKey": "xxxxxxx"
  ],
  "refId": "5656",
  "transactionRequest": [
    "transactionType": "authCaptureTransaction",
    "amount": "55",
    "payment": [
      "creditCard": [
        "cardNumber": "4111111111111111",
        "expirationDate": "2020-12",
        "cardCode": "999"
      ]
    ]
  ]
]
</code>```

after print this JSON sequence are changed

答:
Have you read the documentation? It's very clear from the linked page that what you're running into is a side effect of their translation of JSON elements to XML elements in the backend, specifically around the ordering of parameters in your JSON request:

A Note Regarding JSON Support

The Authorize.Net API, which is not
based on REST, offers JSON support through a translation of JSON
elements to XML elements. While JSON does not typically require a set
order to the elements in an object, XML requires strict ordering.
Developers using the Authorize.Net API should force the ordering of
elements to match this API Reference.

Their examples below this block also show that their transactionType parameters appear as the first attribute in the transactionRequest object. Tl;dr - move your transactionType parameter up in your transactionRequest object:

```<code>{
    "createTransactionRequest": {
        "merchantAuthentication": {
            "name": "XXXXXX",
            "transactionKey": "XXXXXXX"
        },
        "refId": "123456",
        "transactionRequest": {
            "transactionType": "authCaptureTransaction",
            "amount": "5",
            "payment": {
                "creditCard": {
                    "cardCode": "999",
                    "cardNumber": "5424000000000015",
                    "expirationDate": "2020-12"
                }
            }
        }
    }
}
</code>```

Body:
hello everyone as i am using payment gateway charge credit api but i am getting error while passing json object to api.and here my original JSON object which pass to charge credit api.

{
    "createTransactionRequest": {
        "merchantAuthentication": {
            "name": "XXXXXX",
            "transactionKey": "XXXXXXXX"
        },
        "refId": "123456",
        "transactionRequest": {
            "transactionType": "authCaptureTransaction",
            "amount": "5",
            "payment": {
                "creditCard": {
                    "cardNumber": "5424000000000015",
                    "expirationDate": "2020-12",
                    "cardCode": "999"
                }
            }
        }
    }
}

this is original  json request
but in iOS while making JSON we get below JSON object and sequence of JSON object are change that's why we getting error from api.

{
    "createTransactionRequest": {
        "merchantAuthentication": {
            "name": "XXXXXX",
            "transactionKey": "XXXXXXX"
        },
        "refId": "123456",
        "transactionRequest": {
            "amount": "5",
            "payment": {
                "creditCard": {
                    "cardCode": "999",
                    "cardNumber": "5424000000000015",
                    "expirationDate": "2020-12"
                }
            },
            "transactionType": "authCaptureTransaction"
        }
    }
}

after passing this JSON object to API, we will get bellow error

{
    "messages": {
        "resultCode": "Error",
        "message": [
            {
                "code": "E00003",
                "text": "The element 'transactionRequest' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' has invalid child element 'amount' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'. List of possible elements expected: 'transactionType' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'."
            }
        ]
    }
}

here is my code for creating JSON object in app

var dict = Dictionary<String, Any>()
 dict=[
  "merchantAuthentication": [
    "name": "xxxxxxx",
    "transactionKey": "xxxxxxx"
  ],
  "refId": "5656",
  "transactionRequest": [
    "transactionType": "authCaptureTransaction",
    "amount": "55",
    "payment": [
      "creditCard": [
        "cardNumber": "4111111111111111",
        "expirationDate": "2020-12",
        "cardCode": "999"
      ]
    ]
  ]
]

after print this JSON sequence are changed

Body:
Have you read the documentation? It's very clear from the linked page that what you're running into is a side effect of their translation of JSON elements to XML elements in the backend, specifically around the ordering of parameters in your JSON request:

A Note Regarding JSON Support

The Authorize.Net API, which is not
based on REST, offers JSON support through a translation of JSON
elements to XML elements. While JSON does not typically require a set
order to the elements in an object, XML requires strict ordering.
Developers using the Authorize.Net API should force the ordering of
elements to match this API Reference.

Their examples below this block also show that their transactionType parameters appear as the first attribute in the transactionRequest object. Tl;dr - move your transactionType parameter up in your transactionRequest object:

{
    "createTransactionRequest": {
        "merchantAuthentication": {
            "name": "XXXXXX",
            "transactionKey": "XXXXXXX"
        },
        "refId": "123456",
        "transactionRequest": {
            "transactionType": "authCaptureTransaction",
            "amount": "5",
            "payment": {
                "creditCard": {
                    "cardCode": "999",
                    "cardNumber": "5424000000000015",
                    "expirationDate": "2020-12"
                }
            }
        }
    }
}


问:
Python regex re.finditer weird behavior with match.end()
I am trying to find the positions of patterns in a file, and I am using Python regex.  When I run the below code, several start positions are printed but only one end position, the one corresponding to the latest start position, is printed.  The bottom print statement is also only printed once.  Why is there not a match.end() value for every match.start() value? File is a .obj file.

```<code>import re
import binascii

def findByte(b,file):
    f = open(file, "rb").read()
    f = binascii.hexlify(f)
    regex = b + "(?=(?:[\\da-fA-F]{2})*$)"

    for match in (re.finditer(regex, f)):

        s = match.start()
        print("S" + str(s))

        e = match.end()
        print("E" + str(e))

        g = match.group()
        print(g)

        print ('String match "%s" at %d:%d' % (g, s, e))

findByte("ca","demo.obj")
</code>```

When I run it, the below answers are printed.

```<code>S0
S64
S184
S252
E254
ca
String match "ca" at 252:254
</code>```

If I instead write

```<code>def findByte(b,file):
    f = open(file, "rb").read()
    f = binascii.hexlify(f)
    regex = b + "(?=(?:[\\da-fA-F]{2})*$)"

    m = re.findall(regex,f)
    print(m)

findByte("ca","demo.obj")
</code>```

The printed value is

```<code>['ca', 'ca', 'ca', 'ca']
</code>```

答:
Checking the actual code you pasted, it's clear you've committed the cardinal Python sin of mixing tabs and spaces, and it's biting you (try selecting the leading whitespace in your own code on this page; you'll see some of it is selected as blocks of four spaces at a time, while other parts have single space granularity). Your editor is showing you tabs as being equivalent to four spaces, but in the code you pasted, you have purely tab based indentation up through print("S" + str(s)), then four spaces followed by a tab as the indentation for subsequent lines.

Most such mixed indentation stuff is rejected by Python 3, but Python 2 is more flexible (it gives you the rope to hang yourself), which may be what is happening here (Python 2 is end of life as of the beginning of this year, so if you're writing new code, I'd suggest switching for this and many other reasons). Your code looks like it's all in the for loop, but most of it isn't.

Replace all your tabs with four space indents, and reconfigure your editor to always expand tabs to spaces in the future, so you aren't bit by this in the future; Python style is consistent four space indents with no tabs for a reason.

Body:
I am trying to find the positions of patterns in a file, and I am using Python regex.  When I run the below code, several start positions are printed but only one end position, the one corresponding to the latest start position, is printed.  The bottom print statement is also only printed once.  Why is there not a match.end() value for every match.start() value? File is a .obj file.

import re
import binascii

def findByte(b,file):
    f = open(file, "rb").read()
    f = binascii.hexlify(f)
    regex = b + "(?=(?:[\\da-fA-F]{2})*$)"

    for match in (re.finditer(regex, f)):

        s = match.start()
        print("S" + str(s))

        e = match.end()
        print("E" + str(e))

        g = match.group()
        print(g)

        print ('String match "%s" at %d:%d' % (g, s, e))

findByte("ca","demo.obj")

When I run it, the below answers are printed.

S0
S64
S184
S252
E254
ca
String match "ca" at 252:254

If I instead write

def findByte(b,file):
    f = open(file, "rb").read()
    f = binascii.hexlify(f)
    regex = b + "(?=(?:[\\da-fA-F]{2})*$)"

    m = re.findall(regex,f)
    print(m)

findByte("ca","demo.obj")

The printed value is

['ca', 'ca', 'ca', 'ca']


问:
Using React to create a form, how could I get my err message to display on Submit (when the submit button is clicked)?
I am using React to create a form with two input text and would like to display an error message every time the user enters a non-numerical value as the age and clicks the submit button. The form apparently is doing most of what I want but it is not displaying the error message.

NB: I would love not to use the alert() syntax here if possible.

Thanks for your help.

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      age: null,
      errormessage: ''
    };
  }

 errorHandler = () => {
  let err = '';
  if (nam === "age") {
    if (val !="" && !Number(val)) {
      err = Your age must be a number;
    }
  }
  this.setState({errormessage: err});
 }

  myChangeHandler = (event) => {
    let nam = event.target.name;
    let val = event.target.value;
    this.setState({[nam]: val});
  }

  render() {
    return (
      <form onSubmit={this.errorHandler}>

Hello {this.state.username} {this.state.age}

Enter your name:

      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />

Enter your age:

      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />

      <input
        type='submit'
      />
      {this.state.errormessage}
      </form>
    );
  }
}
ReactDOM.render(<MyForm />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div></code>```

答:
In your errorHandler you have two undefined variables, nam and val, (nam === "age") and (val !="" && !Number(val)). The nam and val variables only work inside the local scope of your myChangeHandler method. I would separate your onChange handlers into two as shown below to set the different inputs. Finally, you could use Number() on the state age to convert a string to a number, then you use the if statement to use isNaN() to see if the age is a number or not. When you try to use Number() on a string value with letters it will return Not a Number so you can check that using isNaN(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

Here is the code in a sandbox: https://codesandbox.io/s/stoic-brattain-doz7t

```<code>class MyForm extends React.Component {
  constructor(props) {
   super(props);
   this.state = {
     username: "",
     age: null,
     errormessage: ""
   };
  }

  errorHandler = e => {
    e.preventDefault();
    let err = "";
    let newAge = Number(this.state.age);

    if (isNaN(newAge)) {
      err = <strong>Your age must be a number</strong>;
    }
    this.setState({ errormessage: err });
  };

  handleUserName = event => {
    this.setState({
      username: event.target.value
    });
  };

  handleMyAge = event => {
    this.setState({
      age: event.target.value
    });
  };

  render() {
    return (
      <form onSubmit={this.errorHandler}>
        <h1>
          Hello {this.state.username} {this.state.age}
        </h1>
    <p>Enter your name:</p>
    <input
      type="text"
      name="username"
      defaultValue=""
      onChange={this.handleUserName}
    />
    <p>Enter your age:</p>
    <input
      type="text"
      name="age"
      defaultValue=""
      onChange={this.handleMyAge}
    />
    <br />
    <input type="submit" />
    {this.state.errormessage}
  </form>
);
  }
}
ReactDOM.render(<MyForm />, document.getElementById("root"));
</code>```

Body:
In your errorHandler you have two undefined variables, nam and val, (nam === "age") and (val !="" && !Number(val)). The nam and val variables only work inside the local scope of your myChangeHandler method. I would separate your onChange handlers into two as shown below to set the different inputs. Finally, you could use Number() on the state age to convert a string to a number, then you use the if statement to use isNaN() to see if the age is a number or not. When you try to use Number() on a string value with letters it will return Not a Number so you can check that using isNaN(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

Here is the code in a sandbox: https://codesandbox.io/s/stoic-brattain-doz7t

class MyForm extends React.Component {
  constructor(props) {
   super(props);
   this.state = {
     username: "",
     age: null,
     errormessage: ""
   };
  }

  errorHandler = e => {
    e.preventDefault();
    let err = "";
    let newAge = Number(this.state.age);

    if (isNaN(newAge)) {
      err = <strong>Your age must be a number</strong>;
    }
    this.setState({ errormessage: err });
  };

  handleUserName = event => {
    this.setState({
      username: event.target.value
    });
  };

  handleMyAge = event => {
    this.setState({
      age: event.target.value
    });
  };

  render() {
    return (
      <form onSubmit={this.errorHandler}>
        <h1>
          Hello {this.state.username} {this.state.age}
        </h1>
    <p>Enter your name:</p>
    <input
      type="text"
      name="username"
      defaultValue=""
      onChange={this.handleUserName}
    />
    <p>Enter your age:</p>
    <input
      type="text"
      name="age"
      defaultValue=""
      onChange={this.handleMyAge}
    />
    <br />
    <input type="submit" />
    {this.state.errormessage}
  </form>
);
  }
}
ReactDOM.render(<MyForm />, document.getElementById("root"));


问:
Matlab array of audioplayers
I am creating a matlab script inside labview. Inside that script I try to create an array of audioplayer objects. However, I got an error, and I can't find a way around it.

This is the script:

```<code>nrOfSounds = 11;
if (exist('p') == 0)
    [snd, freq, bps] = wavread('sounds/1.wav');
    p = audioplayer(snd, freq);
    for t=2:nrOfSounds
        [snd,freq,bps] = wavread(strcat('sounds/',num2str(t),'.wav'));
        s = audioplayer(snd,freq);
        p(end+1) = s;
    end
end
</code>```

And this is the error:

```<code>Audioplayer objects cannot be concatenated.
</code>```

It seems that I can't create an array of audioplayer objects, but I can't really find a way around this since I'm not really experienced with matlab. Can anyone help me with this?

答:
You have to use cells, not arrays.</p>

```<code>nrOfSounds = 11;
if (exist('p') == 0)
    [snd, freq, bps] = wavread('sounds/1.wav');
    p{1} = audioplayer(snd, freq);
    for t=2:nrOfSounds
        [snd,freq,bps] = wavread(strcat('sounds/',num2str(t),'.wav'));
        s = audioplayer(snd,freq);
        p{end+1} = s;
    end
end
</code>```

Title: Matlab array of audioplayers

Body:
I am creating a matlab script inside labview. Inside that script I try to create an array of audioplayer objects. However, I got an error, and I can't find a way around it.

This is the script:

nrOfSounds = 11;
if (exist('p') == 0)
    [snd, freq, bps] = wavread('sounds/1.wav');
    p = audioplayer(snd, freq);
    for t=2:nrOfSounds
        [snd,freq,bps] = wavread(strcat('sounds/',num2str(t),'.wav'));
        s = audioplayer(snd,freq);
        p(end+1) = s;
    end
end

And this is the error:

Audioplayer objects cannot be concatenated.

It seems that I can't create an array of audioplayer objects, but I can't really find a way around this since I'm not really experienced with matlab. Can anyone help me with this?

Body:
You have to use cells, not arrays.

nrOfSounds = 11;
if (exist('p') == 0)
    [snd, freq, bps] = wavread('sounds/1.wav');
    p{1} = audioplayer(snd, freq);
    for t=2:nrOfSounds
        [snd,freq,bps] = wavread(strcat('sounds/',num2str(t),'.wav'));
        s = audioplayer(snd,freq);
        p{end+1} = s;
    end
end


问:
Bad lighting using Phong Method
I'm trying to make a cube, which is irregularly triangulated, but virtually coplanar, shade correctly.

Here is the current result I have:

With wireframe:

Normals calculated in my program:

Normals calculated by meshlabjs.net:

The lighting works properly when using regular size triangles for the cube. As you can see, I'm duplicating vertices and using angle weighting.

lighting.frag

```<code>vec4 scene_ambient = vec4(1, 1, 1, 1.0);

struct material
{
  vec4 ambient;
  vec4 diffuse;
  vec4 specular;
  float shininess;
};

material frontMaterial = material(
  vec4(0.25, 0.25, 0.25, 1.0),
  vec4(0.4, 0.4, 0.4, 1.0),
  vec4(0.774597, 0.774597, 0.774597, 1.0),
  76
);

struct lightSource
{
  vec4 position;
  vec4 diffuse;
  vec4 specular;
  float constantAttenuation, linearAttenuation, quadraticAttenuation;
  float spotCutoff, spotExponent;
  vec3 spotDirection;
};

lightSource light0 = lightSource(
  vec4(0.0,  0.0, 0.0, 1.0),
  vec4(100.0,  100.0,  100.0, 100.0),
  vec4(100.0,  100.0,  100.0, 100.0),
  0.1, 1, 0.01,
  180.0, 0.0,
  vec3(0.0, 0.0, 0.0)
);

vec4 light(lightSource ls, vec3 norm, vec3 deviation, vec3 position)
{
  vec3 viewDirection = normalize(vec3(1.0 * vec4(0, 0, 0, 1.0) - vec4(position, 1)));

  vec3 lightDirection;
  float attenuation;

  //ls.position.xyz = cameraPos;
  ls.position.z += 50;

  if (0.0 == ls.position.w) // directional light?
  {
    attenuation = 1.0; // no attenuation
    lightDirection = normalize(vec3(ls.position));
  }
  else // point light or spotlight (or other kind of light)
  {
      vec3 positionToLightSource = vec3(ls.position - vec4(position, 1.0));
    float distance = length(positionToLightSource);
    lightDirection = normalize(positionToLightSource);
    attenuation = 1.0 / (ls.constantAttenuation
      + ls.linearAttenuation * distance
      + ls.quadraticAttenuation * distance * distance);

    if (ls.spotCutoff <= 90.0) // spotlight?
    {
      float clampedCosine = max(0.0, dot(-lightDirection, ls.spotDirection));
      if (clampedCosine < cos(radians(ls.spotCutoff))) // outside of spotlight cone?
      {
        attenuation = 0.0;
        }
      else
        {
        attenuation = attenuation * pow(clampedCosine, ls.spotExponent);
        }
    }
  }

  vec3 ambientLighting = vec3(scene_ambient) * vec3(frontMaterial.ambient);

  vec3 diffuseReflection = attenuation
    * vec3(ls.diffuse) * vec3(frontMaterial.diffuse)
    * max(0.0, dot(norm, lightDirection));

  vec3 specularReflection;
  if (dot(norm, lightDirection) < 0.0) // light source on the wrong side?
  {
    specularReflection = vec3(0.0, 0.0, 0.0); // no specular reflection
  }
  else // light source on the right side
  {
    specularReflection = attenuation * vec3(ls.specular) * vec3(frontMaterial.specular)
         * pow(max(0.0, dot(reflect(lightDirection, norm), viewDirection)), frontMaterial.shininess);
  }

  return vec4(ambientLighting + diffuseReflection + specularReflection, 1.0);
}

vec4 generateGlobalLighting(vec3 norm, vec3 position)
{
  return light(light0, norm, vec3(2,0,0), position);
}
</code>```

mainmesh.frag

```<code>#version 430
in vec3 f_color;
in vec3 f_normal;
in vec3 f_position;

in float f_opacity;

out vec4 fragColor;

vec4 generateGlobalLighting(vec3 norm, vec3 position);

void main()
{
  vec3 norm = normalize(f_normal);
  vec4 l0 = generateGlobalLighting(norm, f_position);

  fragColor = vec4(f_color, f_opacity) * l0;
}
</code>```

Follows the code to generate the verts, normals and faces for the painter.

```<code>m_vertices_buf.resize(m_mesh.num_faces() * 3, 3);
m_normals_buf.resize(m_mesh.num_faces() * 3, 3);
m_faces_buf.resize(m_mesh.num_faces(), 3);

std::map<vertex_descriptor, std::list<Vector3d>> map;
GLDebugging* deb = GLDebugging::getInstance();

auto getAngle = [](Vector3d a, Vector3d b) {
    double angle = 0.0;
    angle = std::atan2(a.cross(b).norm(), a.dot(b));
    return angle;
};

for (const auto& f : m_mesh.faces()) {
    auto f_hh = m_mesh.halfedge(f);
    //auto n = PMP::compute_face_normal(f, m_mesh);

    vertex_descriptor vs[3];
    Vector3d ps[3];

    int i = 0;
    for (const auto& v : m_mesh.vertices_around_face(f_hh)) {
        auto p = m_mesh.point(v);
        ps[i] = Vector3d(p.x(), p.y(), p.z());
        vs[i++] = v;
    }

    auto n = (ps[1] - ps[0]).cross(ps[2] - ps[0]).normalized();

    auto a1 = getAngle((ps[1] - ps[0]).normalized(), (ps[2] - ps[0]).normalized());
    auto a2 = getAngle((ps[2] - ps[1]).normalized(), (ps[0] - ps[1]).normalized());
    auto a3 = getAngle((ps[0] - ps[2]).normalized(), (ps[1] - ps[2]).normalized());

    auto area = PMP::face_area(f, m_mesh);

    map[vs[0]].push_back(n * a1);
    map[vs[1]].push_back(n * a2);
    map[vs[2]].push_back(n * a3);

    auto p = m_mesh.point(vs[0]);
    deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(n.x(), n.y(), n.z()) * 4);

    p = m_mesh.point(vs[1]);
    deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(n.x(), n.y(), n.z()) * 4);

    p = m_mesh.point(vs[2]);
    deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(n.x(), n.y(), n.z()) * 4);
}

int j = 0;
int i = 0;
for (const auto& f : m_mesh.faces()) {
    auto f_hh = m_mesh.halfedge(f);
    for (const auto& v : m_mesh.vertices_around_face(f_hh)) {
        const auto& p = m_mesh.point(v);
        m_vertices_buf.row(i) = RowVector3d(p.x(), p.y(), p.z());

        Vector3d n(0, 0, 0);

        //auto n = PMP::compute_face_normal(f, m_mesh);
        Vector3d norm = Vector3d(n.x(), n.y(), n.z());

        for (auto val : map[v]) {
            norm += val;
        }

        norm.normalize();

        deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(norm.x(), norm.y(), norm.z()) * 3,
            Vector3d(1.0, 0, 0));

        m_normals_buf.row(i++) = RowVector3d(norm.x(), norm.y(), norm.z());
    }

    m_faces_buf.row(j++) = RowVector3i(i - 3, i - 2, i - 1);
}
</code>```

Follows the painter code:

```<code>m_vertexAttrLoc = program.attributeLocation("v_vertex");
m_colorAttrLoc = program.attributeLocation("v_color");
m_normalAttrLoc = program.attributeLocation("v_normal");

m_mvMatrixLoc = program.uniformLocation("v_modelViewMatrix");
m_projMatrixLoc = program.uniformLocation("v_projectionMatrix");
m_normalMatrixLoc = program.uniformLocation("v_normalMatrix");
//m_relativePosLoc = program.uniformLocation("v_relativePos");
m_opacityLoc = program.uniformLocation("v_opacity");
m_colorMaskLoc = program.uniformLocation("v_colorMask");

//bool for unmapping depth color
m_useDepthMap = program.uniformLocation("v_useDepthMap");
program.setUniformValue(m_mvMatrixLoc, modelView);

//uniform used for Color map to regular model switch
program.setUniformValue(m_useDepthMap, (m_showColorMap &&
    (m_showProblemAreas || m_showPrepMap || m_showDepthMap || m_showMockupMap)));

QMatrix3x3 normalMatrix = modelView.normalMatrix();
program.setUniformValue(m_normalMatrixLoc, normalMatrix);
program.setUniformValue(m_projMatrixLoc, projection);

//program.setUniformValue(m_relativePosLoc, m_relativePos);
program.setUniformValue(m_opacityLoc, m_opacity);
program.setUniformValue(m_colorMaskLoc, m_colorMask);

glEnableVertexAttribArray(m_vertexAttrLoc);
m_vertices.bind();
glVertexAttribPointer(m_vertexAttrLoc, 3, GL_DOUBLE, false, 3 * sizeof(GLdouble), NULL);
m_vertices.release();

glEnableVertexAttribArray(m_normalAttrLoc);
m_normals.bind();
glVertexAttribPointer(m_normalAttrLoc, 3, GL_DOUBLE, false, 0, NULL);
m_normals.release();

glEnableVertexAttribArray(m_colorAttrLoc);

if (m_showProblemAreas) {
    m_problemColorMap.bind();
    glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL);
    m_problemColorMap.release();
}
else if (m_showPrepMap) {
    m_prepColorMap.bind();
    glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL);
    m_prepColorMap.release();
}
else if (m_showMockupMap) {
    m_mokupColorMap.bind();
    glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL);
    m_mokupColorMap.release();
}
else {
    //m_colors.bind();
    //glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL);
    //m_colors.release();
}

m_indices.bind();
glDrawElements(GL_TRIANGLES, m_indices.size() / sizeof(int), GL_UNSIGNED_INT, NULL);
m_indices.release();

glDisableVertexAttribArray(m_vertexAttrLoc);
glDisableVertexAttribArray(m_normalAttrLoc);
glDisableVertexAttribArray(m_colorAttrLoc);
</code>```

EDIT: Sorry for not being clear enough. The cube is merely an example. My requirements are that the shading works for any kind of mesh. Those with very sharp edges, and those that are very organic (like humans or animals).

答:
As mentioned in the other answers the problem is your mesh normals.
Computing an average normal, like you are doing currently, is what you would want
to do for a smooth object like a sphere.
cgal has a function for that CGAL::Polygon_mesh_processing::compute_vertex_normal
 For a cube what you want is normals perpendicular to the faces

cgal has a functoin for that too CGAL::Polygon_mesh_processing::compute_face_normal

To debug the normals you can just set fragColor = vec4(norm,1); in mainmesh.frag. Here the cubes on the left have averaged (smooth) normals and on the right have face (flat) normals:

And shaded they look like this:

shading has to work for any kind of mesh (a cube or any organic mesh)

For that you can use something like per_corner_normals whitch:

Implements a simple scheme which computes corner normals as averages
  of normals of faces incident on the corresponding vertex which do not
  deviate by more than a specified dihedral angle (e.g. 20°)

And this is what it looks like with a angle of 1°, 20°, 100°:

Title: Bad lighting using Phong Method

Body:
I'm trying to make a cube, which is irregularly triangulated, but virtually coplanar, shade correctly.

Here is the current result I have:

With wireframe:

Normals calculated in my program:

Normals calculated by meshlabjs.net:

The lighting works properly when using regular size triangles for the cube. As you can see, I'm duplicating vertices and using angle weighting.

lighting.frag

vec4 scene_ambient = vec4(1, 1, 1, 1.0);

struct material
{
  vec4 ambient;
  vec4 diffuse;
  vec4 specular;
  float shininess;
};

material frontMaterial = material(
  vec4(0.25, 0.25, 0.25, 1.0),
  vec4(0.4, 0.4, 0.4, 1.0),
  vec4(0.774597, 0.774597, 0.774597, 1.0),
  76
);

struct lightSource
{
  vec4 position;
  vec4 diffuse;
  vec4 specular;
  float constantAttenuation, linearAttenuation, quadraticAttenuation;
  float spotCutoff, spotExponent;
  vec3 spotDirection;
};

lightSource light0 = lightSource(
  vec4(0.0,  0.0, 0.0, 1.0),
  vec4(100.0,  100.0,  100.0, 100.0),
  vec4(100.0,  100.0,  100.0, 100.0),
  0.1, 1, 0.01,
  180.0, 0.0,
  vec3(0.0, 0.0, 0.0)
);

vec4 light(lightSource ls, vec3 norm, vec3 deviation, vec3 position)
{
  vec3 viewDirection = normalize(vec3(1.0 * vec4(0, 0, 0, 1.0) - vec4(position, 1)));

  vec3 lightDirection;
  float attenuation;

  //ls.position.xyz = cameraPos;
  ls.position.z += 50;

  if (0.0 == ls.position.w) // directional light?
  {
    attenuation = 1.0; // no attenuation
    lightDirection = normalize(vec3(ls.position));
  }
  else // point light or spotlight (or other kind of light)
  {
      vec3 positionToLightSource = vec3(ls.position - vec4(position, 1.0));
    float distance = length(positionToLightSource);
    lightDirection = normalize(positionToLightSource);
    attenuation = 1.0 / (ls.constantAttenuation
      + ls.linearAttenuation * distance
      + ls.quadraticAttenuation * distance * distance);

    if (ls.spotCutoff <= 90.0) // spotlight?
    {
      float clampedCosine = max(0.0, dot(-lightDirection, ls.spotDirection));
      if (clampedCosine < cos(radians(ls.spotCutoff))) // outside of spotlight cone?
      {
        attenuation = 0.0;
        }
      else
        {
        attenuation = attenuation * pow(clampedCosine, ls.spotExponent);
        }
    }
  }

  vec3 ambientLighting = vec3(scene_ambient) * vec3(frontMaterial.ambient);

  vec3 diffuseReflection = attenuation
    * vec3(ls.diffuse) * vec3(frontMaterial.diffuse)
    * max(0.0, dot(norm, lightDirection));

  vec3 specularReflection;
  if (dot(norm, lightDirection) < 0.0) // light source on the wrong side?
  {
    specularReflection = vec3(0.0, 0.0, 0.0); // no specular reflection
  }
  else // light source on the right side
  {
    specularReflection = attenuation * vec3(ls.specular) * vec3(frontMaterial.specular)
         * pow(max(0.0, dot(reflect(lightDirection, norm), viewDirection)), frontMaterial.shininess);
  }

  return vec4(ambientLighting + diffuseReflection + specularReflection, 1.0);
}

vec4 generateGlobalLighting(vec3 norm, vec3 position)
{
  return light(light0, norm, vec3(2,0,0), position);
}

mainmesh.frag

#version 430
in vec3 f_color;
in vec3 f_normal;
in vec3 f_position;

in float f_opacity;

out vec4 fragColor;

vec4 generateGlobalLighting(vec3 norm, vec3 position);

void main()
{
  vec3 norm = normalize(f_normal);
  vec4 l0 = generateGlobalLighting(norm, f_position);

  fragColor = vec4(f_color, f_opacity) * l0;
}

Follows the code to generate the verts, normals and faces for the painter.

m_vertices_buf.resize(m_mesh.num_faces() * 3, 3);
m_normals_buf.resize(m_mesh.num_faces() * 3, 3);
m_faces_buf.resize(m_mesh.num_faces(), 3);

std::map<vertex_descriptor, std::list<Vector3d>> map;
GLDebugging* deb = GLDebugging::getInstance();

auto getAngle = [](Vector3d a, Vector3d b) {
    double angle = 0.0;
    angle = std::atan2(a.cross(b).norm(), a.dot(b));
    return angle;
};

for (const auto& f : m_mesh.faces()) {
    auto f_hh = m_mesh.halfedge(f);
    //auto n = PMP::compute_face_normal(f, m_mesh);

    vertex_descriptor vs[3];
    Vector3d ps[3];

    int i = 0;
    for (const auto& v : m_mesh.vertices_around_face(f_hh)) {
        auto p = m_mesh.point(v);
        ps[i] = Vector3d(p.x(), p.y(), p.z());
        vs[i++] = v;
    }

    auto n = (ps[1] - ps[0]).cross(ps[2] - ps[0]).normalized();

    auto a1 = getAngle((ps[1] - ps[0]).normalized(), (ps[2] - ps[0]).normalized());
    auto a2 = getAngle((ps[2] - ps[1]).normalized(), (ps[0] - ps[1]).normalized());
    auto a3 = getAngle((ps[0] - ps[2]).normalized(), (ps[1] - ps[2]).normalized());

    auto area = PMP::face_area(f, m_mesh);

    map[vs[0]].push_back(n * a1);
    map[vs[1]].push_back(n * a2);
    map[vs[2]].push_back(n * a3);

    auto p = m_mesh.point(vs[0]);
    deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(n.x(), n.y(), n.z()) * 4);

    p = m_mesh.point(vs[1]);
    deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(n.x(), n.y(), n.z()) * 4);

    p = m_mesh.point(vs[2]);
    deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(n.x(), n.y(), n.z()) * 4);
}

int j = 0;
int i = 0;
for (const auto& f : m_mesh.faces()) {
    auto f_hh = m_mesh.halfedge(f);
    for (const auto& v : m_mesh.vertices_around_face(f_hh)) {
        const auto& p = m_mesh.point(v);
        m_vertices_buf.row(i) = RowVector3d(p.x(), p.y(), p.z());

        Vector3d n(0, 0, 0);

        //auto n = PMP::compute_face_normal(f, m_mesh);
        Vector3d norm = Vector3d(n.x(), n.y(), n.z());

        for (auto val : map[v]) {
            norm += val;
        }

        norm.normalize();

        deb->drawLine(Vector3d(p.x(), p.y(), p.z()), Vector3d(p.x(), p.y(), p.z()) + Vector3d(norm.x(), norm.y(), norm.z()) * 3,
            Vector3d(1.0, 0, 0));

        m_normals_buf.row(i++) = RowVector3d(norm.x(), norm.y(), norm.z());
    }

    m_faces_buf.row(j++) = RowVector3i(i - 3, i - 2, i - 1);
}

Follows the painter code:

m_vertexAttrLoc = program.attributeLocation("v_vertex");
m_colorAttrLoc = program.attributeLocation("v_color");
m_normalAttrLoc = program.attributeLocation("v_normal");

m_mvMatrixLoc = program.uniformLocation("v_modelViewMatrix");
m_projMatrixLoc = program.uniformLocation("v_projectionMatrix");
m_normalMatrixLoc = program.uniformLocation("v_normalMatrix");
//m_relativePosLoc = program.uniformLocation("v_relativePos");
m_opacityLoc = program.uniformLocation("v_opacity");
m_colorMaskLoc = program.uniformLocation("v_colorMask");

//bool for unmapping depth color
m_useDepthMap = program.uniformLocation("v_useDepthMap");
program.setUniformValue(m_mvMatrixLoc, modelView);

//uniform used for Color map to regular model switch
program.setUniformValue(m_useDepthMap, (m_showColorMap &&
    (m_showProblemAreas || m_showPrepMap || m_showDepthMap || m_showMockupMap)));

QMatrix3x3 normalMatrix = modelView.normalMatrix();
program.setUniformValue(m_normalMatrixLoc, normalMatrix);
program.setUniformValue(m_projMatrixLoc, projection);

//program.setUniformValue(m_relativePosLoc, m_relativePos);
program.setUniformValue(m_opacityLoc, m_opacity);
program.setUniformValue(m_colorMaskLoc, m_colorMask);

glEnableVertexAttribArray(m_vertexAttrLoc);
m_vertices.bind();
glVertexAttribPointer(m_vertexAttrLoc, 3, GL_DOUBLE, false, 3 * sizeof(GLdouble), NULL);
m_vertices.release();

glEnableVertexAttribArray(m_normalAttrLoc);
m_normals.bind();
glVertexAttribPointer(m_normalAttrLoc, 3, GL_DOUBLE, false, 0, NULL);
m_normals.release();

glEnableVertexAttribArray(m_colorAttrLoc);

if (m_showProblemAreas) {
    m_problemColorMap.bind();
    glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL);
    m_problemColorMap.release();
}
else if (m_showPrepMap) {
    m_prepColorMap.bind();
    glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL);
    m_prepColorMap.release();
}
else if (m_showMockupMap) {
    m_mokupColorMap.bind();
    glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL);
    m_mokupColorMap.release();
}
else {
    //m_colors.bind();
    //glVertexAttribPointer(m_colorAttrLoc, 3, GL_DOUBLE, false, 0, NULL);
    //m_colors.release();
}

m_indices.bind();
glDrawElements(GL_TRIANGLES, m_indices.size() / sizeof(int), GL_UNSIGNED_INT, NULL);
m_indices.release();

glDisableVertexAttribArray(m_vertexAttrLoc);
glDisableVertexAttribArray(m_normalAttrLoc);
glDisableVertexAttribArray(m_colorAttrLoc);

EDIT: Sorry for not being clear enough. The cube is merely an example. My requirements are that the shading works for any kind of mesh. Those with very sharp edges, and those that are very organic (like humans or animals).


问:
Does Google CloudML Serving allow connecting to NoSQL DBs e.g. Datastore?
We have a model currently serving on Cloud ML. As a modification we added connections to datastore, which return 403, Insufficient privileges.

The mock code generating the error is:

```<code>    from google.cloud import datastore
    import datetime
    # create & upload task
    client = datastore.Client()
    key = client.key('Task')
    task = datastore.Entity(
        key, exclude_from_indexes=['description'])

    task.update({
        'created': datetime.datetime.utcnow(),
        'description': 'description',
        'done': False
    })

    client.put(task)

    # now list tasks
    query = client.query(kind='Task')
    query.order = ['created']
    return list(query.fetch())
</code>```

The next step would be adding credentials (service account) and exporting new path to GOOGLE_APPLICATION_DEFAULT parameter. However, since getting this account is difficult (company layering), I'd like to save time by asking the question.

Is the only way of communication with a NoSQL DB via Cloud Functions? Is that the common approach?

答:
When you create your Model, you need custom prediction, and define a service account that has access to your resources.</p>

```<code>gcloud components install beta

gcloud beta ai-platform versions create your-version-name \
  --service-account your-service-account-name@your-project-id.iam.gserviceaccount.com
  ...
</code>```

Body:
We have a model currently serving on Cloud ML. As a modification we added connections to datastore, which return 403, Insufficient privileges.

The mock code generating the error is:

    from google.cloud import datastore
    import datetime
    # create & upload task
    client = datastore.Client()
    key = client.key('Task')
    task = datastore.Entity(
        key, exclude_from_indexes=['description'])

    task.update({
        'created': datetime.datetime.utcnow(),
        'description': 'description',
        'done': False
    })

    client.put(task)

    # now list tasks
    query = client.query(kind='Task')
    query.order = ['created']
    return list(query.fetch())

The next step would be adding credentials (service account) and exporting new path to GOOGLE_APPLICATION_DEFAULT parameter. However, since getting this account is difficult (company layering), I'd like to save time by asking the question.

Is the only way of communication with a NoSQL DB via Cloud Functions? Is that the common approach?

Body:
When you create your Model, you need custom prediction, and define a service account that has access to your resources.

gcloud components install beta

gcloud beta ai-platform versions create your-version-name \
  --service-account your-service-account-name@your-project-id.iam.gserviceaccount.com
  ...


问:
NumberFormatException while parsing date with SimpleDateFormat.parse()
Have a function that creates a time-only Date object. (why this is required is a long story which is irrelevant in this context but I need to compare to some stuff in XML world where TIME (i.e. time-only) is a valid concept).

```<code>private static final SimpleDateFormat DF_TIMEONLY = new SimpleDateFormat("HH:mm:ss.SSSZ");

public static Date getCurrentTimeOnly() {

    String onlyTimeStr = DF_TIMEONLY.format(new Date());  // line #5
    Date  onlyTimeDt = null;
    try {
        onlyTimeDt = DF_TIMEONLY.parse(onlyTimeStr);  // line #8
    } catch (ParseException ex) {
        // can never happen (you would think!)
    }
    return onlyTimeDt;
}
</code>```

There are probably at least a couple other ways to create a time-only Date in Java (or more precisely one where the date part is 1970-01-01) but my question is really not about that.

My question is that this piece of code starts randomly throwing NumberFormatException on line #8 after having run in production for long time. Technically I would say that this should be impossible, right ?

Here's an extract of random NumberFormatExceptions that come from above piece of code:

```<code>java.lang.NumberFormatException: multiple points
java.lang.NumberFormatException: For input string: ".11331133EE22"
java.lang.NumberFormatException: For input string: "880044E.3880044"
java.lang.NumberFormatException: For input string: "880044E.3880044E3"
</code>```

First of all I hope we can agree that formally this should be impossible?  The code uses the same format (DF_TIMEONLY) as output and then input. Let me know if you disagree that it should be impossible.

I haven't been able to re-produce the problem in a standalone environment. The problem seems to come when the JVM has run for a long time (>1 week). I cannot find a pattern to the problem, i.e. summer time / winter time, AM/PM, etc.  The error is sporadic, meaning that one minute it will throw NumberFormatException and the next minute it will run fine.

I suspect that there's some kind of arithmetic malfunction somewhere in either the JVM or perhaps even in the CPU. The above exceptions suggests that there's floating point numbers involved but I fail to see where they would come from. As far as I know Java's Date object is a wrapper around a long which holds the number of millis since the epoch.

I'm guessing what is happening is that there's an unexpected string onlyTimeStr created in line #5 so the problem really lies here rather than in line #8.

Here's an example of a full stacktrace:

```<code>java.lang.NumberFormatException: For input string: "880044E.3880044E3"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
    at java.lang.Double.parseDouble(Double.java:540)
    at java.text.DigitList.getDouble(DigitList.java:168)
    at java.text.DecimalFormat.parse(DecimalFormat.java:1321)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2086)
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1455)
    at java.text.DateFormat.parse(DateFormat.java:355)
    at org.mannmann.zip.Tanker.getCurrentTimeOnly(Tanker.java:746)
</code>```

Environment:  Java 7

答:
The diagnosis in the accepted answer is correct. I am providing the modern answer: do use java.time, the modern Java date and time API, for your date and time work. In Java 7 too. SimpleDateFormat is notoriously troublesome, its lack of thread safety is only one of its many problems. So don’t use that class.

OffsetTime.now() and ThreeTen Backport

You want the current time only, though with an offset from UTC, if your format pattern is to be believed. We have got a method exactly for that in java.time, the modern Java date and time API. So no reason to format into a string and parse back.

```<code>    OffsetTime timeOnly = OffsetTime.now(ZoneId.systemDefault());
    System.out.println(timeOnly);
</code>```

When I ran the code just now in my time zone, Europe/Copenhagen, on jdk.1.7.0_67, the output was:

06:21:55.419+01:00

By the way this is also the XML format for the concept of a time with time zone. Are we done?

The Date class you were returning is poorly designed and long outdated, so avoid it if you can. If you need one for a legacy API that you cannot afford to change just now, convert like this:

```<code>    Instant asInstant = LocalDate.of(1970, Month.JANUARY, 1)
            .atTime(timeOnly)
            .toInstant();
    Date oldfashionedDateObject = DateTimeUtils.toDate(asInstant);

    System.out.println("As java.util.Date: " + oldfashionedDateObject);
</code>```

As java.util.Date: Thu Jan 01 06:21:55 CET 1970

Question: Does it work on Java 7?

Environment: Java 7

java.time just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. In this case use Date.from(asInstant) for converting from  Instant to Date instead of the way shown in the code above.

In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Wikipedia article: ISO 8601

Body:
Have a function that creates a time-only Date object. (why this is required is a long story which is irrelevant in this context but I need to compare to some stuff in XML world where TIME (i.e. time-only) is a valid concept).

private static final SimpleDateFormat DF_TIMEONLY = new SimpleDateFormat("HH:mm:ss.SSSZ");

public static Date getCurrentTimeOnly() {

    String onlyTimeStr = DF_TIMEONLY.format(new Date());  // line #5
    Date  onlyTimeDt = null;
    try {
        onlyTimeDt = DF_TIMEONLY.parse(onlyTimeStr);  // line #8
    } catch (ParseException ex) {
        // can never happen (you would think!)
    }
    return onlyTimeDt;
}

There are probably at least a couple other ways to create a time-only Date in Java (or more precisely one where the date part is 1970-01-01) but my question is really not about that.

My question is that this piece of code starts randomly throwing NumberFormatException on line #8 after having run in production for long time. Technically I would say that this should be impossible, right ?

Here's an extract of random NumberFormatExceptions that come from above piece of code:

java.lang.NumberFormatException: multiple points
java.lang.NumberFormatException: For input string: ".11331133EE22"
java.lang.NumberFormatException: For input string: "880044E.3880044"
java.lang.NumberFormatException: For input string: "880044E.3880044E3"

First of all I hope we can agree that formally this should be impossible?  The code uses the same format (DF_TIMEONLY) as output and then input. Let me know if you disagree that it should be impossible.

I haven't been able to re-produce the problem in a standalone environment. The problem seems to come when the JVM has run for a long time (>1 week). I cannot find a pattern to the problem, i.e. summer time / winter time, AM/PM, etc.  The error is sporadic, meaning that one minute it will throw NumberFormatException and the next minute it will run fine.

I suspect that there's some kind of arithmetic malfunction somewhere in either the JVM or perhaps even in the CPU. The above exceptions suggests that there's floating point numbers involved but I fail to see where they would come from. As far as I know Java's Date object is a wrapper around a long which holds the number of millis since the epoch.

I'm guessing what is happening is that there's an unexpected string onlyTimeStr created in line #5 so the problem really lies here rather than in line #8.

Here's an example of a full stacktrace:

java.lang.NumberFormatException: For input string: "880044E.3880044E3"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
    at java.lang.Double.parseDouble(Double.java:540)
    at java.text.DigitList.getDouble(DigitList.java:168)
    at java.text.DecimalFormat.parse(DecimalFormat.java:1321)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2086)
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1455)
    at java.text.DateFormat.parse(DateFormat.java:355)
    at org.mannmann.zip.Tanker.getCurrentTimeOnly(Tanker.java:746)

Environment:  Java 7

Body:
The diagnosis in the accepted answer is correct. I am providing the modern answer: do use java.time, the modern Java date and time API, for your date and time work. In Java 7 too. SimpleDateFormat is notoriously troublesome, its lack of thread safety is only one of its many problems. So don’t use that class.

OffsetTime.now() and ThreeTen Backport

You want the current time only, though with an offset from UTC, if your format pattern is to be believed. We have got a method exactly for that in java.time, the modern Java date and time API. So no reason to format into a string and parse back.

    OffsetTime timeOnly = OffsetTime.now(ZoneId.systemDefault());
    System.out.println(timeOnly);

When I ran the code just now in my time zone, Europe/Copenhagen, on jdk.1.7.0_67, the output was:

06:21:55.419+01:00

By the way this is also the XML format for the concept of a time with time zone. Are we done?

The Date class you were returning is poorly designed and long outdated, so avoid it if you can. If you need one for a legacy API that you cannot afford to change just now, convert like this:

    Instant asInstant = LocalDate.of(1970, Month.JANUARY, 1)
            .atTime(timeOnly)
            .toInstant();
    Date oldfashionedDateObject = DateTimeUtils.toDate(asInstant);

    System.out.println("As java.util.Date: " + oldfashionedDateObject);

As java.util.Date: Thu Jan 01 06:21:55 CET 1970

Question: Does it work on Java 7?

Environment: Java 7

java.time just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. In this case use Date.from(asInstant) for converting from  Instant to Date instead of the way shown in the code above.

In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Wikipedia article: ISO 8601


问:
How to set Custom UI in GridView in Flutter?
I have a design which is like this :

I have tried using StaggeredGridView.count, StaggeredGridView.countBuilder and also Sliver Grid, but I didn't get the expected result because the UI has to be in the center of any device and should look like the image. The data would be from an API, so it has to be dynamic.

Any help would be appreciated.

Please find the image of the design to be achieved.
And here's my repo where is some code I tried:
https://github.com/marimeli/custom-layout/blob/master/lib/main.dart

答: Can you just create rows with containers inside. You can dynamically size containers based on the number of containers retrieved per row.</p>


问:
Could we maintain order of messages in AWS-IoT at subscriber end?
We have created a thing using AWS-IoT service. We have created a topic in that particular thing. Subscriber has subscribed to that topic and publisher is sending messages to that topic.

Below is the publisher messaging order:

```<code>message 0
message 1
message 2
message 3
message 4
</code>```

At the subscriber end the sequence of messages is not maintained. It's showing like this:

```<code>message 0
message 1
message 4
message 2
message 3
</code>```

答:
I guess its too late to answer to this question but I'll still go ahead so others facing this issue can have a work around. I faced a similar scenario and I did the following to make sure that the order is maintained.

I added sequence ID or timestamp to the payload sent to the broker from my iot device (can be any kind of client)

I then configured the IoT rules engine (add actions) to send the messages directly to DynamoDB where the data was automatically stored in a sorted manner (needs to be configured to sort by seqID).

Then I used Lambda to pull out the data from DynamoDB for my further workflow but you can use whatever service according to yours.

Body:
We have created a thing using AWS-IoT service. We have created a topic in that particular thing. Subscriber has subscribed to that topic and publisher is sending messages to that topic.

Below is the publisher messaging order:

message 0
message 1
message 2
message 3
message 4

At the subscriber end the sequence of messages is not maintained. It's showing like this:

message 0
message 1
message 4
message 2
message 3


问:
How to Create a Global Function then use on Controller
Im From VB.net base want to learn ASP.NET MVC

For Example : Function created below (how to create in global folder/cs and how to call it then use in Controller)

```<code>Function pRound(Number ,NumDigits)
    Dim dblPower, vPSTEmp, intSgn

    dblPower = 10 ^ NumDigits
    vPSTEmp = CDbl(Number * dblPower + 0.5)
    pRound = Int(vPSTEmp) / dblPower
End Function
</code>```

For vb I just add <--#include file="include/function.asp"-->

then can use it like pRound(number, 4)

Please Teach Me How to Do it. Thx a lot.

答: You can make a wrapper class and call from the controller else another option is that you can create a base controller and implement it in all your other controller, then you can access like base.pRound(1,1);</p>

Body:
Im From VB.net base want to learn ASP.NET MVC

For Example : Function created below (how to create in global folder/cs and how to call it then use in Controller)

Function pRound(Number ,NumDigits)
    Dim dblPower, vPSTEmp, intSgn

    dblPower = 10 ^ NumDigits
    vPSTEmp = CDbl(Number * dblPower + 0.5)
    pRound = Int(vPSTEmp) / dblPower
End Function

For vb I just add <--#include file="include/function.asp"-->

then can use it like pRound(number, 4)

Please Teach Me How to Do it. Thx a lot.


问:
Changing the membership providers ApplicationName during runtime. How?
I have a bit of a unique situation here. I'm making a web application that is going to have
the ability to login with different web applications credentials. For example you can login/register with my site or you can login/register with your YouTube account. I'm not using OpenID because I need to have access to YouTube's data in this case.

I'm using ASP.NET MVC 3 EF4 with custom Membership, role, profile providers.

The problem is user names can't be unique because someone with a YouTube user name could have the same user name as someone that registered with my site. So I got around with by specifying a user type in my user table. This is pretty much a composite key (user id and user type).

I have a custom authorize attribute that is checking for the role that the user is in but now I need to implement a custom IPrincipal because I need to pass a user type. Only problem is where do I store that? the session?

Originally I thought this is what the Application table was for, and I had momentary success with that but read there is threading issues, and I was getting session faults all over the place it wasn't that great :(

I'm wondering what the best way to do with is because I can't use the overridden methods in the providers because I have to add a UserType parameter to some of the methods, but then this breaks the functionality of the provider.

EDIT:
I basically need to have the ability to change the ApplicationName at runtime pro-grammatically. I tried doing this, the only problem was when I stopped my development server but left my browser open then ran my dev server again it wouldnt keep the application name.

EDIT:
I've changed my application to use OAuth, I never found a good solution.

答:
I basically need to have the ability
  to change the ApplicationName at
  runtime pro-grammatically. I tried
  doing this, the only problem was when
  I stopped my development server but
  left my browser open then ran my dev
  server again it wouldnt keep the
  application name.

If you need to change the ApplicationName, this means you need to select a provider at runtime.
The only way to do this is to NOT use the singleton "Membership" as it uses the provider defined in web.config.

Instead each time you need your provider use :

```<code>MembershipProvider userProvider = Membership.Providers[UserProviderName];
</code>```

Just set UserProviderName the way you want. I would go with a custom global authorization or preAction filter which detect the provider from some cookie or other session variable and put the provider in the HttpContextBase.Items collection which lives for one and only one request.

Body:
I basically need to have the ability
  to change the ApplicationName at
  runtime pro-grammatically. I tried
  doing this, the only problem was when
  I stopped my development server but
  left my browser open then ran my dev
  server again it wouldnt keep the
  application name.

If you need to change the ApplicationName, this means you need to select a provider at runtime.
The only way to do this is to NOT use the singleton "Membership" as it uses the provider defined in web.config.

Instead each time you need your provider use :

MembershipProvider userProvider = Membership.Providers[UserProviderName];

Just set UserProviderName the way you want. I would go with a custom global authorization or preAction filter which detect the provider from some cookie or other session variable and put the provider in the HttpContextBase.Items collection which lives for one and only one request.


问:
How to overwrite Excel destination in SSIS?
I have created a package to fetch data from two SQL Server tables, and using merge join combined this data, then stored the result into an Excel destination.

The first time it works fine. The second time it stores repeated data in the Excel file.

How do I overwrite the Excel file rows?

答: Using a CSV file with flat-file connection manager would serve your purpose of overwriting.</p>


问:
How to add members to a class dynamically using options as coonstructor args in python?
I want to create my Python class which will dynamically build its members in the constructor based on the options.
Check the following sample code that I am trying to build.

options = {
'param1' = 'v1'
'param2' = 2
'param3' = bool
'param4' = {}
}

class MyCustomObject:
  def __init__(self, options):
    self.props = {}
    for key in options.keys():
      self.props[key] = options[key]

a1 = MyCustomObject(options)

# I want to access the attributes of the props using dot
a1.param1 = 10
print(a1.param1)
```
<p>If I had known what options I need to add to the my object when defining the class, the I could have added following to the class definition:</p>
<pre class="lang-py prettyprint-override"><code>@property
def param1(self):
  return self.options['param1']

@param1.setter(self, value)
  self.options['param1'] = value
</code>```

How to achieve the same behavior dynamically i.e. providing the options during object instantiation?

答:
You can make use of setattr method of Python.

setattr(object, name, value)

The setattr() function sets the value of the attribute of an object.

```<code>options = {'param1' :'v1','param2' : 2,'param3' : "bool",'param4' : {}}
class MyCustomObject:
    def __init__(self, options):
        for key in options.keys():
            setattr(self, key, options[key])
a1 = MyCustomObject(options)
</code>```

Body:
I want to create my Python class which will dynamically build its members in the constructor based on the options.
Check the following sample code that I am trying to build.

options = {
'param1' = 'v1'
'param2' = 2
'param3' = bool
'param4' = {}
}

class MyCustomObject:
  def __init__(self, options):
    self.props = {}
    for key in options.keys():
      self.props[key] = options[key]

a1 = MyCustomObject(options)

# I want to access the attributes of the props using dot
a1.param1 = 10
print(a1.param1)

If I had known what options I need to add to the my object when defining the class, the I could have added following to the class definition:

@property
def param1(self):
  return self.options['param1']

@param1.setter(self, value)
  self.options['param1'] = value

How to achieve the same behavior dynamically i.e. providing the options during object instantiation?

Body:
You can make use of setattr method of Python.

setattr(object, name, value)

The setattr() function sets the value of the attribute of an object.

options = {'param1' :'v1','param2' : 2,'param3' : "bool",'param4' : {}}
class MyCustomObject:
    def __init__(self, options):
        for key in options.keys():
            setattr(self, key, options[key])
a1 = MyCustomObject(options)