问:
BatchUpdateException is not continues the flow once exception occurs
My business scenario is to read a csv file and its contents and then persist in to the oracle database.

Consider that csv file having 1000 rows in it. Iterating each line and their columns values and setting in to preparedstatement and then adding in to batch using preparedStatement.addBatch() and then executing the batch. refer example below.

```<code>try {
  for(List<String> mainList:dataList) { //lines
     int i=1;
     ps = conn.prepareStatement(insertQuery);
     for(String value:mainList) { //column values
        ps.setString(i++, value);
     }
     ps.addBatch();
  }
  int[] updateCounts = ps.executeBatch(); //50th record not valid

  } catch(BatchUpdateException e){
       int[] updateCounts = e.getUpdateCounts();
  }
</code>```

Here addbatch will have all lines(1000) and values, say example 50th record values is not valid. As of now batch executed(inserted) 49 records properly in database table. At the time of 50th record insertion, executebatch throwing BatchUpdateException (it might be any issue) in catch block since not a valid record.

After this, flow is blocked and does not continues to execute the remaining 950 records in the batch. what I want is once exception is thrown my code should run and insert remaining 950 records in the database.

Please help to resolve this issue or provide me any other alternate way to achieve this logic.

CSV sample:

```<code>Name,Id,Firstname,Lastname
Bharathi,2070,Bharathi,Raja   --> row 1
Craig,Text,Craig,Johnson      --> row 2
Mary,9346,Mary,Jenk           --> row 3
</code>```

Consider row 2 is the 50th record, value for the Id is Text which is not valid it should be number so exception thrown.

I'm having below dependencies in pom.xml and using Spring Boot Application

```<code><dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>
</code>```

答:
Found alternate way to achieve this kind of problems.

I have made Prior validation before setting values in to preparedstatement and added in to batch. so that always valid records only added in to batch.

I have taken column name and datatype from tables and kept as Map(columnDataTypeMap) for the validation.

```<code>try {
  boolean skipFlag=true;
  for(List<String> mainList:dataList) { //lines
     int i=1;
     ps = conn.prepareStatement(insertQuery);
     for(String value:mainList) { //column values
        try {
               String columnName = csvHeader.split(",")[columnCount];
               String dataType = columnDataTypeMap.get(columnName.toUpperCase());
               if("VARCHAR2".equalsIgnoreCase(dataType)) {
                    ps.setString(i++, String.valueOf(value));
               } else if("NUMBER".equalsIgnoreCase(dataType)) {
                    ps.setInt(i++, Integer.valueOf(value));
               }
        }catch(Exception e) {
            skipFlag = false;
        }
     }
    if(skipFlag) {
        ps.addBatch();
    }
  }
  int[] updateCounts = ps.executeBatch();

  } catch(BatchUpdateException e){
       int[] updateCounts = e.getUpdateCounts();
  }
</code>```

Body:
My business scenario is to read a csv file and its contents and then persist in to the oracle database.

Consider that csv file having 1000 rows in it. Iterating each line and their columns values and setting in to preparedstatement and then adding in to batch using preparedStatement.addBatch() and then executing the batch. refer example below.

try {
  for(List<String> mainList:dataList) { //lines
     int i=1;
     ps = conn.prepareStatement(insertQuery);
     for(String value:mainList) { //column values
        ps.setString(i++, value);
     }
     ps.addBatch();
  }
  int[] updateCounts = ps.executeBatch(); //50th record not valid

  } catch(BatchUpdateException e){
       int[] updateCounts = e.getUpdateCounts();
  }

Here addbatch will have all lines(1000) and values, say example 50th record values is not valid. As of now batch executed(inserted) 49 records properly in database table. At the time of 50th record insertion, executebatch throwing BatchUpdateException (it might be any issue) in catch block since not a valid record.

After this, flow is blocked and does not continues to execute the remaining 950 records in the batch. what I want is once exception is thrown my code should run and insert remaining 950 records in the database.

Please help to resolve this issue or provide me any other alternate way to achieve this logic.

CSV sample:

Name,Id,Firstname,Lastname
Bharathi,2070,Bharathi,Raja   --> row 1
Craig,Text,Craig,Johnson      --> row 2
Mary,9346,Mary,Jenk           --> row 3

Consider row 2 is the 50th record, value for the Id is Text which is not valid it should be number so exception thrown.

I'm having below dependencies in pom.xml and using Spring Boot Application

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>

Body:
Found alternate way to achieve this kind of problems.

I have made Prior validation before setting values in to preparedstatement and added in to batch. so that always valid records only added in to batch.

I have taken column name and datatype from tables and kept as Map(columnDataTypeMap) for the validation.

try {
  boolean skipFlag=true;
  for(List<String> mainList:dataList) { //lines
     int i=1;
     ps = conn.prepareStatement(insertQuery);
     for(String value:mainList) { //column values
        try {
               String columnName = csvHeader.split(",")[columnCount];
               String dataType = columnDataTypeMap.get(columnName.toUpperCase());
               if("VARCHAR2".equalsIgnoreCase(dataType)) {
                    ps.setString(i++, String.valueOf(value));
               } else if("NUMBER".equalsIgnoreCase(dataType)) {
                    ps.setInt(i++, Integer.valueOf(value));
               }
        }catch(Exception e) {
            skipFlag = false;
        }
     }
    if(skipFlag) {
        ps.addBatch();
    }
  }
  int[] updateCounts = ps.executeBatch();

  } catch(BatchUpdateException e){
       int[] updateCounts = e.getUpdateCounts();
  }


来源: stackexchange

问:
Codeigniter issue with escaping values when passing array to query with "in" in the where clause
I have the function below in my model for a codeigniter project, and the variable $id is an array and for example, contains (1,2,3). Now that i'm revisiting it, I think that i'm not actually escaping my array $id. I think I would have to change the line
$this->db->escape($id)
to
$id = $this->db->escape($id)

If I do that, then it puts single quotes around every element in the array and treats it as one long string like this: '(1,2,3)'.

Can someone confirm that I am not actually escaping my variable and either suggest a solution or let me know if this is a bug within the codeigniter framework?

```<code>function get_ratings($id)
    {

        $this->db->escape($id); // had to manually escape the variable since it's being used in an "in" in the where clause.

        $sql = "select * from toys t
                 where t.toy_id in ($id)";

        $query = $this->db->query($sql, $id);

        if($query->num_rows() > 0)
        {
            return $query->result_array();
        }
        else
        {
            return false;
        }
    }
</code>```

答:
What you want to do is escape the individual values in the array. So you can use array_map on the array first.

```<code>$id = array_map('some_escape_function', $id);
</code>```

See: http://php.net/manual/en/function.array-map.php

Then you can do:

```<code>$in = join(",",$id);
</code>```

Your SQL would then be:

```<code>WHERE t.toy_id in ($in)
</code>```

Which gives you:

```<code>WHERE t.toy_id in ('1','2','3')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the function below in my model for a codeigniter project, and the variable $id is an array and for example, contains (1,2,3). Now that i'm revisiting it, I think that i'm not actually escaping my array $id. I think I would have to change the line
$this->db->escape($id)
to
$id = $this->db->escape($id)

If I do that, then it puts single quotes around every element in the array and treats it as one long string like this: '(1,2,3)'.

Can someone confirm that I am not actually escaping my variable and either suggest a solution or let me know if this is a bug within the codeigniter framework?

function get_ratings($id)
    {

        $this->db->escape($id); // had to manually escape the variable since it's being used in an "in" in the where clause.

        $sql = "select * from toys t
                 where t.toy_id in ($id)";

        $query = $this->db->query($sql, $id);

        if($query->num_rows() > 0)
        {
            return $query->result_array();
        }
        else
        {
            return false;
        }
    }

Body:
What you want to do is escape the individual values in the array. So you can use array_map on the array first.

$id = array_map('some_escape_function', $id);

See: http://php.net/manual/en/function.array-map.php

Then you can do:

$in = join(",",$id);

Your SQL would then be:

WHERE t.toy_id in ($in)

Which gives you:

WHERE t.toy_id in ('1','2','3')


问:
Accuracy of 1.0 while Training Loss and Validation Loss still decreasing
I have created a LSTM RNN in order to predict whether someone is driving or not based on gps coordinates.
Here is a sample of the data(note: x,y,z are 3d coordinates converted from lat,lon):

```<code>                        x           y           z       trip_id,mode_cat,weekday,period_of_day
datetime            id
2011-08-27 06:13:01 20  0.650429    0.043524    0.758319    1   1   1   0
2011-08-27 06:13:02 20  0.650418    0.043487    0.758330    1   1   1   0
2011-08-27 06:13:03 20  0.650421    0.043490    0.758328    1   1   1   0
2011-08-27 06:13:04 20  0.650427    0.043506    0.758322    1   1   1   0
2011-08-27 06:13:05 20  0.650438    0.043516    0.758312    1   1   1   0
</code>```

When I train my network, my training_loss and validation_loss both decrease but accuracy reaches 1.0 on the first epoch. I made sure that my training and testing data are not the same.
Here is how I split the training and testing data:

```<code>t_num_test = df["trip_id"].iloc[-1]*4//5
train_test_df = df.loc[df["trip_id"]<=t_num_test].copy(deep=True)
test_test_df = df.loc[df["trip_id"]>t_num_test].copy(deep=True)

features_train = train_test_df[["x","y","z","datetime","id","trip_id","mode_cat","weekday","period_of_day"]]
features_train.set_index(["datetime","id"],inplace=True)
dataset_train_x = features_train[["x","y","z","trip_id","weekday","period_of_day"]].values
dataset_train_y = features_train[["mode_cat"]].values

features_test = test_test_df[["x","y","z","datetime","id","trip_id","mode_cat","weekday","period_of_day"]]
features_test.set_index(["datetime","id"],inplace=True)
dataset_test_x = features_test[["x","y","z","trip_id","weekday","period_of_day"]].values
dataset_test_y = features_test[["mode_cat"]].values
</code>```

And here is how I have built my network:

```<code>single_step_model = tf.keras.models.Sequential()
single_step_model.add(tf.keras.layers.LSTM(1,
                                           input_shape=x_train_single.shape[-2:]))
single_step_model.add(tf.keras.layers.Dropout(0.2))
single_step_model.add(tf.keras.layers.Dense(1, activation='sigmoid'))

single_step_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), loss='binary_crossentropy',
                          metrics=['accuracy'])
.
.
.
single_step_history = single_step_model.fit(train_data_single, epochs=epochs,
                                            steps_per_epoch=evaluation_interval,
                                            validation_data=test_data_single,
                                            validation_steps=60)
</code>```

And here is the graph displaying training_loss, validation_loss and accuracy

What could be causing this outcome?
If it matters, I'm using approximately 500,000 data points with approximately 8000 unique trip_id.

Please advise

EDIT:
# of Driving/Not Driving (Mode_cat: 1/0)

答:
Hope this helps!

Few cases I could think of

Your dataset is biased. It could such that most of the input data is skewed? Check the % of mode_cat values in it. (All are 1 only, or most of them are 1's only ?)

You X values could have a feature/column that is a function y is a function of x values (like y_val = m * x_col2 + x_col3 ?)

Accuracy is good to learn but try to use something like f1 score/confusion_matrix.

Link:

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html#sklearn.metrics.f1_score

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html#sklearn.metrics.confusion_matrix

ContentLicense: CC BY-SA 4.0

Body:
I have created a LSTM RNN in order to predict whether someone is driving or not based on gps coordinates.
Here is a sample of the data(note: x,y,z are 3d coordinates converted from lat,lon):

                        x           y           z       trip_id,mode_cat,weekday,period_of_day
datetime            id
2011-08-27 06:13:01 20  0.650429    0.043524    0.758319    1   1   1   0
2011-08-27 06:13:02 20  0.650418    0.043487    0.758330    1   1   1   0
2011-08-27 06:13:03 20  0.650421    0.043490    0.758328    1   1   1   0
2011-08-27 06:13:04 20  0.650427    0.043506    0.758322    1   1   1   0
2011-08-27 06:13:05 20  0.650438    0.043516    0.758312    1   1   1   0

When I train my network, my training_loss and validation_loss both decrease but accuracy reaches 1.0 on the first epoch. I made sure that my training and testing data are not the same.
Here is how I split the training and testing data:

t_num_test = df["trip_id"].iloc[-1]*4//5
train_test_df = df.loc[df["trip_id"]<=t_num_test].copy(deep=True)
test_test_df = df.loc[df["trip_id"]>t_num_test].copy(deep=True)

features_train = train_test_df[["x","y","z","datetime","id","trip_id","mode_cat","weekday","period_of_day"]]
features_train.set_index(["datetime","id"],inplace=True)
dataset_train_x = features_train[["x","y","z","trip_id","weekday","period_of_day"]].values
dataset_train_y = features_train[["mode_cat"]].values

features_test = test_test_df[["x","y","z","datetime","id","trip_id","mode_cat","weekday","period_of_day"]]
features_test.set_index(["datetime","id"],inplace=True)
dataset_test_x = features_test[["x","y","z","trip_id","weekday","period_of_day"]].values
dataset_test_y = features_test[["mode_cat"]].values

And here is how I have built my network:

single_step_model = tf.keras.models.Sequential()
single_step_model.add(tf.keras.layers.LSTM(1,
                                           input_shape=x_train_single.shape[-2:]))
single_step_model.add(tf.keras.layers.Dropout(0.2))
single_step_model.add(tf.keras.layers.Dense(1, activation='sigmoid'))

single_step_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), loss='binary_crossentropy',
                          metrics=['accuracy'])
.
.
.
single_step_history = single_step_model.fit(train_data_single, epochs=epochs,
                                            steps_per_epoch=evaluation_interval,
                                            validation_data=test_data_single,
                                            validation_steps=60)

And here is the graph displaying training_loss, validation_loss and accuracy

What could be causing this outcome?
If it matters, I'm using approximately 500,000 data points with approximately 8000 unique trip_id.

Please advise

EDIT:
# of Driving/Not Driving (Mode_cat: 1/0)


问:
VB Entering a Non_Numeric value crashes the program
Please consider adding a description to this question to attract more helpful responses.

```<code>Public Class Form1
    Private Sub BtnCalculateRevenue_Click(sender As Object, e As EventArgs) Handles BtnCalculateRevenue.Click
        Dim intvalue As Integer = CInt(TxtInputClassA.Text)
        Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
        Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
        Dim total As Double
        Try
            LblStatus.Text = String.Empty

            LblClassAResult.Text = (intvalue * 15).ToString("c")
            LblClassBResult.Text = (intvalue2 * 12).ToString("c")
            LblClassCResult.Text = (intvalue3 * 9).ToString("c")
            total = CDbl((intvalue * 15) + (intvalue2 * 12) + (intvalue3 * 9))
            LblTotal.Text = total.ToString("c")
        Catch
            LblStatus.Text = "Please Enter a Number"
        End Try
    End Sub

    Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles BtnExit.Click
        Me.Close()
    End Sub

    Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
        TxtInputClassA.Clear()
        TxtInputClassB.Clear()
        TxtinputClassC.Clear()
        LblClassAResult.Text = String.Empty
        LblClassBResult.Text = String.Empty
        LblClassCResult.Text = String.Empty
        LblTotal.Text = String.Empty
    End Sub
End Class
</code>```

VB Entering a Non_Numeric value crashes the program

答: Replace your textboxes with NumericUpDown controls and retrieve their .Value for your calculation. NUDs don't allow non numeric input and can have a fixed number of decimal places which may also be useful in a financial context</p>

Body:
Please consider adding a description to this question to attract more helpful responses.

Public Class Form1
    Private Sub BtnCalculateRevenue_Click(sender As Object, e As EventArgs) Handles BtnCalculateRevenue.Click
        Dim intvalue As Integer = CInt(TxtInputClassA.Text)
        Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
        Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
        Dim total As Double
        Try
            LblStatus.Text = String.Empty

            LblClassAResult.Text = (intvalue * 15).ToString("c")
            LblClassBResult.Text = (intvalue2 * 12).ToString("c")
            LblClassCResult.Text = (intvalue3 * 9).ToString("c")
            total = CDbl((intvalue * 15) + (intvalue2 * 12) + (intvalue3 * 9))
            LblTotal.Text = total.ToString("c")
        Catch
            LblStatus.Text = "Please Enter a Number"
        End Try
    End Sub

    Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles BtnExit.Click
        Me.Close()
    End Sub

    Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
        TxtInputClassA.Clear()
        TxtInputClassB.Clear()
        TxtinputClassC.Clear()
        LblClassAResult.Text = String.Empty
        LblClassBResult.Text = String.Empty
        LblClassCResult.Text = String.Empty
        LblTotal.Text = String.Empty
    End Sub
End Class

VB Entering a Non_Numeric value crashes the program


问:
Can i install Kubernates cluster on single machine?
i have only one instance machine which is  centos-7 minimal installation. can i install kubernates cluster as a master and node same machine(without minikube and micro8s). is there any possible way? </p>

<p>Thanks.  </p>

答:
You can use kind. Kind is a tool for running local Kubernetes clusters using Docker container. So on the same machine docker containers are created for each Kubernetes node.

Also you can install a single node Kubernetes cluster using kubeadm and the master node can be marked as schedule-able so that pods can be scheduled on the master node.

Body:
i have only one instance machine which is  centos-7 minimal installation. can i install kubernates cluster as a master and node same machine(without minikube and micro8s). is there any possible way?

Thanks.


问:
upload images useing the chevereto api with php
i am trying to upload images  from my server to the img server where chevereto  is installed but i cant get it to work

here is my code so far :

```<code> $directory = "/var/www";
 $images = glob($directory . "/*.jpg");
foreach($images as $image)
{
  echo $image;
  $data =  base64_encode(file_get_contents($image));

  $run= shell_exec("curl --location --request POST \"http://ip/api/1/upload/?key=123456789&source=$data&format=json\"");
print_r($run);

}
</code>```

getting error : 414 Request-URI Too Large

here is the api documentation : https://chevereto.com/docs/api-v1

答:
You are using a POST request method, but you are sending the source parameter in URL.
The $data in your URL is base64 encoded, which results in a very large string. That's why you are getting the error 414 Request-URI Too Large.

Solution:

You should change the params to JSON body using the same POST method.

From the documentation of chevereto that you provided it is made clear.

API v1 calls can be done using the POST or GET request methods but since GET request are limited by the maximum allowed length of an URL you should prefer the POST request method.

So use POST method with JSON Body containing the parameters as key:value pair. That will solve the issue.

Sample PHP Code:

$requestData = [
    'key' => 123456789,
    'source' => 'base64EncodedStringHere',
    'format' => 'json'
];

$jsonData = json_encode($jsonData);

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://ip/api/1/upload",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $jsonData,
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

```

Body:
i am trying to upload images  from my server to the img server where chevereto  is installed but i cant get it to work

here is my code so far :

 $directory = "/var/www";
 $images = glob($directory . "/*.jpg");
foreach($images as $image)
{
  echo $image;
  $data =  base64_encode(file_get_contents($image));

  $run= shell_exec("curl --location --request POST \"http://ip/api/1/upload/?key=123456789&source=$data&format=json\"");
print_r($run);

}

getting error : 414 Request-URI Too Large

here is the api documentation : https://chevereto.com/docs/api-v1


问:
Which is the best approach to consume webservices and manipulate its data?
Need some advice on the best approach.

Currently we are going to start a new CI web project where we need to leverage data heavily from a external web-services or API for data?

Is it better to manipulate the data programically (in objects or array) when i need to sort them or store them in database and call them with order, group by etc..?

Is there a known architecture or framework for this?

What's the best approach use nowadays like how aggregater website is doing where they pull many data sources from various vendor API?

答:
After all these while, i've have come up with the plan and it's working great !

Consume webservices

Deserialize XML to arrays/ objects

Store in cache (APC/File cache, i'm using codeigniter by the way ) (expire every 4hrs)

First request will take 3-4 secs to complete(first call to webservice to grab data, stored it in cache), while subsequent requests from users take 0.002 secs due to cached data. 4hours later, the cycle will repeat so as to make sure data is 4hourly updated from webservice.
If you are the first user that access the site after each refresh, you are the unlucky chap. But you sacrificed for all other chaps.


问:
Git confusion, made many changes including deleting and renaming files in goorm, how to proceed
I am rewriting my personal website and have drastically changed the way the site works, which means I have deleted many of the old files that are not needed out of my goorm workspace (many files were moved to a CDN). I have been always doing the git add, git commit -m and git push heroku master steps when pushing any changes out to heroku to make the changes live, but I’m now confused about what to do after changing so much of the file structure.
  When I do a

```<code> git status
</code>```

there are dozens of deleted files, I have changed so much, I almost think it would be better to wipe the git repo clean and start over. What is the best way to do this.?
  If I truly don’t want to revert to any previous versions, can I just delete the .git folder in my local goorm structure and start over with

```<code>git init
</code>```

or is there a better way? The web dev course I watched explained very little about git and not sure If I could create some other "v2" branch that is the new file structure. I will not be going back to a previous version of this site since I drastically changed the way the entire site functions.
Also, if I create a new git repo with git init and it has way less files than what is currently on heroku, do the files that were on heroku stay, or does a git push command overwrite everything that is at the target of the push.?
 Thanks for any info.

答:
If you want delete the "old" git-repo and create a new repo with the current status and all changed files you can remove the .git folder.

```<code>cd repository-path/
rm -rf .git
</code>```

(for deleting git repository on git-server tutorial)

after this you can create a new git repo in this path with

```<code>git init
git add . //with . you add all files
git commit -m "new repo cleaned old files"
git push
</code>```

If you don't want ti delete the changed files make

```<code>git add . //with . you add all files
git commit -m "cleaned current repo from old files"
git push
</code>```

Is there a better way?

I would not delete the current git repository, even if you never want to go back to the old version, because that's what git is made for. And at some point you might still be happy if you can't go back, who knows? Since git is a versioning system, you can change as much as you want, that doesn't disturb git, because git was created for it.
So I leave it up to you what you want to do, whether completely delete and restart or just revise.

Look also git tag for identify specific release version. So you can save several version. In your case old-version and new-version tutorial just to show how powerful git is!

Body:
I am rewriting my personal website and have drastically changed the way the site works, which means I have deleted many of the old files that are not needed out of my goorm workspace (many files were moved to a CDN). I have been always doing the git add, git commit -m and git push heroku master steps when pushing any changes out to heroku to make the changes live, but I’m now confused about what to do after changing so much of the file structure.
  When I do a

 git status

there are dozens of deleted files, I have changed so much, I almost think it would be better to wipe the git repo clean and start over. What is the best way to do this.?
  If I truly don’t want to revert to any previous versions, can I just delete the .git folder in my local goorm structure and start over with

git init

or is there a better way? The web dev course I watched explained very little about git and not sure If I could create some other "v2" branch that is the new file structure. I will not be going back to a previous version of this site since I drastically changed the way the entire site functions.
Also, if I create a new git repo with git init and it has way less files than what is currently on heroku, do the files that were on heroku stay, or does a git push command overwrite everything that is at the target of the push.?
 Thanks for any info.

Body:
If you want delete the "old" git-repo and create a new repo with the current status and all changed files you can remove the .git folder.

cd repository-path/
rm -rf .git

(for deleting git repository on git-server tutorial)

after this you can create a new git repo in this path with

git init
git add . //with . you add all files
git commit -m "new repo cleaned old files"
git push

If you don't want ti delete the changed files make

git add . //with . you add all files
git commit -m "cleaned current repo from old files"
git push

Is there a better way?

I would not delete the current git repository, even if you never want to go back to the old version, because that's what git is made for. And at some point you might still be happy if you can't go back, who knows? Since git is a versioning system, you can change as much as you want, that doesn't disturb git, because git was created for it.
So I leave it up to you what you want to do, whether completely delete and restart or just revise.

Look also git tag for identify specific release version. So you can save several version. In your case old-version and new-version tutorial just to show how powerful git is!


问:
Pandas row filters and and division from specific rows and columns
I have the following dataframe:-

```<code>traffic_type    date        region   total_views
desktop         01/04/2018  aug      50
mobileweb       01/04/2018  aug      60
total           01/04/2018  aug      100
desktop         01/04/2018  world    20
mobileweb       01/04/2018  world    30
total           01/04/2018  world    40
</code>```

I need to group by traffic_type, date, region, and filter the rows with traffic type total and in the same row create a desktop_share column which is total_views of traffic_type==desktop / total views of the traffic_type ==total the rest of the rows are blank for this column.

```<code> traffic_type    date        region   total_views desktop_share
desktop         01/04/2018  aug      50
mobileweb       01/04/2018  aug      60
total           01/04/2018  aug      200          0.25
desktop         01/04/2018  world    20
mobileweb       01/04/2018  world    30
total           01/04/2018  world    40           0.5
</code>```

I have a long approach which works but I am looking for something more precise
based on numpy or just pandas.
My solution:

```<code>df1 = df2.loc[df2.traffic_type == 'desktop']
df1 = df1[['date', 'region', 'total_views']]
df1 = df2.merge(df1, how='left', on=['region', 'date'], suffixes=('', '_desktop'))
df1 = df1.loc[df1.traffic_type == 'total']
df1['desktop_share'] = df1['total_views_desktop'] / df1['total_views']
df1 = df1[['date', 'region', 'desktop_share', 'traffic_type']]

dfinal = df2.merge(df1, how='left', on=['region', 'date', 'traffic_type'])
</code>```

答:
One idea with pivoting:

```<code>df1 = df.pivot_table(index=['date','region'],
                     columns='traffic_type',
                     values='total_views',
                     aggfunc='sum')
print (df1)
traffic_type       desktop  mobileweb  total
date       region
01/04/2018 aug          50         60    200
           world        20         30     40

df2 = df1['desktop'].div(df1['total']).reset_index(name='desktop_share').assign(traffic_type='total')

df = df.merge(df2, how='left')
print (df)
  traffic_type        date region  total_views  desktop_share
0      desktop  01/04/2018    aug           50            NaN
1    mobileweb  01/04/2018    aug           60            NaN
2        total  01/04/2018    aug          200           0.25
3      desktop  01/04/2018  world           20            NaN
4    mobileweb  01/04/2018  world           30            NaN
5        total  01/04/2018  world           40           0.50
</code>```

Another idea with MultiIndex:

```<code>df1 = df.set_index(['traffic_type','date','region'])

a = df1.xs('desktop', drop_level=False).rename({'desktop':'total'})
b = df1.xs('total', drop_level=False)

df = df1.assign(desktop_share = a['total_views'].div(b['total_views'])).reset_index()
print (df)
  traffic_type        date region  total_views  desktop_share
0      desktop  01/04/2018    aug           50            NaN
1    mobileweb  01/04/2018    aug           60            NaN
2        total  01/04/2018    aug          200           0.25
3      desktop  01/04/2018  world           20            NaN
4    mobileweb  01/04/2018  world           30            NaN
5        total  01/04/2018  world           40           0.50
</code>```

Body:
I have the following dataframe:-

traffic_type    date        region   total_views
desktop         01/04/2018  aug      50
mobileweb       01/04/2018  aug      60
total           01/04/2018  aug      100
desktop         01/04/2018  world    20
mobileweb       01/04/2018  world    30
total           01/04/2018  world    40

I need to group by traffic_type, date, region, and filter the rows with traffic type total and in the same row create a desktop_share column which is total_views of traffic_type==desktop / total views of the traffic_type ==total the rest of the rows are blank for this column.

 traffic_type    date        region   total_views desktop_share
desktop         01/04/2018  aug      50
mobileweb       01/04/2018  aug      60
total           01/04/2018  aug      200          0.25
desktop         01/04/2018  world    20
mobileweb       01/04/2018  world    30
total           01/04/2018  world    40           0.5

I have a long approach which works but I am looking for something more precise
based on numpy or just pandas.
My solution:

df1 = df2.loc[df2.traffic_type == 'desktop']
df1 = df1[['date', 'region', 'total_views']]
df1 = df2.merge(df1, how='left', on=['region', 'date'], suffixes=('', '_desktop'))
df1 = df1.loc[df1.traffic_type == 'total']
df1['desktop_share'] = df1['total_views_desktop'] / df1['total_views']
df1 = df1[['date', 'region', 'desktop_share', 'traffic_type']]

dfinal = df2.merge(df1, how='left', on=['region', 'date', 'traffic_type'])

Body:
One idea with pivoting:

df1 = df.pivot_table(index=['date','region'],
                     columns='traffic_type',
                     values='total_views',
                     aggfunc='sum')
print (df1)
traffic_type       desktop  mobileweb  total
date       region
01/04/2018 aug          50         60    200
           world        20         30     40

df2 = df1['desktop'].div(df1['total']).reset_index(name='desktop_share').assign(traffic_type='total')

df = df.merge(df2, how='left')
print (df)
  traffic_type        date region  total_views  desktop_share
0      desktop  01/04/2018    aug           50            NaN
1    mobileweb  01/04/2018    aug           60            NaN
2        total  01/04/2018    aug          200           0.25
3      desktop  01/04/2018  world           20            NaN
4    mobileweb  01/04/2018  world           30            NaN
5        total  01/04/2018  world           40           0.50

Another idea with MultiIndex:

df1 = df.set_index(['traffic_type','date','region'])

a = df1.xs('desktop', drop_level=False).rename({'desktop':'total'})
b = df1.xs('total', drop_level=False)

df = df1.assign(desktop_share = a['total_views'].div(b['total_views'])).reset_index()
print (df)
  traffic_type        date region  total_views  desktop_share
0      desktop  01/04/2018    aug           50            NaN
1    mobileweb  01/04/2018    aug           60            NaN
2        total  01/04/2018    aug          200           0.25
3      desktop  01/04/2018  world           20            NaN
4    mobileweb  01/04/2018  world           30            NaN
5        total  01/04/2018  world           40           0.50


问:
Airflow Slack failed to send Message
I am trying to achieve Airflow integration with Slack,
have received the webhook URL, and created the connection as below. Why is it showing google.com ??

Why is it using the default http_conn_id and connecting to google ??

But got an error as below

ERROR - Error in sending a message to Slack channel #airflow-alerts
            by Airflow: 404:Not Found

```<code>{base_hook.py:83} INFO - Using connection to: id: http_default. Host: https://www.google.com/, Port: None, Schema: None, Login: None, Password: None, extra: {}
{logging_mixin.py:95} INFO - [2020-05-29 12:43:21,374] {http_hook.py:128} INFO - Sending 'POST' to url: https://www.google.com//T00A6ASFHD8S/G1FDF4K/a3zfKsadfsrScxgadfsdafOIgIvgW

requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://www.google.com//T00A6ASFHD8S/G1FDF4K/a3zfKsadfsrScxgadfsdafOIgIvgW
</code>```

But I got the below error, unable to figure out

答:
I finally figured out after long struggle ...

There was a bug in SlackWebhookOperator in Airflow≤1.10.3 (Bug Jira Issue). This was fixed in 1.10.4 with this PR (fix commit).

Title: Airflow Slack failed to send Message

Body:
I am trying to achieve Airflow integration with Slack,
have received the webhook URL, and created the connection as below. Why is it showing google.com ??

Why is it using the default http_conn_id and connecting to google ??

But got an error as below

ERROR - Error in sending a message to Slack channel #airflow-alerts
            by Airflow: 404:Not Found

{base_hook.py:83} INFO - Using connection to: id: http_default. Host: https://www.google.com/, Port: None, Schema: None, Login: None, Password: None, extra: {}
{logging_mixin.py:95} INFO - [2020-05-29 12:43:21,374] {http_hook.py:128} INFO - Sending 'POST' to url: https://www.google.com//T00A6ASFHD8S/G1FDF4K/a3zfKsadfsrScxgadfsdafOIgIvgW

requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://www.google.com//T00A6ASFHD8S/G1FDF4K/a3zfKsadfsrScxgadfsdafOIgIvgW

But I got the below error, unable to figure out


问:
The servlet does not show all the match results from joining two tables
I have the field in my JSP <c:param name="names" value="${tempstudent.name}"/> for showing the user name and my servlet take this field by String names=request.getParameter("names") and send it to the student_db_util  class in the method named public List <studentrgister> showcourse(String names) as a parameter  which has a task to take a names and use it in my sql query to show match result from 2 tables(mytest table which has a firstName,lastName, id column and class table which has an id, class column). the problem for this app is that in both tables there is more than one match result when I join both tables but my app only show on match result in my JSP page

```<code><body>
<table>
<form action="studentregister" method="get">

                        <input type="hidden" name ="comand" value="seecourse"/>

<c:forEach var="tempstudent" items="${mycourse}">
                                                <td >${tempstudent.name}</td>
</c:forEach>
</form>
</table>
</code>```

jsp page that names field located

```<code><form action="studentregister" method="get">
                        <input type="hidden" name="command" value="pass" />
<table>
<c:forEach var="tempstudent" items="${studentlist}">
<c:url var="seecourse" value="studentregister">
            <c:param name="command" value="seecourse"/>
            <c:param name="names" value="${tempstudent.name}"/>
            </c:url>
                        <td >${tempstudent.email}</td>
                                                <td >${tempstudent.name}</td>
                                                <a href="${seecourse}"
                        >
                        seecourse</a>

</c:forEach>
</table>
</form>

</code>```

servlet method

```<code>    private void seecourse(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String names=request.getParameter("names");
        student_db_util.showcourse(names);
        List<studentrgister> student=student_db_util.showcourse(names);
        request.setAttribute("mycourse", student);
        RequestDispatcher rd=request.getRequestDispatcher("/showcourse.jsp");
        rd.forward(request,response);
    }
</code>```

method in student_db_util class

```<code>public List <studentrgister> showcourse(String names) throws Exception {
        List<studentrgister> students = new ArrayList<>();
         String connectionURL = "jdbc:mysql://localhost:3306/web_student_tracker";
          System.out.println("loding the driver");
          Statement s=null;

        studentrgister mystudent=null;
        Connection myConn = null;
        myConn= DriverManager.getConnection(connectionURL, "webstudent", "webstudent");
      System.out.println("username and password is correect");

        PreparedStatement myStmt=null;
        ResultSet myRs = null;
        String  name=names;
try {
      Class.forName("com.mysql.jdbc.Driver");
          System.out.println("driver is loaded");
    //myConn = dataSource.getConnection();
        String sql = "SELECT mytest.firstName,class.name FROM mytest "
                 + "INNER JOIN class ON mytest.id=class.id "
                 + "where mytest.firstName = ? " ;
                PreparedStatement ps = myConn.prepareStatement(sql);
                ps.setString(1,name);
    myRs=ps.executeQuery();
    if (myRs.next()) {
        String classname = myRs.getString("name");
        //String numbername=myRs.getString("firstName");
        mystudent = new studentrgister(classname);
        students.add(mystudent);
        }
        else {
            throw new Exception("Could not find student id: " );
        }

        return students;
}
        finally {
            close(myConn,myStmt,null);

        }

    }
</code>```

答:
This List declaration is inside the method but the method returns the variable,
i assume the students variable should be outside the method in an accessible scope to be used. You should declare the List globally in the class so it can be accessed outside the method or if you have another students variable outside to return to it cannot return the local scoped variable declared in the method.</p>

```<code>List<studentrgister> students = new ArrayList<>();
</code>```

Body:
I have the field in my JSP <c:param name="names" value="${tempstudent.name}"/> for showing the user name and my servlet take this field by String names=request.getParameter("names") and send it to the student_db_util  class in the method named public List <studentrgister> showcourse(String names) as a parameter  which has a task to take a names and use it in my sql query to show match result from 2 tables(mytest table which has a firstName,lastName, id column and class table which has an id, class column). the problem for this app is that in both tables there is more than one match result when I join both tables but my app only show on match result in my JSP page

<form action="studentregister" method="get">

                        <input type="hidden" name ="comand" value="seecourse"/>

<c:forEach var="tempstudent" items="${mycourse}">
                                                ${tempstudent.name}
</c:forEach>
</form>

jsp page that names field located

<form action="studentregister" method="get">
                        <input type="hidden" name="command" value="pass" />

<c:forEach var="tempstudent" items="${studentlist}">
<c:url var="seecourse" value="studentregister">
            <c:param name="command" value="seecourse"/>
            <c:param name="names" value="${tempstudent.name}"/>
            </c:url>
                        ${tempstudent.email}
                                                ${tempstudent.name}

                        seecourse

</c:forEach>

</form>

servlet method

    private void seecourse(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String names=request.getParameter("names");
        student_db_util.showcourse(names);
        List<studentrgister> student=student_db_util.showcourse(names);
        request.setAttribute("mycourse", student);
        RequestDispatcher rd=request.getRequestDispatcher("/showcourse.jsp");
        rd.forward(request,response);
    }

method in student_db_util class

public List <studentrgister> showcourse(String names) throws Exception {
        List<studentrgister> students = new ArrayList<>();
         String connectionURL = "jdbc:mysql://localhost:3306/web_student_tracker";
          System.out.println("loding the driver");
          Statement s=null;

        studentrgister mystudent=null;
        Connection myConn = null;
        myConn= DriverManager.getConnection(connectionURL, "webstudent", "webstudent");
      System.out.println("username and password is correect");

        PreparedStatement myStmt=null;
        ResultSet myRs = null;
        String  name=names;
try {
      Class.forName("com.mysql.jdbc.Driver");
          System.out.println("driver is loaded");
    //myConn = dataSource.getConnection();
        String sql = "SELECT mytest.firstName,class.name FROM mytest "
                 + "INNER JOIN class ON mytest.id=class.id "
                 + "where mytest.firstName = ? " ;
                PreparedStatement ps = myConn.prepareStatement(sql);
                ps.setString(1,name);
    myRs=ps.executeQuery();
    if (myRs.next()) {
        String classname = myRs.getString("name");
        //String numbername=myRs.getString("firstName");
        mystudent = new studentrgister(classname);
        students.add(mystudent);
        }
        else {
            throw new Exception("Could not find student id: " );
        }

        return students;
}
        finally {
            close(myConn,myStmt,null);

        }

    }

Body:
This List declaration is inside the method but the method returns the variable,
i assume the students variable should be outside the method in an accessible scope to be used. You should declare the List globally in the class so it can be accessed outside the method or if you have another students variable outside to return to it cannot return the local scoped variable declared in the method.

List<studentrgister> students = new ArrayList<>();


问:
How to make the overflow CSS property work with hidden as value
I am having a tough time with overflow: hidden.

Basically, I am trying to hide the overflow of an unordered list which is located in a
.

I have no idea why this isn't working though.

Instead of hiding it, it breaks my list from a horizontal layout to a vertical layout.

The unordered list is carousel and the container is list.

Below is my CSS code;

```<code>div.body .container .images {
    background: url(/images/images-background.jpg);
    height: 62px;
    margin-bottom: 17px;
    width: 384px;
}
div.body .container .images #images-previous {
    cursor: pointer;
    float: left;
}
div.body .container .images #images-next {
    cursor: pointer;
    float: left;
}
div.body .container .images .list {
    float: left;
    overflow: hidden;
    vertical-align: top;
    width: 336px;
}
div.body .container .images .carousel {
    margin-bottom: 6px;
    margin-top: 8px;
    width: 336px;
}
</code>```

Here, my HTML;

```<code><div class="images">
    <div id="images-previous">
        <img src="/images/images-previous.jpg" width="24" height="62" alt="Previous" />
    </div>
    <div class="list">
        <ul class="carousel">
            <li>
                <img src="/photogallery/23.jpg" width="44" height="44" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="thumbnail" />
                <img src="/images/carousel-image-holder-over.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="over" />
                <img src="/images/carousel-image-holder.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="under" />
            </li>
            <li>
                <img src="/photogallery/23.jpg" width="44" height="44" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="thumbnail" />
                <img src="/images/carousel-image-holder-over.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="over" />
                <img src="/images/carousel-image-holder.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="under" />
            </li>
            <li>
                <img src="/photogallery/23.jpg" width="44" height="44" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="thumbnail" />
                <img src="/images/carousel-image-holder-over.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="over" />
                <img src="/images/carousel-image-holder.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="under" />
            </li>
            <li>
                <img src="/photogallery/23.jpg" width="44" height="44" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="thumbnail" />
                <img src="/images/carousel-image-holder-over.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="over" />
                <img src="/images/carousel-image-holder.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="under" />
            </li>
            <li>
                <img src="/photogallery/23.jpg" width="44" height="44" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="thumbnail" />
                <img src="/images/carousel-image-holder-over.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="over" />
                <img src="/images/carousel-image-holder.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="under" />
            </li>
            <li>
                <img src="/photogallery/23.jpg" width="44" height="44" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="thumbnail" />
                <img src="/images/carousel-image-holder-over.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="over" />
                <img src="/images/carousel-image-holder.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="under" />
            </li>
            <li>
                <img src="/photogallery/23.jpg" width="44" height="44" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="thumbnail" />
                <img src="/images/carousel-image-holder-over.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="over" />
                <img src="/images/carousel-image-holder.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="under" />
            </li>
            <li>
                <img src="/photogallery/23.jpg" width="44" height="44" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="thumbnail" />
                <img src="/images/carousel-image-holder-over.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="over" />
                <img src="/images/carousel-image-holder.png" width="49" height="48" alt="Cross Bottle 8.5" Frosted/Amber/Chain/Fleur di Lis" class="under" />
            </li>
            <!--
            <cfset i=1>
                <cfloop condition="i lte images.recordcount">
                    <cfoutput>
                        <li>
                            <img src="#images.thumburl[i]#" width="44" height="44" alt="#images.alt[i]#" class="thumbnail" />
                            <img src="/images/carousel-image-holder-over.png" width="49" height="48" alt="#images.alt[i]#" class="over" />
                            <img src="/images/carousel-image-holder.png" width="49" height="48" alt="#images.alt[i]#" class="under" />
                        </li>
                    </cfoutput>
                    <cfset i=i+1>
                </cfloop>
            </cfset>
            -->
        </ul>
    </div>
    <div id="images-next">
        <img src="/images/images-next.jpg" width="24" height="62" alt="Next" />
    </div>
<div class="clear"></div>
</code>```

答:
This worked for me

```<code><div style="display: flex; position: absolute; width: 100%;">
  <div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
  </div>
</div>
</code>```

Adding position:absolute to the parent container made it work.

PS: This is for anyone looking for a solution to dynamically truncating text.

EDIT: This was meant to be an answer for this question but since they are related and it could help someone on this question I shall also leave it here instead of deleting it.

Body:
I am having a tough time with overflow: hidden.

Basically, I am trying to hide the overflow of an unordered list which is located in a
.

I have no idea why this isn't working though.

Instead of hiding it, it breaks my list from a horizontal layout to a vertical layout.

The unordered list is carousel and the container is list.

Below is my CSS code;

div.body .container .images {
    background: url(/images/images-background.jpg);
    height: 62px;
    margin-bottom: 17px;
    width: 384px;
}
div.body .container .images #images-previous {
    cursor: pointer;
    float: left;
}
div.body .container .images #images-next {
    cursor: pointer;
    float: left;
}
div.body .container .images .list {
    float: left;
    overflow: hidden;
    vertical-align: top;
    width: 336px;
}
div.body .container .images .carousel {
    margin-bottom: 6px;
    margin-top: 8px;
    width: 336px;
}

Here, my HTML;

Body:
This worked for me

<div style="display: flex; position: absolute; width: 100%;">
  <div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
  </div>
</div>

Adding position:absolute to the parent container made it work.

PS: This is for anyone looking for a solution to dynamically truncating text.

EDIT: This was meant to be an answer for this question but since they are related and it could help someone on this question I shall also leave it here instead of deleting it.


问:
@Query keep pulling null from database
I am currently having what I'd like to call as Code Block (Writer block but with coding). I have tried to check many times and make sure that everything is in the proper place but it keeps getting me a null despite the data that I ask in the @Query is exist.

This is the @Query that I currently have,

```<code>@Query(value = "select d.denda from data_transaksi_model d WHERE d.tanggal=:x AND d.nama_wp = :y AND d.masa_pajak=:z", nativeQuery = true)
    String findAllDenda(String x,String y,String z);
</code>```

My expected output from there is a collection of "denda" from the table of "data_transaksi_model" which has the specific "tanggal", "name", and "masa_pajak" from that table. I have double checked the table that is created within the database and it has the same name as to what I inquire there,

As you can see, the table name is matchup and the name of the column name that has the name of what I want in my query is also match up. Just to make sure, I also check the structure of the database and it is indeed a string, also the same with others.

The table is the byproduct of the model from my Spring Boot's project that I have made.

```<code>
@Entity
public class DataTransaksiModel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @NotNull
    @Column(name = "tanggal")
    private String tanggal;

    @NotNull
    @Column(name = "no_kohir")
    private String noKohir;

    @NotNull
    @Column(name = "no_urut")
    private String noUrut;

    @NotNull
    @Column(name = "nama_wp")
    private String namaWP;

    @NotNull
    @Column(name = "jam")
    private String jam;

    @NotNull
    @Column(name = "nop")
    private String nop;

    @NotNull
    @Column(name = "denda")
    private String denda;

    @NotNull
    @Column(name = "jumlah_setoran")
    private String jumlahSetoran;

    @NotNull
    @Column(name = "luas_tanah")
    private String luasTanah;

    @NotNull
    @Column(name = "luas_bangunan")
    private String luasBangunan;

    @NotNull
    @Column(name = "kecamatan")
    private String kecamatan;

    @NotNull
    @Column(name = "kelurahan")
    private String kelurahan;

    @NotNull
    @Column(name = "masa_pajak")
    private String masaPajak;

    @NotNull
    @Column(name = "lokasi")
    private String lokasi;

    @NotNull
    @Column(name = "pokok")
    private String pokok;

    @NotNull
    @Column(name = "cabang")
    private String cabang;

    @NotNull
    @Column(name = "User")
    private String user;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTanggal() {
        return tanggal;
    }

    public void setTanggal(String tanggal) {
        this.tanggal = tanggal;
    }

    public String getNoKohir() {
        return noKohir;
    }

    public void setNoKohir(String noKohir) {
        this.noKohir = noKohir;
    }

    public String getNoUrut() {
        return noUrut;
    }

    public void setNoUrut(String noUrut) {
        this.noUrut = noUrut;
    }

    public String getNamaWP() {
        return namaWP;
    }

    public void setNamaWP(String namaWP) {
        this.namaWP = namaWP;
    }

    public String getJam() {
        return jam;
    }

    public void setJam(String jam) {
        this.jam = jam;
    }

    public String getNop() {
        return nop;
    }

    public void setNop(String nop) {
        this.nop = nop;
    }

    public String getDenda() {
        return denda;
    }

    public void setDenda(String denda) {
        this.denda = denda;
    }

    public String getJumlahSetoran() {
        return jumlahSetoran;
    }

    public void setJumlahSetoran(String jumlahSetoran) {
        this.jumlahSetoran = jumlahSetoran;
    }

    public String getLuasTanah() {
        return luasTanah;
    }

    public void setLuasTanah(String luasTanah) {
        this.luasTanah = luasTanah;
    }

    public String getLuasBangunan() {
        return luasBangunan;
    }

    public void setLuasBangunan(String luasBangunan) {
        this.luasBangunan = luasBangunan;
    }

    public String getKecamatan() {
        return kecamatan;
    }

    public void setKecamatan(String kecamatan) {
        this.kecamatan = kecamatan;
    }

    public String getKelurahan() {
        return kelurahan;
    }

    public void setKelurahan(String kelurahan) {
        this.kelurahan = kelurahan;
    }

    public String getMasaPajak() {
        return masaPajak;
    }

    public void setMasaPajak(String masaPajak) {
        this.masaPajak = masaPajak;
    }

    public String getLokasi() {
        return lokasi;
    }

    public void setLokasi(String lokasi) {
        this.lokasi = lokasi;
    }

    public String getPokok() {
        return pokok;
    }

    public void setPokok(String pokok) {
        this.pokok = pokok;
    }

    public String getCabang() {
        return cabang;
    }

    public void setCabang(String cabang) {
        this.cabang = cabang;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
}
</code>```

With that finished, I insert a data dummy into the database as the following.

Therefore, I tried to put the input of tanggal with "1170130", nama_wp with "SURATNO" and masa_pajak with "2016". However, I keep getting null instead of "9.166" in the collection. Where did I do wrong? I am using XAMPP, MySQL, and Spring Boot for this project.

/EDIT: I tried it manually in my XAMPP with SELECT denda FROM data_transaksi_modelWHERE nama_wp="SURATNO" AND masa_pajak="2014" AND tanggal="1170130" and it actually gives me a return

However, when I do it in my spring boot project it still return null.

//Edit2: I am using IntelliJ as my IDE and there is a warning (not an error) within the @Query annotation. It is said that "No data sources are configured to run this SQL and provide advanced code assistance. Disable this inspection via problem menu (alt+enter)" there is also a warning that said, "SQL dialect is not configured". If that is the source of the problem, how to fix it?

///edit3: I tried to fix around the query and it doesn't show the result that I wanted. This is the service that I am using for the repository

```<code>    @Autowired
    DataTransaksiDb dataTransaksiDb;

    @Override
    public List<String> getDenda(String tanggal, String nama, String masaPajak){
        // TODO Auto-generated method stub
        return dataTransaksiDb.findAllDenda(tanggal, nama, masaPajak);
    }
</code>```

and this is the controller where I am using the service. The controller is using a multipart file where the data is taken out from the CSV that is uploaded where within the CSV has the table that is the same as the database.

```<code> @PostMapping("/uploadFile")
    public static void uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
        if (file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) {
            InputStreamReader input = new InputStreamReader(file.getInputStream());
            CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(input);
            for (CSVRecord record : csvParser) {
                String nama = record.get("nama_wp");
                String masa = record.get("masa_pajak");
                String tanggal = record.get("tanggal");
                String denda = record.get("denda");
                String jumlahSetoran = record.get("jumlah_setoran");
                String pokok = record.get("pokok");
                String luasTanah = record.get("luas_tanah");
                String luasBangunan = record.get("luas_bangunan");

                try {
                    System.err.println(tanggal + "\n" + nama + "\n" + masa);
                    List<String> results = rekonsiliasiService.getDenda(tanggal, nama, masa);
                    System.err.println("results " + results);
                } catch (NullPointerException e) {
                    System.err.println(e);
                }

            }

            response.sendRedirect("/rekonsiliasi");
        } else {
            response.sendRedirect("/rekonsiliasi");
        }
    }
</code>```

Whatever the result of the input that I get, it keep getting catches by the nullpointerexception

////EDIT4:
I tried debugging it and from my controller, I tried to do System.err.println(rekonsiliasiService.getDenda(tanggal,nama,masa)); and it keep me getting a NullPointerException. Then I tried to see if the problem is the input of the parameter itself within the service

```<code>@Override
    public List<String> getDenda(String tanggal, String nama, String masaPajak){
        // TODO Auto-generated method stub
        System.err.println("tanggal " + tanggal + "\n" + "nama " + nama + "\n" + "masaPajak " + masaPajak);
        return dataTransaksiDb.findAllDenda(tanggal, nama, masaPajak);
    }
</code>```

It never reached to the System.err.println("tanggal " + tanggal + "\n" + "nama " + nama + "\n" + "masaPajak " + masaPajak); within my Service layer.

答:
try this :

```<code>@Query(value = "select d.denda from DataTransaksiModel d WHERE d.tanggal=:x AND d.namaWP = :y AND d.masaPajak=:z")
    List<String> findAllDenda(@Param("x")String x, @Param("y")String y,@Param("z") String z);
</code>```

if it didn't work try this :

```<code>@Query(value = "select d.denda from data_transaksi_model d WHERE d.tanggal=:x AND d.nama_wp = :y AND d.masa_pajak=:z", nativeQuery = true)
    List<String> findAllDenda(@Param("x")String x, @Param("y")String y,@Param("z") String z);
</code>```

Title: @Query keep pulling null from database

Body:
I am currently having what I'd like to call as Code Block (Writer block but with coding). I have tried to check many times and make sure that everything is in the proper place but it keeps getting me a null despite the data that I ask in the @Query is exist.

This is the @Query that I currently have,

@Query(value = "select d.denda from data_transaksi_model d WHERE d.tanggal=:x AND d.nama_wp = :y AND d.masa_pajak=:z", nativeQuery = true)
    String findAllDenda(String x,String y,String z);

My expected output from there is a collection of "denda" from the table of "data_transaksi_model" which has the specific "tanggal", "name", and "masa_pajak" from that table. I have double checked the table that is created within the database and it has the same name as to what I inquire there,

As you can see, the table name is matchup and the name of the column name that has the name of what I want in my query is also match up. Just to make sure, I also check the structure of the database and it is indeed a string, also the same with others.

The table is the byproduct of the model from my Spring Boot's project that I have made.

@Entity
public class DataTransaksiModel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @NotNull
    @Column(name = "tanggal")
    private String tanggal;

    @NotNull
    @Column(name = "no_kohir")
    private String noKohir;

    @NotNull
    @Column(name = "no_urut")
    private String noUrut;

    @NotNull
    @Column(name = "nama_wp")
    private String namaWP;

    @NotNull
    @Column(name = "jam")
    private String jam;

    @NotNull
    @Column(name = "nop")
    private String nop;

    @NotNull
    @Column(name = "denda")
    private String denda;

    @NotNull
    @Column(name = "jumlah_setoran")
    private String jumlahSetoran;

    @NotNull
    @Column(name = "luas_tanah")
    private String luasTanah;

    @NotNull
    @Column(name = "luas_bangunan")
    private String luasBangunan;

    @NotNull
    @Column(name = "kecamatan")
    private String kecamatan;

    @NotNull
    @Column(name = "kelurahan")
    private String kelurahan;

    @NotNull
    @Column(name = "masa_pajak")
    private String masaPajak;

    @NotNull
    @Column(name = "lokasi")
    private String lokasi;

    @NotNull
    @Column(name = "pokok")
    private String pokok;

    @NotNull
    @Column(name = "cabang")
    private String cabang;

    @NotNull
    @Column(name = "User")
    private String user;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTanggal() {
        return tanggal;
    }

    public void setTanggal(String tanggal) {
        this.tanggal = tanggal;
    }

    public String getNoKohir() {
        return noKohir;
    }

    public void setNoKohir(String noKohir) {
        this.noKohir = noKohir;
    }

    public String getNoUrut() {
        return noUrut;
    }

    public void setNoUrut(String noUrut) {
        this.noUrut = noUrut;
    }

    public String getNamaWP() {
        return namaWP;
    }

    public void setNamaWP(String namaWP) {
        this.namaWP = namaWP;
    }

    public String getJam() {
        return jam;
    }

    public void setJam(String jam) {
        this.jam = jam;
    }

    public String getNop() {
        return nop;
    }

    public void setNop(String nop) {
        this.nop = nop;
    }

    public String getDenda() {
        return denda;
    }

    public void setDenda(String denda) {
        this.denda = denda;
    }

    public String getJumlahSetoran() {
        return jumlahSetoran;
    }

    public void setJumlahSetoran(String jumlahSetoran) {
        this.jumlahSetoran = jumlahSetoran;
    }

    public String getLuasTanah() {
        return luasTanah;
    }

    public void setLuasTanah(String luasTanah) {
        this.luasTanah = luasTanah;
    }

    public String getLuasBangunan() {
        return luasBangunan;
    }

    public void setLuasBangunan(String luasBangunan) {
        this.luasBangunan = luasBangunan;
    }

    public String getKecamatan() {
        return kecamatan;
    }

    public void setKecamatan(String kecamatan) {
        this.kecamatan = kecamatan;
    }

    public String getKelurahan() {
        return kelurahan;
    }

    public void setKelurahan(String kelurahan) {
        this.kelurahan = kelurahan;
    }

    public String getMasaPajak() {
        return masaPajak;
    }

    public void setMasaPajak(String masaPajak) {
        this.masaPajak = masaPajak;
    }

    public String getLokasi() {
        return lokasi;
    }

    public void setLokasi(String lokasi) {
        this.lokasi = lokasi;
    }

    public String getPokok() {
        return pokok;
    }

    public void setPokok(String pokok) {
        this.pokok = pokok;
    }

    public String getCabang() {
        return cabang;
    }

    public void setCabang(String cabang) {
        this.cabang = cabang;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
}

With that finished, I insert a data dummy into the database as the following.

Therefore, I tried to put the input of tanggal with "1170130", nama_wp with "SURATNO" and masa_pajak with "2016". However, I keep getting null instead of "9.166" in the collection. Where did I do wrong? I am using XAMPP, MySQL, and Spring Boot for this project.

/EDIT: I tried it manually in my XAMPP with SELECT denda FROM data_transaksi_modelWHERE nama_wp="SURATNO" AND masa_pajak="2014" AND tanggal="1170130" and it actually gives me a return

However, when I do it in my spring boot project it still return null.

//Edit2: I am using IntelliJ as my IDE and there is a warning (not an error) within the @Query annotation. It is said that "No data sources are configured to run this SQL and provide advanced code assistance. Disable this inspection via problem menu (alt+enter)" there is also a warning that said, "SQL dialect is not configured". If that is the source of the problem, how to fix it?

///edit3: I tried to fix around the query and it doesn't show the result that I wanted. This is the service that I am using for the repository

    @Autowired
    DataTransaksiDb dataTransaksiDb;

    @Override
    public List<String> getDenda(String tanggal, String nama, String masaPajak){
        // TODO Auto-generated method stub
        return dataTransaksiDb.findAllDenda(tanggal, nama, masaPajak);
    }

and this is the controller where I am using the service. The controller is using a multipart file where the data is taken out from the CSV that is uploaded where within the CSV has the table that is the same as the database.

 @PostMapping("/uploadFile")
    public static void uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
        if (file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) {
            InputStreamReader input = new InputStreamReader(file.getInputStream());
            CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(input);
            for (CSVRecord record : csvParser) {
                String nama = record.get("nama_wp");
                String masa = record.get("masa_pajak");
                String tanggal = record.get("tanggal");
                String denda = record.get("denda");
                String jumlahSetoran = record.get("jumlah_setoran");
                String pokok = record.get("pokok");
                String luasTanah = record.get("luas_tanah");
                String luasBangunan = record.get("luas_bangunan");

                try {
                    System.err.println(tanggal + "\n" + nama + "\n" + masa);
                    List<String> results = rekonsiliasiService.getDenda(tanggal, nama, masa);
                    System.err.println("results " + results);
                } catch (NullPointerException e) {
                    System.err.println(e);
                }

            }

            response.sendRedirect("/rekonsiliasi");
        } else {
            response.sendRedirect("/rekonsiliasi");
        }
    }

Whatever the result of the input that I get, it keep getting catches by the nullpointerexception

////EDIT4:
I tried debugging it and from my controller, I tried to do System.err.println(rekonsiliasiService.getDenda(tanggal,nama,masa)); and it keep me getting a NullPointerException. Then I tried to see if the problem is the input of the parameter itself within the service

@Override
    public List<String> getDenda(String tanggal, String nama, String masaPajak){
        // TODO Auto-generated method stub
        System.err.println("tanggal " + tanggal + "\n" + "nama " + nama + "\n" + "masaPajak " + masaPajak);
        return dataTransaksiDb.findAllDenda(tanggal, nama, masaPajak);
    }

It never reached to the System.err.println("tanggal " + tanggal + "\n" + "nama " + nama + "\n" + "masaPajak " + masaPajak); within my Service layer.

Body:
try this :

@Query(value = "select d.denda from DataTransaksiModel d WHERE d.tanggal=:x AND d.namaWP = :y AND d.masaPajak=:z")
    List<String> findAllDenda(@Param("x")String x, @Param("y")String y,@Param("z") String z);

if it didn't work try this :

@Query(value = "select d.denda from data_transaksi_model d WHERE d.tanggal=:x AND d.nama_wp = :y AND d.masa_pajak=:z", nativeQuery = true)
    List<String> findAllDenda(@Param("x")String x, @Param("y")String y,@Param("z") String z);


问:
Is there a way to control the order of child entity, when using one-to-many relationhips?
According to https://developer.android.com/training/data-storage/room/relationships

We can have one-to-many relationships

```<code>public class UserWithPlaylists {
    @Embedded public User user;
    @Relation(
         parentColumn = "userId",
         entityColumn = "userCreatorId"
    )
    public List<Playlist> playlists;
}

@Transaction
@Query("SELECT * FROM User")
public List<UserWithPlaylists> getUsersWithPlaylists();
</code>```

In both entity User and Playlist, we have added a column named sort_key

The purpose is, when we perform query, we can do the following

```<code>@Transaction
@Query("SELECT * FROM User order by sort_key")
public List<UserWithPlaylists> getUsersWithPlaylists();
</code>```

We can control the order of List<UserWithPlaylists>.

But, how about List<Playlist> playlists child entity?

How can we define a custom query for child entity Playlist, so that we can have control over List<Playlist> playlists ordering?

答:
I'm not sure It is possible to add @Query to a field but what i'm sure is that you can use a particular collection to make the order. These are the steps:

Make the Playlist entity emplements Comparable interface, then define the compareTo method following the sort_key attribute.

Instead of list in UserWithPlaylists entity, use SortedSet or TreeSet this particular collection returns items ordered using natural order or Comparator.

Body:
According to https://developer.android.com/training/data-storage/room/relationships

We can have one-to-many relationships

public class UserWithPlaylists {
    @Embedded public User user;
    @Relation(
         parentColumn = "userId",
         entityColumn = "userCreatorId"
    )
    public List<Playlist> playlists;
}

@Transaction
@Query("SELECT * FROM User")
public List<UserWithPlaylists> getUsersWithPlaylists();

In both entity User and Playlist, we have added a column named sort_key

The purpose is, when we perform query, we can do the following

@Transaction
@Query("SELECT * FROM User order by sort_key")
public List<UserWithPlaylists> getUsersWithPlaylists();

We can control the order of List<UserWithPlaylists>.

But, how about List<Playlist> playlists child entity?

How can we define a custom query for child entity Playlist, so that we can have control over List<Playlist> playlists ordering?


问:
bash: pip: command not found
I downloaded pip and ran python setup.py install and everything worked just fine. The very next step in the tutorial is to run pip install <lib you want> but before it even tries to find anything online I get an error "bash: pip: command not found".

This is on Mac OS X. I'm assuming there's some kind of path setting that was not set correctly when I ran setup.py. How can I investigate further? What do I need to check to get a better idea of the exact cause of the problem?

EDIT: I also tried installing Python 2.7 for Mac in the hopes that the friendly install process would do any housekeeping like editing PATH and whatever else needs to happen for everything to work according to the tutorials, but this didn't work. After installing, running 'python' still ran Python 2.6 and PATH was not updated.

答:
The problem seems that your python version and the library yoıu want to install is not matching versionally. Ex: If Django is Django3 and your python version is 2.7, you may get this error.

"After installing is running 'python' still ran Python 2.6 and PATH was not updated."

1- Install latest version of Python
2- Change your PATH manually as python38 and compare them.
3- Try to reinstall.

I solved this problem as replacing PATH manually with the latest version of Python.
As for Windows:   ;C:\python38\Scripts

Title: bash: pip: command not found


问:
Query to count record with one query based on multiple and different where condition?
I am having a problem with my laravel count code, Please check the code to count the record.

```<code>       /**
        *
        *These Are constants
        *Record::StatusVerified = 1
        *Record::StatusReject = 2
        *Record::StatusUnverified = 0
        *
        */
        $allCity = City::get();
        $rowData = [];
        foreach ($allCity as $val) {
            $content = [];
            $record  = Records::where(['city' => $val->id]);
       // other filters

            $statusVerified = $record->where(['status' => Record::StatusVerified])->count();
            $statusRejected = $record->where(['status' => Record::StatusReject])->count();
            $statusUnverified = $record->where(['status' => Record::StatusUnverified])->count();
            $content['verified'] = $statusVerified;
            $content['Rejected'] = $statusRejected;
            $content['Unverified'] = $statusUnverified;
            $rowData[] = $content;
        }

        //pur row to CSV file
</code>```

In this code I am trying to get count of record based on city and count of total record with where condition of status.
But only the first count give correct record but other give zero(0) count.
I try to put $record variable into another variable and then try to get count but still the same problem.

```<code>$newVariable = $record;
$content['verified'] = $newVariable->where(['status' => Record::StatusVerified])->count();
$content['Rejected'] = $newVariable->where(['status' => Record::StatusRejected])->count();
$content['Unverified'] = $newVariable->where(['status' => Record::StatusUnverified])->count();
</code>```

I even created 3 variable $verified, $unverified and $rejected and then assign variable $record to them then try to get count with these 3 variable.

```<code>$verified = $unverified = $rejected = $record;
$content['verified'] = $verified->where(['status' => Record::StatusVerified])->count();
$content['Rejected'] = $rejected->where(['status' => Record::StatusRejected])->count();
$content['Unverified'] = $unverified->where(['status' => Record::StatusUnverified])->count();
</code>```

But still it give me correct in first one and zero(0) in other two.
So I have to write full query for all 3 record, I can use other function to call full query with variable pass but I have a situation that I can't becase so many other filter are included in the query and if I do create new function with so many variable pass the code will look ugly.

答:
I believe that the problem is this:

```<code>$verified = $unverified = $rejected = $record;
</code>```

All those variables refer to the same query object. Now this first line is gonna work:

```<code>$content['verified'] = $verified->where(['status' => Record::StatusVerified])->count();
</code>```

However, in the second statement:

```<code>$content['Rejected'] = $rejected->where(['status' => Record::StatusRejected])->count();
</code>```

It doesn't work because $verified and $rejected refer to the same query. $rejected add one more condition to the previous query and the underlying query is some thing like this:

```<code>SELECT COUNT(id) FROM records
WHERE city = 'some_city_id'
AND status = 'verified'
AND status = 'rejected'
</code>```

Now the above query clearly return zero, because there's no records that have both statuses.

The best approach in my opinion is simply use group by:

```<code>SELECT COUNT(id), status FROM records
GROUP BY status
WHERE city = 'some_city_id'
AND status in (‘verified', ‘rejected’, ‘unverified’)
</code>```

Or a "quick and dirty" approach (which I don't recommend) is to clone the initial query:

```<code>$verified = clone $record;
$unverified = clone $record;
$rejected = clone $record;
$content['verified'] = $verified->where(['status' => Record::StatusVerified])->count();
$content['Rejected'] = $rejected->where(['status' => Record::StatusRejected])->count();
$content['Unverified'] = $unverified->where(['status' => Record::StatusUnverified])->count();
</code>```

Body:
I am having a problem with my laravel count code, Please check the code to count the record.

       /**
        *
        *These Are constants
        *Record::StatusVerified = 1
        *Record::StatusReject = 2
        *Record::StatusUnverified = 0
        *
        */
        $allCity = City::get();
        $rowData = [];
        foreach ($allCity as $val) {
            $content = [];
            $record  = Records::where(['city' => $val->id]);
       // other filters

            $statusVerified = $record->where(['status' => Record::StatusVerified])->count();
            $statusRejected = $record->where(['status' => Record::StatusReject])->count();
            $statusUnverified = $record->where(['status' => Record::StatusUnverified])->count();
            $content['verified'] = $statusVerified;
            $content['Rejected'] = $statusRejected;
            $content['Unverified'] = $statusUnverified;
            $rowData[] = $content;
        }

        //pur row to CSV file

In this code I am trying to get count of record based on city and count of total record with where condition of status.
But only the first count give correct record but other give zero(0) count.
I try to put $record variable into another variable and then try to get count but still the same problem.

$newVariable = $record;
$content['verified'] = $newVariable->where(['status' => Record::StatusVerified])->count();
$content['Rejected'] = $newVariable->where(['status' => Record::StatusRejected])->count();
$content['Unverified'] = $newVariable->where(['status' => Record::StatusUnverified])->count();

I even created 3 variable $verified, $unverified and $rejected and then assign variable $record to them then try to get count with these 3 variable.

$verified = $unverified = $rejected = $record;
$content['verified'] = $verified->where(['status' => Record::StatusVerified])->count();
$content['Rejected'] = $rejected->where(['status' => Record::StatusRejected])->count();
$content['Unverified'] = $unverified->where(['status' => Record::StatusUnverified])->count();

But still it give me correct in first one and zero(0) in other two.
So I have to write full query for all 3 record, I can use other function to call full query with variable pass but I have a situation that I can't becase so many other filter are included in the query and if I do create new function with so many variable pass the code will look ugly.

Body:
I believe that the problem is this:

$verified = $unverified = $rejected = $record;

All those variables refer to the same query object. Now this first line is gonna work:

$content['verified'] = $verified->where(['status' => Record::StatusVerified])->count();

However, in the second statement:

$content['Rejected'] = $rejected->where(['status' => Record::StatusRejected])->count();

It doesn't work because $verified and $rejected refer to the same query. $rejected add one more condition to the previous query and the underlying query is some thing like this:

SELECT COUNT(id) FROM records
WHERE city = 'some_city_id'
AND status = 'verified'
AND status = 'rejected'

Now the above query clearly return zero, because there's no records that have both statuses.

The best approach in my opinion is simply use group by:

SELECT COUNT(id), status FROM records
GROUP BY status
WHERE city = 'some_city_id'
AND status in (‘verified', ‘rejected’, ‘unverified’)

Or a "quick and dirty" approach (which I don't recommend) is to clone the initial query:

$verified = clone $record;
$unverified = clone $record;
$rejected = clone $record;
$content['verified'] = $verified->where(['status' => Record::StatusVerified])->count();
$content['Rejected'] = $rejected->where(['status' => Record::StatusRejected])->count();
$content['Unverified'] = $unverified->where(['status' => Record::StatusUnverified])->count();


问:
How to fix an extensive echoing while recording audio using navigator.mediaDevices.getUserMedia?
So, I am working on a small electron desktop app that captures desktop screen and records video and audio.
When I am trying to add audio to the stream it starts echoing really badly and I am not sure why.

I am using:

Windows 10 PRO 18362.778

Chrome 81.0.4044.113

Electron 8.2.3

Here is some code.

I create these constraints when I want to capture and record video only:

```<code>const constraints = {
        audio: false,
        video: {
            mandatory: {
                chromeMediaSource: 'desktop',
                chromeMediaSourceId: source.id
            }
        }
    }
</code>```

Then I pass is to the stream like that:

const stream = await navigator.mediaDevices.getUserMedia(constraints)

It works like a charm. However when I start adding audio it gives me echo:

```<code>const constraints = {
        audio: {
            mandatory: {
                chromeMediaSource: 'desktop',
            }
        },
        video: {
            mandatory: {
                chromeMediaSource: 'desktop',
            }
        }
    }
</code>```

Also, I can't just set the audio to true. It then gives me this error:

Uncaught (in promise) DOMException: Error starting screen capture

An interesting fact. When I go to Mozilla documentation page on audio constraints and use the demo button it gives me echo too. I tried doing it on Edge and the result was better, but still had echo. So can it be the audio codec?

Here it says that echoCancellation constraint is supported and on by default starting Chrome version 62.

Here is the branch on the Github where I tried to find solution, but failed.

Here is my git repo if you want to look at it more closely.

PS: this is my first post here. Let me know if I did something wrong here and can improve the post. Thank you!

答:
The problem comes from attempting to initiate a single stream of your microphone audio and computer screen video at the same time. To fix this issue, you will need to create an audio stream first, then separately create a video stream that captures your computer screen, and finally, combine the streams into one.

```<code>// create audio and video constraints
const constraintsVideo = {
    audio: false,
    video: {
        mandatory: {
            chromeMediaSource: 'desktop',
            chromeMediaSourceId: source.id
        }
    }
}
const constraintsAudio = {audio: true}

// create audio and video streams separately
const audioStream = await navigator.mediaDevices.getUserMedia(constraintsAudio)
const videoStream = await navigator.mediaDevices.getUserMedia(constraintsVideo)

// combine the streams
const combinedStream = new MediaStream([...videoStream.getVideoTracks(), ...audioStream.getAudioTracks()])
</code>```

After you combine the streams, you can use combinedStream as if it originated as a single stream.

Body:
So, I am working on a small electron desktop app that captures desktop screen and records video and audio.
When I am trying to add audio to the stream it starts echoing really badly and I am not sure why.

I am using:

Windows 10 PRO 18362.778

Chrome 81.0.4044.113

Electron 8.2.3

Here is some code.

I create these constraints when I want to capture and record video only:

const constraints = {
        audio: false,
        video: {
            mandatory: {
                chromeMediaSource: 'desktop',
                chromeMediaSourceId: source.id
            }
        }
    }

Then I pass is to the stream like that:

const stream = await navigator.mediaDevices.getUserMedia(constraints)

It works like a charm. However when I start adding audio it gives me echo:

const constraints = {
        audio: {
            mandatory: {
                chromeMediaSource: 'desktop',
            }
        },
        video: {
            mandatory: {
                chromeMediaSource: 'desktop',
            }
        }
    }

Also, I can't just set the audio to true. It then gives me this error:

Uncaught (in promise) DOMException: Error starting screen capture

An interesting fact. When I go to Mozilla documentation page on audio constraints and use the demo button it gives me echo too. I tried doing it on Edge and the result was better, but still had echo. So can it be the audio codec?

Here it says that echoCancellation constraint is supported and on by default starting Chrome version 62.

Here is the branch on the Github where I tried to find solution, but failed.

Here is my git repo if you want to look at it more closely.

PS: this is my first post here. Let me know if I did something wrong here and can improve the post. Thank you!

Body:
The problem comes from attempting to initiate a single stream of your microphone audio and computer screen video at the same time. To fix this issue, you will need to create an audio stream first, then separately create a video stream that captures your computer screen, and finally, combine the streams into one.

// create audio and video constraints
const constraintsVideo = {
    audio: false,
    video: {
        mandatory: {
            chromeMediaSource: 'desktop',
            chromeMediaSourceId: source.id
        }
    }
}
const constraintsAudio = {audio: true}

// create audio and video streams separately
const audioStream = await navigator.mediaDevices.getUserMedia(constraintsAudio)
const videoStream = await navigator.mediaDevices.getUserMedia(constraintsVideo)

// combine the streams
const combinedStream = new MediaStream([...videoStream.getVideoTracks(), ...audioStream.getAudioTracks()])

After you combine the streams, you can use combinedStream as if it originated as a single stream.


问:
ucwords but ignore words what are in BLOCK capitals?
I was wondering how to format the strings below to uppercase first letter of words but ingore words that are in uppercase already.

Examples

```<code>ABcd Efg = Abcd Efg
abcd EFG = Abcd EFG
</code>```

Could someone please give an example if it is possible.

Thanks

答:
You would need to evaluate each word separately:

```<code>if( strtoupper($word) != $word ){
    $word = ucwords($word);
}
</code>```

This means splitting any strings on spaces and evaluating each part separately.

UPDATE:

Here's a working example:

```<code>// put these into an array to demo the logic
$s1="ABcd Efg";
$s2="abcd EFG";
$words_array = array($s1,$s2);

foreach( $words_array as $words ){
    echo "Old words: $words\n";

    // inline replace of words
    $split_words = explode(" ",$words);
    for( $i=0; $i<count($split_words); $i++ ){
        $word = $split_words[$i];
        if( strtoupper($word) != $word ){
            $split_words[$i] = ucwords(strtolower($word));
        }
    }
    echo "New words: ".implode(" ",$split_words)."\n";
}
</code>```

Body:
I was wondering how to format the strings below to uppercase first letter of words but ingore words that are in uppercase already.

Examples

ABcd Efg = Abcd Efg
abcd EFG = Abcd EFG

Could someone please give an example if it is possible.

Thanks

Body:
You would need to evaluate each word separately:

if( strtoupper($word) != $word ){
    $word = ucwords($word);
}

This means splitting any strings on spaces and evaluating each part separately.

UPDATE:

Here's a working example:

// put these into an array to demo the logic
$s1="ABcd Efg";
$s2="abcd EFG";
$words_array = array($s1,$s2);

foreach( $words_array as $words ){
    echo "Old words: $words\n";

    // inline replace of words
    $split_words = explode(" ",$words);
    for( $i=0; $i<count($split_words); $i++ ){
        $word = $split_words[$i];
        if( strtoupper($word) != $word ){
            $split_words[$i] = ucwords(strtolower($word));
        }
    }
    echo "New words: ".implode(" ",$split_words)."\n";
}


问:
Splitting std::vector of size m into vector of vectors of size n
Given a vector [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
what are some possible approaches to construct [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17]], focusing primarily on readability?

At the moment, I have correctly defined the starting and ending indexes of all the subarrays, and was trying to use std::copy(cam.begin() + start, cam.begin() + end+ 1, vec.begin()); to construct a new vector.. resulting in:

```<code>terminate called after throwing an instance of 'std::bad_alloc'
what():  std::bad_alloc
</code>```

答:
If the vector of vectors is interpreted as a matrix, the first n-1 rows can be filled in a straightforward way by copying segments from the one-dimensional input vector. Only the last row of that "matrix" requires some attention, as it may not be completely filled.

```<code>#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
#include <cmath>

int main() {
  // create initial data
  int vecSize = 17;
  std::vector<int> inVec(vecSize);
  std::iota(inVec.begin(), inVec.end(), 1);

  // prepare new container
  int ncol = 5;
  int nrow = std::ceil(float(vecSize) / float(ncol));
  std::vector<std::vector<int>> outVecVec(nrow);

  // row-wise copy
  for (int i = 0; i < nrow; ++i) {
    int rowLength = ncol;
    if (i == nrow - 1 && vecSize % ncol != 0) {
      rowLength = vecSize % ncol; // length of last row, if not filled
    }
    outVecVec[i].resize(rowLength);
    auto vecIndex = inVec.begin() + i * ncol;
    std::copy(vecIndex, vecIndex + rowLength, outVecVec[i].begin());
  }

  // print output
   for (int i = 0; i < nrow; ++i) {
     for (int j = 0; j < outVecVec[i].size(); ++j)
       std::cout << outVecVec[i][j] << " ";
     std::cout << std::endl;
   }
}
</code>```

demo: https://godbolt.org/z/w9aDrE

Body:
Given a vector [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
what are some possible approaches to construct [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17]], focusing primarily on readability?

At the moment, I have correctly defined the starting and ending indexes of all the subarrays, and was trying to use std::copy(cam.begin() + start, cam.begin() + end+ 1, vec.begin()); to construct a new vector.. resulting in:

terminate called after throwing an instance of 'std::bad_alloc'
what():  std::bad_alloc

Body:
If the vector of vectors is interpreted as a matrix, the first n-1 rows can be filled in a straightforward way by copying segments from the one-dimensional input vector. Only the last row of that "matrix" requires some attention, as it may not be completely filled.

#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
#include <cmath>

int main() {
  // create initial data
  int vecSize = 17;
  std::vector<int> inVec(vecSize);
  std::iota(inVec.begin(), inVec.end(), 1);

  // prepare new container
  int ncol = 5;
  int nrow = std::ceil(float(vecSize) / float(ncol));
  std::vector<std::vector<int>> outVecVec(nrow);

  // row-wise copy
  for (int i = 0; i < nrow; ++i) {
    int rowLength = ncol;
    if (i == nrow - 1 && vecSize % ncol != 0) {
      rowLength = vecSize % ncol; // length of last row, if not filled
    }
    outVecVec[i].resize(rowLength);
    auto vecIndex = inVec.begin() + i * ncol;
    std::copy(vecIndex, vecIndex + rowLength, outVecVec[i].begin());
  }

  // print output
   for (int i = 0; i < nrow; ++i) {
     for (int j = 0; j < outVecVec[i].size(); ++j)
       std::cout << outVecVec[i][j] << " ";
     std::cout << std::endl;
   }
}

demo: https://godbolt.org/z/w9aDrE