问:
EC2 SSH connection broken pipe; cannot reconnect
I successfully connected to an EC2 instance like so:

```<code>ssh -i .ssh/ec2docker.cer user@SOMEIP
</code>```

After about an hour of using the instance, I leave and come back further two hours to this:

```<code>$ packet_write_wait: Connection to xx port 22: Broken pipe
</code>```

Now, when trying to connect, nothing happens at all:

```<code>OpenSSH_7.9p1, OpenSSL 1.1.1b FIPS  26 Feb 2019
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: not matched 'final'
debug2: match not found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1 (parse only)
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug1: configuration requests final Match pass
debug1: re-parsing configuration
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: matched 'final'
debug2: match found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug2: resolving "xxxx" port 22
debug2: ssh_connect_direct
debug1: Connecting to xxx [xx] port 22.
debug1: Connection established.
debug1: identity file .ssh/ec2docker.cer type -1
debug1: identity file .ssh/ec2docker.cer-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9
</code>```

ssh does not terminate or give an error. The EC2 monitor shows that the instance is running with non-zero CPU utilization (around 25%) and non-zero network read and write.

答: The reason for this issue was a memory leak in the application I was launching; it choked the whole EC2 instance.</p>

Body:
I successfully connected to an EC2 instance like so:

ssh -i .ssh/ec2docker.cer user@SOMEIP

After about an hour of using the instance, I leave and come back further two hours to this:

$ packet_write_wait: Connection to xx port 22: Broken pipe

Now, when trying to connect, nothing happens at all:

OpenSSH_7.9p1, OpenSSL 1.1.1b FIPS  26 Feb 2019
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: not matched 'final'
debug2: match not found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1 (parse only)
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug1: configuration requests final Match pass
debug1: re-parsing configuration
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: matched 'final'
debug2: match found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug2: resolving "xxxx" port 22
debug2: ssh_connect_direct
debug1: Connecting to xxx [xx] port 22.
debug1: Connection established.
debug1: identity file .ssh/ec2docker.cer type -1
debug1: identity file .ssh/ec2docker.cer-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9

ssh does not terminate or give an error. The EC2 monitor shows that the instance is running with non-zero CPU utilization (around 25%) and non-zero network read and write.


来源: stackexchange

问:
Subtract mean of columns grouped by one column
I have a Pandas DataFrame which looks as follows:

```<code>data = {'user_id':[1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3],
        'time':[10, 12, 11, 20, 40, 41, 42, 100, 60, 22, 0, 3],
        'height':[1.23, 1.1, 0.5, 10.3, 3.33, 4.55, 2.22, 2.21, 2.25, 7.75, 9.2, 5.5],
        'width':[3, 4, 6, 2, 4, 8, 9, 0, 6, 6, 6, 4]}
df = pd.DataFrame(data)
</code>```

Now, I would like to subtract from every column (except the user_id column) the mean value grouped by user_id. That means for user_id 1 the mean value for time is 13.25 ((10 + 12 + 11 + 20) / 4), so 13.25 is subtracted from 10, 12, 11 and 20 leading to

```<code>'time':[-3.25, -1.25, -2.25, 6.75, 40, 41, 42, 100, 60, 22, 0, 3]
</code>```

This I would like to do for all columns and all users. How can this be done?

ContentLicense: CC BY-SA 4.0

Body:
I have a Pandas DataFrame which looks as follows:

data = {'user_id':[1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3],
        'time':[10, 12, 11, 20, 40, 41, 42, 100, 60, 22, 0, 3],
        'height':[1.23, 1.1, 0.5, 10.3, 3.33, 4.55, 2.22, 2.21, 2.25, 7.75, 9.2, 5.5],
        'width':[3, 4, 6, 2, 4, 8, 9, 0, 6, 6, 6, 4]}
df = pd.DataFrame(data)

Now, I would like to subtract from every column (except the user_id column) the mean value grouped by user_id. That means for user_id 1 the mean value for time is 13.25 ((10 + 12 + 11 + 20) / 4), so 13.25 is subtracted from 10, 12, 11 and 20 leading to

'time':[-3.25, -1.25, -2.25, 6.75, 40, 41, 42, 100, 60, 22, 0, 3]

This I would like to do for all columns and all users. How can this be done?

Body:
Is this what you want?

df[df.columns.difference(['user_id'])].sub(df.groupby('user_id').transform('mean'))

From @piRSquare:

df.update(df - df.groupby('user_id').transform('mean'))

or

df.loc[:, ['height', 'time', 'width']] -= df.groupby('user_id').transform('mean')

From @anky_91:

df.drop('user_id',1).sub(df.groupby('user_id').time.transform('mean'),axis=0)

Out[2054]:
      height   time  width
0  -2.052500  -3.25  -0.75
1  -2.182500  -1.25   0.25
2  -2.782500  -2.25   2.25
3   7.017500   6.75  -1.75
4  -0.036667  -1.00  -3.00
5   1.183333   0.00   1.00
6  -1.146667   1.00   2.00
7  -3.172000  63.00  -4.40
8  -3.132000  23.00   1.60
9   2.368000 -15.00   1.60
10  3.818000 -37.00   1.60
11  0.118000 -34.00  -0.40


问:
How to fix "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement.'"?
I have been getting a syntax error in my UPDATE datagridview code which happens to work in another .cs file. My group has been looking at different solutions online but everything won't work.

My group has been looking at different solutions online but everything won't seem to work.

```<code>        {
            connection.Open();
            OleDbCommand cmd = connection.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Update Table1 set treatment = '" + treat.Text + "', remarks = '" + appRemarks.Text + "', cost = '" + treatCost.Text + "', Time = '" + textBox2.Text + "' where lastName = '" + Lastname.Text + "' ";

            cmd.ExecuteNonQuery();
            connection.Close();
            MessageBox.Show("Updated Successfully!");
        }
</code>```

The expected output should be Updated Successfully! and it should reflect in the database file after clicking the update button. Sometimes the output is "Microsoft Engine database" which does not save the changes.

The error says "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement.'" pointing to cmd.ExecuteNonQuery();

答:
This would happen if someone types an apostrophe into the remarks field, which SQL server will interpret as the ending quote of the string.  But much worse things can happen if the user knows a bit of sql and wants to cause trouble.  For example, putting '-- in the remarks will result in

```<code>Update Table1 set treatment = 'blah', remarks = ''-- where lastName = 'foobar'
</code>```

which will overwrite every row in the table, not only the one containing foobar.

Use query parameters so that user-provided values can't be interpreted as query keywords and structure.

Instead of remarks = '" + appRemarks.Text + "' you will have remarks = @Remarks as well as

```<code>cmd.Parameters.Add("@Remarks", SqlDbType.NText).Value = appRemarks.Text;
</code>```

and all the other user inputs likewise.

Body:
I have been getting a syntax error in my UPDATE datagridview code which happens to work in another .cs file. My group has been looking at different solutions online but everything won't work.

My group has been looking at different solutions online but everything won't seem to work.

        {
            connection.Open();
            OleDbCommand cmd = connection.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Update Table1 set treatment = '" + treat.Text + "', remarks = '" + appRemarks.Text + "', cost = '" + treatCost.Text + "', Time = '" + textBox2.Text + "' where lastName = '" + Lastname.Text + "' ";

            cmd.ExecuteNonQuery();
            connection.Close();
            MessageBox.Show("Updated Successfully!");
        }

The expected output should be Updated Successfully! and it should reflect in the database file after clicking the update button. Sometimes the output is "Microsoft Engine database" which does not save the changes.

The error says "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement.'" pointing to cmd.ExecuteNonQuery();

Body:
This would happen if someone types an apostrophe into the remarks field, which SQL server will interpret as the ending quote of the string.  But much worse things can happen if the user knows a bit of sql and wants to cause trouble.  For example, putting '-- in the remarks will result in

Update Table1 set treatment = 'blah', remarks = ''-- where lastName = 'foobar'

which will overwrite every row in the table, not only the one containing foobar.

Use query parameters so that user-provided values can't be interpreted as query keywords and structure.

Instead of remarks = '" + appRemarks.Text + "' you will have remarks = @Remarks as well as

cmd.Parameters.Add("@Remarks", SqlDbType.NText).Value = appRemarks.Text;

and all the other user inputs likewise.


问:
Adding dictonary into the dictonary using 'for' loop
Below are the lists :

```<code>text = ['is', 'ramping', 'brings']
head = ['ramping', 'ramping', 'ramping']
childWord = [[],
 ['Cola', 'is', 'up', 'launches', 'brings', 'drink', '.'],
 ['as', 'it', 'mineral']]
</code>```

And using below code I am updating this list item in value of dictonary verb.

```<code>verb = {}
for i in range(0 , len(text)):

    verb [i] = {'Verb Text': text[i], 'Text Head of the verb' : head[i], 'Child Word of the verb' : childWord[i]}

verb.update(verb [i])
verb
</code>```

And I am getting an output as follow:

```<code>{0: {'Verb Text': 'is',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': []},
 1: {'Verb Text': 'ramping',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': ['Cola',
   'is',
   'up',
   'launches',
   'brings',
   'drink',
   '.']},
 2: {'Verb Text': 'brings',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': ['as', 'it', 'mineral']},
 'Verb Text': 'brings',
 'Text Head of the verb': 'ramping',
 'Child Word of the verb': ['as', 'it', 'mineral']}
</code>```

In the output the issue is its creating below key value pair two times

```<code>'Verb Text': 'brings',
 'Text Head of the verb': 'ramping',
 'Child Word of the verb': ['as', 'it', 'mineral']
</code>```

Any comments will be appreciated..!!

答:
The line verb.update(verb[i]) updates the dictionary with the last element after the for loop, hence the last element comes up twice.

Remove that line and your code will work fine

Hence the code changes to

```<code>text = ['is', 'ramping', 'brings']
head = ['ramping', 'ramping', 'ramping']
childWord = [[],
 ['Cola', 'is', 'up', 'launches', 'brings', 'drink', '.'],
 ['as', 'it', 'mineral']]

verb = {}
for i in range(0 , len(text)):

    verb [i] = {'Verb Text': text[i], 'Text Head of the verb' : head[i], 'Child Word of the verb' : childWord[i]}

#Remove this line since it is updating the dictionary with the last element again
#verb.update(verb [i])

print(verb)
</code>```

You can also simplify the code by restructuing your dictionary and then using list comprehension to calculate your final list

```<code>#Dictionary of keys to list of values
dct = { 'Verb Text': ['is', 'ramping', 'brings'],
'Text Head of the verb': ['ramping', 'ramping', 'ramping'],
'Child Word of the verb': [[],
 ['Cola', 'is', 'up', 'launches', 'brings', 'drink', '.'],
 ['as', 'it', 'mineral']]

}

#Keys of the dictionary
keys = dct.keys()

#Iterate over the indexes and keys to make your list via list and dictionary comprehension
verb =  [{key:dct[key][idx]} for idx in range(len(dct['Verb Text'])) for key in keys]

print(verb)
</code>```

And the output will be same in both cases which is

```<code>{
0: {'Verb Text': 'is', 'Text Head of the verb': 'ramping', 'Child Word of the verb': []},
1: {'Verb Text': 'ramping', 'Text Head of the verb': 'ramping', 'Child Word of the verb': ['Cola', 'is', 'up', 'launches', 'brings', 'drink', '.']},
2: {'Verb Text': 'brings', 'Text Head of the verb': 'ramping', 'Child Word of the verb': ['as', 'it', 'mineral']}
}
</code>```

Body:
Below are the lists :

text = ['is', 'ramping', 'brings']
head = ['ramping', 'ramping', 'ramping']
childWord = [[],
 ['Cola', 'is', 'up', 'launches', 'brings', 'drink', '.'],
 ['as', 'it', 'mineral']]

And using below code I am updating this list item in value of dictonary verb.

verb = {}
for i in range(0 , len(text)):

    verb [i] = {'Verb Text': text[i], 'Text Head of the verb' : head[i], 'Child Word of the verb' : childWord[i]}

verb.update(verb [i])
verb

And I am getting an output as follow:

{0: {'Verb Text': 'is',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': []},
 1: {'Verb Text': 'ramping',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': ['Cola',
   'is',
   'up',
   'launches',
   'brings',
   'drink',
   '.']},
 2: {'Verb Text': 'brings',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': ['as', 'it', 'mineral']},
 'Verb Text': 'brings',
 'Text Head of the verb': 'ramping',
 'Child Word of the verb': ['as', 'it', 'mineral']}

In the output the issue is its creating below key value pair two times

'Verb Text': 'brings',
 'Text Head of the verb': 'ramping',
 'Child Word of the verb': ['as', 'it', 'mineral']

Any comments will be appreciated..!!

Body:
The line verb.update(verb[i]) updates the dictionary with the last element after the for loop, hence the last element comes up twice.

Remove that line and your code will work fine

Hence the code changes to

text = ['is', 'ramping', 'brings']
head = ['ramping', 'ramping', 'ramping']
childWord = [[],
 ['Cola', 'is', 'up', 'launches', 'brings', 'drink', '.'],
 ['as', 'it', 'mineral']]

verb = {}
for i in range(0 , len(text)):

    verb [i] = {'Verb Text': text[i], 'Text Head of the verb' : head[i], 'Child Word of the verb' : childWord[i]}

#Remove this line since it is updating the dictionary with the last element again
#verb.update(verb [i])

print(verb)

You can also simplify the code by restructuing your dictionary and then using list comprehension to calculate your final list

#Dictionary of keys to list of values
dct = { 'Verb Text': ['is', 'ramping', 'brings'],
'Text Head of the verb': ['ramping', 'ramping', 'ramping'],
'Child Word of the verb': [[],
 ['Cola', 'is', 'up', 'launches', 'brings', 'drink', '.'],
 ['as', 'it', 'mineral']]

}

#Keys of the dictionary
keys = dct.keys()

#Iterate over the indexes and keys to make your list via list and dictionary comprehension
verb =  [{key:dct[key][idx]} for idx in range(len(dct['Verb Text'])) for key in keys]

print(verb)

And the output will be same in both cases which is

{
0: {'Verb Text': 'is', 'Text Head of the verb': 'ramping', 'Child Word of the verb': []},
1: {'Verb Text': 'ramping', 'Text Head of the verb': 'ramping', 'Child Word of the verb': ['Cola', 'is', 'up', 'launches', 'brings', 'drink', '.']},
2: {'Verb Text': 'brings', 'Text Head of the verb': 'ramping', 'Child Word of the verb': ['as', 'it', 'mineral']}
}


问:
PHP Open Source eCommerce Software
I hope you are good today, my query is a simple one i am searching for an open source ecommerce solution that can be extended with my own modules etc.

after scouring google there are loads of open source solutions and different websites recommend different solutions.

I trust the community of stack far more than random websites on google, so can you please make recommendations on systems you have previously used and how you found them on an overall.

Thanks in advance.

答:
i use osCommerce but it is "old software" but i have be with it a long time and know it well. for someone new looking at getting in to it i would look more to PrestaShop. osCommerce still have its good points in there is a lot of info on the web so it is not hard to find a fix when you need one.

The best bet mite be to download some and have a play for yourself :) hope this helps

ContentLicense: CC BY-SA 3.0

Title: PHP Open Source eCommerce Software


问:
SQL Statement performance slow
I developed an importer which itereates through a file (10K + rows) and writes a CSV file into a MySQL db. Unfortunately this is super slow!
Could you please advice me how to improve the following code?

```<code>for($i=1; $i<count($data); $i++) {
                                        $rowData = $data[$i];
                                        if(isset($rowData[0])){
                                            $brandingPositionDataSql = 'SELECT * from branding_position WHERE sku_simple_product ="'.$rowData[0].'" AND branding_position_de ="'.$rowData[1].'" AND branding_id = "'.$rowData[8].'" AND handling_group_id = "'.$rowData[9].'" AND pre_cost_id = "'.$rowData[11].'"';
                                            $fetchBradingData = $connection->fetchAll($brandingPositionDataSql);

                                            if(count($fetchBradingData) >= 1){
                                                $updateBrandingDataSql = 'UPDATE branding_position SET sku_simple_product="'.$rowData[0].'", branding_position_de   ="'.$rowData[1].'",branding_position_en="'.$rowData[2].'",branding_position_fr  ="'.$rowData[3].'",branding_position_es="'.$rowData[4].'",branding_position_it  ="'.$rowData[5].'",branding_position_pl="'.$rowData[6].'",branding_position_nl="'.$rowData[7].'",branding_id="'.$rowData[8].'",is_branding_incl='.$rowData[10].' WHERE sku_simple_product ="'.$rowData[0].'" AND  branding_position_de ="'.$rowData[1].'" AND  branding_id = "'.$rowData[8].'" AND handling_group_id = "'.$rowData[9].'" AND pre_cost_id = "'.$rowData[11].'"';
                                                $connection->query($updateBrandingDataSql);
                                            }else{
                                                $sql1 = 'INSERT INTO branding_position (sku_simple_product, branding_position_de, branding_position_en, branding_position_fr, branding_position_es, branding_position_it, branding_position_pl, branding_position_nl, branding_id, handling_group_id, is_branding_incl, pre_cost_id) VALUES ("'.$rowData[0].'","'.$rowData[1].'","'.$rowData[2].'","'.$rowData[3].'","'.$rowData[4].'","'.$rowData[5].'","'.$rowData[6].'","'.$rowData[7].'","'.$rowData[8].'","'.$rowData[9].'",'.$rowData[10].',"'.$rowData[11].'")';
                                                $connection->query($sql1);
                                            }
                                          }
                                        }

</code>```

Thanks in advance!

答:
I still don't understand what you are doing.  But here are some tips:

Use LOAD DATA INFILE ... to copy a CSV file into a table.  It is very fast.

If the data (from the LOAD) needs manipulating (before UPDATEing or INSERTing), LOAD into an extra table, then do mass manipulations.

That SELECT and UPDATE need a 5-column index on the 5 columns mentioned in the WHERE clause; they can be in any order.

Consider using INSERT ... ON DUPLICATE KEY UPDATE ... to avoid the select + existence check + update.  You can probably do a single IODKU for the entire LOADed data from the extra table.

Title: SQL Statement performance slow

Body:
I developed an importer which itereates through a file (10K + rows) and writes a CSV file into a MySQL db. Unfortunately this is super slow!
Could you please advice me how to improve the following code?

for($i=1; $i<count($data); $i++) {
                                        $rowData = $data[$i];
                                        if(isset($rowData[0])){
                                            $brandingPositionDataSql = 'SELECT * from branding_position WHERE sku_simple_product ="'.$rowData[0].'" AND branding_position_de ="'.$rowData[1].'" AND branding_id = "'.$rowData[8].'" AND handling_group_id = "'.$rowData[9].'" AND pre_cost_id = "'.$rowData[11].'"';
                                            $fetchBradingData = $connection->fetchAll($brandingPositionDataSql);

                                            if(count($fetchBradingData) >= 1){
                                                $updateBrandingDataSql = 'UPDATE branding_position SET sku_simple_product="'.$rowData[0].'", branding_position_de   ="'.$rowData[1].'",branding_position_en="'.$rowData[2].'",branding_position_fr  ="'.$rowData[3].'",branding_position_es="'.$rowData[4].'",branding_position_it  ="'.$rowData[5].'",branding_position_pl="'.$rowData[6].'",branding_position_nl="'.$rowData[7].'",branding_id="'.$rowData[8].'",is_branding_incl='.$rowData[10].' WHERE sku_simple_product ="'.$rowData[0].'" AND  branding_position_de ="'.$rowData[1].'" AND  branding_id = "'.$rowData[8].'" AND handling_group_id = "'.$rowData[9].'" AND pre_cost_id = "'.$rowData[11].'"';
                                                $connection->query($updateBrandingDataSql);
                                            }else{
                                                $sql1 = 'INSERT INTO branding_position (sku_simple_product, branding_position_de, branding_position_en, branding_position_fr, branding_position_es, branding_position_it, branding_position_pl, branding_position_nl, branding_id, handling_group_id, is_branding_incl, pre_cost_id) VALUES ("'.$rowData[0].'","'.$rowData[1].'","'.$rowData[2].'","'.$rowData[3].'","'.$rowData[4].'","'.$rowData[5].'","'.$rowData[6].'","'.$rowData[7].'","'.$rowData[8].'","'.$rowData[9].'",'.$rowData[10].',"'.$rowData[11].'")';
                                                $connection->query($sql1);
                                            }
                                          }
                                        }

Thanks in advance!


问:
Read specific value of an object
I'm using an api that return this object:

```<code>   {
        "0155894402285712": { "type": "GBUserFieldText", "value": "A0242", "name": "Codice+tessera" },
        "0155894402283800": { "type": "GBUserFieldText", "value": "LZZMRN55L53C003Z", "name": "Codice+Fiscale" }
    }
</code>```

I need to extract the value A0242 and LZZMRN55L53C003Z but the only things that I know are the name "Codice+tessera" and "Codice+fiscale". How can I read these values? Maybe my question is stupid but really I'm losing my brain today...

Thanks

答:
If you are looking to find A0242 from the value "Codice+tessera" that you have, you need something different than the other answers:

var data = {
        "0155894402285712": { "type": "GBUserFieldText", "value": "A0242", "name": "Codice+tessera" },
        "0155894402283800": { "type": "GBUserFieldText", "value": "LZZMRN55L53C003Z", "name": "Codice+Fiscale" }
    }

const values = ["Codice+tessera", "Codice+fiscale"]
const results = values.map(v => Object.values(data).find(datum => datum.name === v)).map(v => v.value)
console.log(results) // [ "A0242", "LZZMRN55L53C003Z" ]
```

Title: Read specific value of an object

Body:
I'm using an api that return this object:

   {
        "0155894402285712": { "type": "GBUserFieldText", "value": "A0242", "name": "Codice+tessera" },
        "0155894402283800": { "type": "GBUserFieldText", "value": "LZZMRN55L53C003Z", "name": "Codice+Fiscale" }
    }

I need to extract the value A0242 and LZZMRN55L53C003Z but the only things that I know are the name "Codice+tessera" and "Codice+fiscale". How can I read these values? Maybe my question is stupid but really I'm losing my brain today...

Thanks


问:
Count lines of code in directory using Python
I have a project whose lines of code I want to count. Is it possible to count all the lines of code in the file directory containing the project by using Python?</p>

答:
This has a slight air of homework assignment :-) -- nonetheless, it's a worthwhile exercise, and Bryce93's formatting is nice. I think many would be unlikely to use Python for this given that it can be done quickly with a couple of shell commands, for example:

```<code>cat $(find . -name "*.py") | grep -E -v '^\s*$|^\s*#' | wc -l
</code>```

Note that none of these solutions accounts for multiline (''') comments.

Body:
This has a slight air of homework assignment :-) -- nonetheless, it's a worthwhile exercise, and Bryce93's formatting is nice. I think many would be unlikely to use Python for this given that it can be done quickly with a couple of shell commands, for example:

cat $(find . -name "*.py") | grep -E -v '^\s*$|^\s*#' | wc -l

Note that none of these solutions accounts for multiline (''') comments.


问:
Prevent close Toastr on Click
I´m trying to keep toastr open alway but it´s dissapear when I click on it, I set extendedTimeOut = 0 , however the toastr dissapear when click on it, so I need a way it never closes even when I make click on it</p>

答:
Only thing that worked for me was setting "tapToDismiss"= false and updating the toastr script:

toastr.options.tapToDismiss = false

Line 273 in toastr.js:

```<code>if (options.onclick) {
    $toastElement.click(function () {
        options.onclick();
        if (options.tapToDismiss) hideToast(); // Line that hides toast.
    });
}
</code>```

Title: Prevent close Toastr on Click

Body:
Only thing that worked for me was setting "tapToDismiss"= false and updating the toastr script:

toastr.options.tapToDismiss = false

Line 273 in toastr.js:

if (options.onclick) {
    $toastElement.click(function () {
        options.onclick();
        if (options.tapToDismiss) hideToast(); // Line that hides toast.
    });
}


问:
How to remove bottom line of custom Tab view

How can I remove that line from my tab view? Or can I set height or colors for it?

答:
try defining a new theme with windowContentOverlay set to null:

```<code><style name="MyTheme" parent="@android:style/Theme>
    <item name="android:windowContentOverlay">@null</item>
</style>
</code>```

And then apply this theme to your activity in your manifest (or you can apply it to the  element to apply it application-wide):

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stylingandroid.VectorDrawables" android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
            android:label="@string/app_name" android:theme="@style/MyTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>
</code>```

That should remove the shadow.

If you want to change the colour of it set android:cacheColorHint in the style.

Body:
try defining a new theme with windowContentOverlay set to null:

<style name="MyTheme" parent="@android:style/Theme>
    <item name="android:windowContentOverlay">@null</item>
</style>

And then apply this theme to your activity in your manifest (or you can apply it to the  element to apply it application-wide):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stylingandroid.VectorDrawables" android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
            android:label="@string/app_name" android:theme="@style/MyTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

That should remove the shadow.

If you want to change the colour of it set android:cacheColorHint in the style.


问:
reactstrap <Navbar> fixed on top
I'm using reactstap and try to implement a navbar being fixed, which works partially, since the navbar is fixed, but the very next component moves to the top (behind the navbar). If the fixed attribute is not set, the content appears correctly below the navbar.</p>

```<code><Navbar className="bg-dark" color="dark" fixed="top" >
</code>```

答:
You can add a margin or padding to the top of the body to move it down to compensate for the height of your navbar.

Add to your stylesheet:

```<code>body {
  padding-top: 45px;
}
</code>```

or add it to your body or main tag as an inline style.

Title: reactstrap <Navbar> fixed on top

Body:
I'm using reactstap and try to implement a navbar being fixed, which works partially, since the navbar is fixed, but the very next component moves to the top (behind the navbar). If the fixed attribute is not set, the content appears correctly below the navbar.

<Navbar className="bg-dark" color="dark" fixed="top" >

Body:
You can add a margin or padding to the top of the body to move it down to compensate for the height of your navbar.

Add to your stylesheet:

body {
  padding-top: 45px;
}

or add it to your body or main tag as an inline style.


问:
Display sum of all datalabels of each each bar stacks
How can I display sum of all the data labels above the bar stack as in the attached image</p>

答: You will need to sum them yourself, perhaps by using chart.series.values and place them in a separate text-box. There is no option in the chart itself to display summary values like this.


问:
eclipse won't start - no java virtual machine was found
Eclipse was running fine yesterday (and has been since I installed it about a year ago). Now all the sudden I'm getting the following error on startup:

```<code>"A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found after searching the following locations:
C:\Program Files\eclipse\jre\bin\javaw.exe
javaw.exe in your current PATH"
</code>```

I have not changed anyhing Eclipse/Java related on my machine but a Windows update was applied to my machine yesterday, so maybe that has something to do with it (but I don't see anything that would affect Java). I've looked at all the other posts about adding something to your PATH or adding the -vm option to the Eclipse ini (couldn't get this to work) or copying the jre folder to eclipse\jre (this worked but doesn't seem like a good long term solution). So I'm really trying to figure out how to get things back to the "default" setup without messing stuff up.

I'm running Windows 7, Eclipse Helios and Java 1.6.0_26.

答:
After setting Java Path, if you are not able to open your eclipse do below steps:

Go to your Eclipse Folder where you have extracted your eclipse.

Open Eclipse file in notepad (by default it will open on notepad)

Enter two lines

```<code>-vm
C:/Program Files/Java/jdk-11.0.2/bin/javaw.exe
</code>```

jdk-11.0.2 ,It should be your Java Version, which you will get by the above location.

Body:
Eclipse was running fine yesterday (and has been since I installed it about a year ago). Now all the sudden I'm getting the following error on startup:

"A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found after searching the following locations:
C:\Program Files\eclipse\jre\bin\javaw.exe
javaw.exe in your current PATH"

I have not changed anyhing Eclipse/Java related on my machine but a Windows update was applied to my machine yesterday, so maybe that has something to do with it (but I don't see anything that would affect Java). I've looked at all the other posts about adding something to your PATH or adding the -vm option to the Eclipse ini (couldn't get this to work) or copying the jre folder to eclipse\jre (this worked but doesn't seem like a good long term solution). So I'm really trying to figure out how to get things back to the "default" setup without messing stuff up.

I'm running Windows 7, Eclipse Helios and Java 1.6.0_26.

Body:
After setting Java Path, if you are not able to open your eclipse do below steps:

Go to your Eclipse Folder where you have extracted your eclipse.

Open Eclipse file in notepad (by default it will open on notepad)

Enter two lines

-vm
C:/Program Files/Java/jdk-11.0.2/bin/javaw.exe

jdk-11.0.2 ,It should be your Java Version, which you will get by the above location.


问:
Check constraints not working on a query/view with join
We have a view described as the following :

```<code>CREATE view [dbo].[PriceHourlyView]
AS
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2018 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2017 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2016 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2015 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2014 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2013 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2012 WITH (NOLOCK)
</code>```

Each of the tables has a check constraint as follows for each year except for the current table without year specified :

```<code>ALTER TABLE [dbo].[PriceHourly2017]  WITH CHECK ADD  CONSTRAINT [CK_PriceHourly2017_Timestamp] CHECK  (([timestamp]>='2017-01-01' AND [timestamp]<='2017-12-31 23:59'))
</code>```

When this view is queried by itself the check constraints limit the tables being searched. The execution plan looks like this :

```<code>SELECT
  *
FROM PriceHourlyview
WHERE nodeid = 24511
AND TimeStamp BETWEEN '2017-05-17' AND '2017-05-24'
</code>```

Now when I join on this table on the timestamp field the query no longer uses the check constraints and uses every table to check for the data.

SELECT
  *
FROM ShapeProfileDetails s WITH (NOLOCK)
LEFT JOIN PriceHourlyView p WITH (NOLOCK)
  ON s.TimeStamp = p.Timestamp
  AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'
WHERE NodeId = 24512
--AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'
```

I know I'm not querying the same field in the joined example and assuming that's the issue but that is the field I need to query for the correct results. I'm wondering if there is anyway to hint or force the query to use the correct check constraints. Or what is the best practice on joining to try and utilize these check constraints.

答:
Okay, as discussed we know that EffectiveDate and TimeStamp are nearly the same. I would try to do something like this. Technically it's the same query, but we will let know SQL Server that it can use constraints (just subtract and add one day on the edges of BETWEEN).

```<code>SELECT * FROM ShapeProfileDetails s WITH (NOLOCK)
JOIN PriceHourlyView p WITH (NOLOCK)
   ON s.TimeStamp = p.Timestamp
AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'
AND s.TimeStamp BETWEEN '2017-05-16' AND '2017-05-25'
WHERE NodeId = 24512
</code>```

Body:
We have a view described as the following :

CREATE view [dbo].[PriceHourlyView]
AS
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2018 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2017 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2016 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2015 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2014 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2013 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2012 WITH (NOLOCK)

Each of the tables has a check constraint as follows for each year except for the current table without year specified :

ALTER TABLE [dbo].[PriceHourly2017]  WITH CHECK ADD  CONSTRAINT [CK_PriceHourly2017_Timestamp] CHECK  (([timestamp]>='2017-01-01' AND [timestamp]<='2017-12-31 23:59'))

When this view is queried by itself the check constraints limit the tables being searched. The execution plan looks like this :

SELECT
  *
FROM PriceHourlyview
WHERE nodeid = 24511
AND TimeStamp BETWEEN '2017-05-17' AND '2017-05-24'

Now when I join on this table on the timestamp field the query no longer uses the check constraints and uses every table to check for the data.

SELECT
  *
FROM ShapeProfileDetails s WITH (NOLOCK)
LEFT JOIN PriceHourlyView p WITH (NOLOCK)
  ON s.TimeStamp = p.Timestamp
  AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'
WHERE NodeId = 24512
--AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'

I know I'm not querying the same field in the joined example and assuming that's the issue but that is the field I need to query for the correct results. I'm wondering if there is anyway to hint or force the query to use the correct check constraints. Or what is the best practice on joining to try and utilize these check constraints.

Body:
Okay, as discussed we know that EffectiveDate and TimeStamp are nearly the same. I would try to do something like this. Technically it's the same query, but we will let know SQL Server that it can use constraints (just subtract and add one day on the edges of BETWEEN).

SELECT * FROM ShapeProfileDetails s WITH (NOLOCK)
JOIN PriceHourlyView p WITH (NOLOCK)
   ON s.TimeStamp = p.Timestamp
AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'
AND s.TimeStamp BETWEEN '2017-05-16' AND '2017-05-25'
WHERE NodeId = 24512


问:
Enclosing a block of text in quotation marks (or any other couple of chars) in a csv
I have a .csv file, and I need to do what follows: for each line, starting from the end of the line, the text that occurs after a certain number of occurrences of a specified character should be enclosed in quotation marks.

I'll try and make myself clearer with an example. Consider the following line of a csv:

```<code>gentlemen, this is a block of text. Thanks!,1,0,0,1
</code>```

I want to enclose in quotation marks the slice of the line which occurs, starting from the end, after the fourth occurrence of a comma. So, it should become:

```<code>"gentlemen, this is a block of text. Thanks!",1,0,0,1
</code>```

I'd like to do it in bash, pure python, or pandas.

答:
In python:

line = r'gentlemen, this is a block of text. Thanks!,1,0,0,1'
num_commas = 4
comma_count = 0
for c in reversed(line):
    from_end += 1
    if c == ',':
        comma_count += 1
    if comma_count >= num_commas:
        break
line[:-from_end]
# 'gentlemen, this is a block of text. Thanks!'
```

The rest is academic.

Body:
I have a .csv file, and I need to do what follows: for each line, starting from the end of the line, the text that occurs after a certain number of occurrences of a specified character should be enclosed in quotation marks.

I'll try and make myself clearer with an example. Consider the following line of a csv:

gentlemen, this is a block of text. Thanks!,1,0,0,1

I want to enclose in quotation marks the slice of the line which occurs, starting from the end, after the fourth occurrence of a comma. So, it should become:

"gentlemen, this is a block of text. Thanks!",1,0,0,1

I'd like to do it in bash, pure python, or pandas.

Body:
In python:

line = r'gentlemen, this is a block of text. Thanks!,1,0,0,1'
num_commas = 4
comma_count = 0
for c in reversed(line):
    from_end += 1
    if c == ',':
        comma_count += 1
    if comma_count >= num_commas:
        break
line[:-from_end]
# 'gentlemen, this is a block of text. Thanks!'

The rest is academic.


问:
c# Thread in 100% CPU
I have a complex system with several threads. sometimes i see the application in 100% cpu and force to restart the system. I have no idea which thread caused it and which code caused it.
I need something that will give me the state of each thread in the system (i.e. in which line the thread is now) so i can find which code causes the 100% CPU

(in java you have the thread dump kill -3 which gives you the state of each thread)

Can you help please?

答:
You could use the debugger to break and then find out what all threads are doing. (Add the Debug Location toolbar to Visual Studio)

Another option is to remove all thread one by one and find the guilty one.

Title: c# Thread in 100% CPU


问:
How to change hit point to crosshair?
Below script uses a function whereas there first is a check if there is a object in range and if it, it is.

On pressing mouse key, the projectile is shooting towards the pivot point of that said object. I want the projectile to

always being able to fire (indifferent if the object is in range) and

shoot towards the crosshair (to the screen midpoint) and NOT towards the object pivot point.

I am a novice at coding and I can't see what code to remove and what to add.

```<code>    using System.Collections;
    using System.Collections.Generic;
    using UnityEditor;
    using UnityEngine;
    using UnityEngine.Events;

    public struct ShootHit
    {
    public GameObject gameObject;
    public Vector3 point;
    }

    [System.Serializable]
    public class UnityEventShootHit : UnityEvent<ShootHit> { }

    [DisallowMultipleComponent, AddComponentMenu("(つ♥v♥)つ/Useables/Shoot")]
    public class ShootComponent : MonoBehaviour
    {
    [Header("Input")]
    [Tooltip("Data that determines the input of player actions")]
    [SerializeField] private InputProfile _inputProfile;
    // [SerializeField] private float _range = 100.0f;

    /* [Header("Sight Values")]
     [Tooltip("How far the the sight can reach")]
     public float sightRadius = 1f;
     [Range(0f, 360f)]
     public float fieldOfViewAngle = 100f;*/

    [Header("Charge-up")]
    [SerializeField] private float _chargeupTime = 0.5f;
    private bool _isChargingPrimary = false;
    private bool _isChargingSecondary = false;

    [Header("Aim Assist")]
    [SerializeField] private LayerMask _aimAssistLayerMask;

    public float aimAssistRadius = 30.0f;  // radius
    [Range(0.0f, 360.0f)]
    public float aimAssistMaxAngleToAssist = 45.0f;  // angle

    private ShootHit? _target;

    //publics
    public Transform shootOrigin;

    [Header("Events")]
    public UnityEventShootHit OnPrimaryFire;
    public UnityEvent OnPrimaryFireStart;
    public UnityEvent OnPrimaryFireStop;

    public UnityEventShootHit OnSecondaryFire;
    public UnityEvent OnSecondaryFireStart;
    public UnityEvent OnSecondaryFireStop;

    private void Start()
    {
        if (_inputProfile == null) Debug.LogError(gameObject.name + " does not
        have a player input");
    }

     private void Update()
     {
         // Remove target if object is too far away
         if (_target.HasValue)
         {
            if (Vector3.Distance(_target.Value.gameObject.transform.position,
         transform.position) > aimAssistRadius)
            {
                _target = null;
            }
         }

         if (_inputProfile.GetPrimaryFireButtonDown())
         {
            StopCoroutine(ChargeUpBeforeFireSecondary());

            if (!_isChargingPrimary)
            {
                StartCoroutine(ChargeUpBeforeFirePrimary());
            }
         }

         else if (_inputProfile.GetSecondaryFireButtonDown())
         {
            StopCoroutine(ChargeUpBeforeFirePrimary());

            if (!_isChargingSecondary)
            {
                StartCoroutine(ChargeUpBeforeFireSecondary());
            }
        }

         if (_inputProfile.GetPrimaryFireButton() ||
        _inputProfile.GetSecondaryFireButton())
        {
            if (!_target.HasValue) _target = GetObjectClosestToAim();

            if (_inputProfile.GetPrimaryFireButton())
            {
                OnPrimaryFire.Invoke(_target.Value);
            }
            if (_inputProfile.GetSecondaryFireButton())
            {
                OnSecondaryFire.Invoke(_target.Value);
            }

        }
        else
        {
            _target = null;
        }

        if (_inputProfile.GetPrimaryFireButtonUp())
            OnPrimaryFireStop.Invoke();
        if (_inputProfile.GetSecondaryFireButtonUp())
            OnSecondaryFireStop.Invoke();
    }

    /// <summary>
    /// Finds the object within range closest to the players forward-vector
    using _aimAssistLayerMask.
    /// </summary>
    /// <returns>Returns object closest to aim if any object is found, else
    returns null.</returns>
    ShootHit? GetObjectClosestToAim()
    {
        // Raycast
        RaycastHit hit;
        if (Physics.Raycast(shootOrigin.position, Camera.main.transform.forward,
        out hit, aimAssistRadius, _aimAssistLayerMask))
        {
            if (hit.transform?.GetComponent<IShootTarget>() != null)
            {
                Debug.Log(hit.transform.name);

                return new ShootHit { gameObject = hit.transform.gameObject,
    point = hit.point };
            }
        }

        float _closestDot = -2f;
        GameObject _closestDotObject = null;
        RaycastHit[] _hit = Physics.SphereCastAll(transform.position,
        aimAssistRadius, transform.forward, 0, _aimAssistLayerMask,
        QueryTriggerInteraction.Ignore);

        // Get best dot from all objects within range
        for (int i = 0; i < _hit.Length; i++)
        {
            if (_hit[i].transform.gameObject == this.gameObject ||
        _hit[i].transform.GetComponent<IShootTarget>() == null)
                continue;

            Vector3 _dif = _hit[i].transform.position - transform.position;

            float _newDot = Vector3.Dot(transform.forward.normalized,
      _dif.normalized);
            if (_newDot > _closestDot)
            {
                _closestDot = _newDot;
                _closestDotObject = _hit[i].transform.gameObject;
            }
        }
        if (!_closestDotObject)
            return null;

        // Make sure there are no object in the way of our best-dot-object
        Collider[] colliders = _closestDotObject.GetComponents<Collider>();
        Vector3 point = colliders[0].ClosestPoint(shootOrigin.position);
        float distanceToPoint = Vector3.Distance(shootOrigin.position, point);
        // Get closest collider
        for (int i = 1; i < colliders.Length; i++)
        {
            Vector3 newPoint = colliders[i].ClosestPoint(shootOrigin.position);
            float newDistanceToPoint = Vector3.Distance(shootOrigin.position,
        newPoint);
            if (distanceToPoint > newDistanceToPoint)
            {
                point = newPoint;
                distanceToPoint = newDistanceToPoint;
            }
        }
        RaycastHit _rayhit;
        if (Physics.Raycast(shootOrigin.position, point - transform.position,
        out _rayhit, aimAssistRadius, _aimAssistLayerMask))
        {
            if (_rayhit.transform.gameObject != _closestDotObject)
            {
                return null;
            }
        }

        Vector3 _vecToClosest = _closestDotObject.transform.position -
    transform.position;
        if (Vector3.Angle(transform.forward, _vecToClosest) <=
    aimAssistMaxAngleToAssist)
         {
            return new ShootHit { gameObject = _closestDotObject, point = point
 };
        }
        else
        {
            return null;
        }
    }

     IEnumerator ChargeUpBeforeFirePrimary()
    {
        _isChargingPrimary = true;
        yield return new WaitForSeconds(_chargeupTime);
        _isChargingPrimary = false;
        OnPrimaryFireStart.Invoke();
    }

    IEnumerator ChargeUpBeforeFireSecondary()
    {
        _isChargingSecondary = true;
        yield return new WaitForSeconds(_chargeupTime);
        _isChargingSecondary = false;
        OnSecondaryFireStart.Invoke();
    }

    #if UNITY_EDITOR
    private void OnDrawGizmosSelected()
    {
        if (!Application.isPlaying) return;

        Color oldColor = Gizmos.color;

        float halfFeildOfView = aimAssistMaxAngleToAssist * 0.5f;
        float coneDirection = -90f;

        Quaternion leftRayRotation = Quaternion.AngleAxis(-halfFeildOfView + coneDirection, Vector3.up);
        Quaternion rightRayRotation = Quaternion.AngleAxis(halfFeildOfView + coneDirection, Vector3.up);

        Vector3 leftRayDirection = leftRayRotation * transform.right * aimAssistRadius;
        Vector3 rightRayDirection = rightRayRotation * transform.right * aimAssistRadius;

        // Green Arc
        Handles.color = new Color(0f, 1f, 0f, 0.25f);
        Handles.DrawSolidArc(transform.position, Vector3.up, leftRayDirection, aimAssistMaxAngleToAssist, aimAssistRadius);

        Gizmos.color = oldColor;

    }
     #endif

}
`
</code>```

This is the code attached to the projectile

```<code>using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
public class ProjectileScript : MonoBehaviour
{

    public GameObject Explosion;

    public Transform Target;

    Rigidbody _rigidbody;

    public float speed = 1.0f;

    void Start()
    {
        _rigidbody = GetComponent<Rigidbody>();

    }

    void FixedUpdate()
    {
        // _rigidbody.AddForce((Target.position - transform.position).normalized, ForceMode.Impulse);
        Collider targetCollider = Target.GetComponent<Collider>();
        Vector3 targetDirection;
        if (targetCollider)
            targetDirection = targetCollider.ClosestPoint(transform.position) - transform.position;
        else
            targetDirection = Target.position - transform.position;

        _rigidbody.velocity = targetDirection.normalized * speed;
        if (Vector3.Distance(transform.position, Target.position) < 1.0f)
        {
            //make the explosion
            GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;

            //destory the projectile
            Destroy(gameObject);
        }
    }

    public void SetTarget(GameObject target)
    {
        this.Target = target.transform;
    }

    public void SetTarget(ShootHit hit) => SetTarget(hit.gameObject);

}
</code>```

This script is how and where the Projectile Spawns. It is attached to an empty gameobject located on the muzzle of the gun.

```<code>public class ProjectileSpawner : MonoBehaviour
{

    public GameObject projectileInsert;

        public GameObject projectileExtract;
        public float projectileSpeed = 1.0f;

        GameObject projectile;

        public void Insert(GameObject target)
        {
            if (projectile) return;

            projectile = Instantiate(projectileInsert, transform.position, Quaternion.identity);
            ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
            projectileScript.SetTarget(target);
            projectileScript.speed = projectileSpeed;

            // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
            // projectileSpawn.parent.GetComponent<Collider>());

        }

        public void Extract(GameObject target)
        {
            if (projectile) return;

            projectile = Instantiate(projectileExtract, target.transform.position, Quaternion.identity);
            ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
            projectileScript.SetTarget(gameObject);
            projectileScript.speed = projectileSpeed;

            // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
            // projectileSpawn.parent.GetComponent<Collider>());

        }

    }
</code>```

答:
In the ProjectileSpawner, add a LayerMask field to filter out invalid collisions (set it in the inspector) for the non-homing projectile. You'll set this in the inspector to make the non-homing projectiles collide with the desired layers:

```<code>public LayerMask collisionLayers;
</code>```

In Insert, find the ray going from the screen's center, and use it and the LayerMask as a parameter to SetTarget:

```<code>public void Insert(GameObject target)
{
    if (projectile) return;

    Ray centerRay = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2, Screen.height/2, 0f));

    projectile = Instantiate(projectileInsert, transform.position, Quaternion.identity);
    ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
    projectileScript.SetTarget(centerRay, collisionLayers);
    projectileScript.speed = projectileSpeed;

    // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
    // projectileSpawn.parent.GetComponent<Collider>());

}

public void Extract(GameObject target)
{
    if (projectile) return;

    projectile = Instantiate(projectileExtract, target.transform.position, Quaternion.identity);
    ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
    projectileScript.SetTarget(gameObject);
    projectileScript.speed = projectileSpeed;

    // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
    // projectileSpawn.parent.GetComponent<Collider>());

}
</code>```

Then in the ProjectileScript, add a bool field to remember if the projectile homes on a gameObject or if it follows a ray, a Ray field to remember such a ray, and a LayerMask field to remember what to collide with:

```<code>public bool isHoming;
public Ray TargetRay
public LayerMask collisionLayers;
</code>```

Then, in public void SetTarget(GameObject target), set that bool to true:

```<code>public void SetTarget(GameObject target)
{
    this.Target = target.transform;
    isHoming = true;
}
</code>```

And make a new public void SetTarget(Ray shootRay) that remembers a Ray and LayerMask and sets the bool to false:

```<code>public void SetTarget(Ray shootRay, LayerMask collisionLayers)
{
    this.TargetRay = shootRay;
    this.collisionLayers = collisionLayers;
    isHoming = false;
}
</code>```

Also, in ProjectileScript, you will need to change the FixedUpdate method to check if the bool is true, and if it is, then do the same as before. Otherwise, move along the ray and destroy it if it travels too far:

```<code>public float maxDistanceBeforeDestroy = 100f;

...

void FixedUpdate()
{
    if (isHoming)
    {
        // _rigidbody.AddForce((Target.position - transform.position).normalized, ForceMode.Impulse);
        Collider targetCollider = Target.GetComponent<Collider>();
        Vector3 targetDirection;
        if (targetCollider)
            targetDirection = targetCollider.ClosestPoint(transform.position) - transform.position;
        else
            targetDirection = Target.position - transform.position;

        _rigidbody.velocity = targetDirection.normalized * speed;
        if (Vector3.Distance(transform.position, Target.position) < 1.0f)
        {
            //make the explosion
            GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;

            //destory the projectile
            Destroy(gameObject);
        }
    }
    else
    {
        _rigidbody.velocity = TargetRay.direction.normalized * speed;

        // Check if it has traveled too far

        if ((transform.position - TargetRay.origin).magnitude > maxDistanceBeforeDestroy )
        {
            Destroy(gameObject);
        }
    }
}
</code>```

Then, add an OnCollisionEnter method that doesn't do anything if the projectile is homing. But if it isn't, it checks if the collision matches the LayerMask, and if it does, it makes the explosion and destroys the projectile:

```<code>void OnCollisionEnter(Collision other)
{
     if (isHoming)
     {
         return;
     }

     if( && ((1<<other.gameObject.layer) & collisionLayers) != 0)
     {
         //make the explosion
        GameObject ThisExplosion = Instantiate(Explosion,
                gameObject.transform.position,
                gameObject.transform.rotation) as GameObject;

        //destroy the projectile
        Destroy(gameObject);
     }
}
</code>```

Title: How to change hit point to crosshair?

Body:
Below script uses a function whereas there first is a check if there is a object in range and if it, it is.

On pressing mouse key, the projectile is shooting towards the pivot point of that said object. I want the projectile to

always being able to fire (indifferent if the object is in range) and

shoot towards the crosshair (to the screen midpoint) and NOT towards the object pivot point.

I am a novice at coding and I can't see what code to remove and what to add.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEditor;
    using UnityEngine;
    using UnityEngine.Events;

    public struct ShootHit
    {
    public GameObject gameObject;
    public Vector3 point;
    }

    [System.Serializable]
    public class UnityEventShootHit : UnityEvent<ShootHit> { }

    [DisallowMultipleComponent, AddComponentMenu("(つ♥v♥)つ/Useables/Shoot")]
    public class ShootComponent : MonoBehaviour
    {
    [Header("Input")]
    [Tooltip("Data that determines the input of player actions")]
    [SerializeField] private InputProfile _inputProfile;
    // [SerializeField] private float _range = 100.0f;

    /* [Header("Sight Values")]
     [Tooltip("How far the the sight can reach")]
     public float sightRadius = 1f;
     [Range(0f, 360f)]
     public float fieldOfViewAngle = 100f;*/

    [Header("Charge-up")]
    [SerializeField] private float _chargeupTime = 0.5f;
    private bool _isChargingPrimary = false;
    private bool _isChargingSecondary = false;

    [Header("Aim Assist")]
    [SerializeField] private LayerMask _aimAssistLayerMask;

    public float aimAssistRadius = 30.0f;  // radius
    [Range(0.0f, 360.0f)]
    public float aimAssistMaxAngleToAssist = 45.0f;  // angle

    private ShootHit? _target;

    //publics
    public Transform shootOrigin;

    [Header("Events")]
    public UnityEventShootHit OnPrimaryFire;
    public UnityEvent OnPrimaryFireStart;
    public UnityEvent OnPrimaryFireStop;

    public UnityEventShootHit OnSecondaryFire;
    public UnityEvent OnSecondaryFireStart;
    public UnityEvent OnSecondaryFireStop;

    private void Start()
    {
        if (_inputProfile == null) Debug.LogError(gameObject.name + " does not
        have a player input");
    }

     private void Update()
     {
         // Remove target if object is too far away
         if (_target.HasValue)
         {
            if (Vector3.Distance(_target.Value.gameObject.transform.position,
         transform.position) > aimAssistRadius)
            {
                _target = null;
            }
         }

         if (_inputProfile.GetPrimaryFireButtonDown())
         {
            StopCoroutine(ChargeUpBeforeFireSecondary());

            if (!_isChargingPrimary)
            {
                StartCoroutine(ChargeUpBeforeFirePrimary());
            }
         }

         else if (_inputProfile.GetSecondaryFireButtonDown())
         {
            StopCoroutine(ChargeUpBeforeFirePrimary());

            if (!_isChargingSecondary)
            {
                StartCoroutine(ChargeUpBeforeFireSecondary());
            }
        }

         if (_inputProfile.GetPrimaryFireButton() ||
        _inputProfile.GetSecondaryFireButton())
        {
            if (!_target.HasValue) _target = GetObjectClosestToAim();

            if (_inputProfile.GetPrimaryFireButton())
            {
                OnPrimaryFire.Invoke(_target.Value);
            }
            if (_inputProfile.GetSecondaryFireButton())
            {
                OnSecondaryFire.Invoke(_target.Value);
            }

        }
        else
        {
            _target = null;
        }

        if (_inputProfile.GetPrimaryFireButtonUp())
            OnPrimaryFireStop.Invoke();
        if (_inputProfile.GetSecondaryFireButtonUp())
            OnSecondaryFireStop.Invoke();
    }

    ///
    /// Finds the object within range closest to the players forward-vector
    using _aimAssistLayerMask.
    ///
    /// <returns>Returns object closest to aim if any object is found, else
    returns null.</returns>
    ShootHit? GetObjectClosestToAim()
    {
        // Raycast
        RaycastHit hit;
        if (Physics.Raycast(shootOrigin.position, Camera.main.transform.forward,
        out hit, aimAssistRadius, _aimAssistLayerMask))
        {
            if (hit.transform?.GetComponent<IShootTarget>() != null)
            {
                Debug.Log(hit.transform.name);

                return new ShootHit { gameObject = hit.transform.gameObject,
    point = hit.point };
            }
        }

        float _closestDot = -2f;
        GameObject _closestDotObject = null;
        RaycastHit[] _hit = Physics.SphereCastAll(transform.position,
        aimAssistRadius, transform.forward, 0, _aimAssistLayerMask,
        QueryTriggerInteraction.Ignore);

        // Get best dot from all objects within range
        for (int i = 0; i < _hit.Length; i++)
        {
            if (_hit[i].transform.gameObject == this.gameObject ||
        _hit[i].transform.GetComponent<IShootTarget>() == null)
                continue;

            Vector3 _dif = _hit[i].transform.position - transform.position;

            float _newDot = Vector3.Dot(transform.forward.normalized,
      _dif.normalized);
            if (_newDot > _closestDot)
            {
                _closestDot = _newDot;
                _closestDotObject = _hit[i].transform.gameObject;
            }
        }
        if (!_closestDotObject)
            return null;

        // Make sure there are no object in the way of our best-dot-object
        Collider[] colliders = _closestDotObject.GetComponents<Collider>();
        Vector3 point = colliders[0].ClosestPoint(shootOrigin.position);
        float distanceToPoint = Vector3.Distance(shootOrigin.position, point);
        // Get closest collider
        for (int i = 1; i < colliders.Length; i++)
        {
            Vector3 newPoint = colliders[i].ClosestPoint(shootOrigin.position);
            float newDistanceToPoint = Vector3.Distance(shootOrigin.position,
        newPoint);
            if (distanceToPoint > newDistanceToPoint)
            {
                point = newPoint;
                distanceToPoint = newDistanceToPoint;
            }
        }
        RaycastHit _rayhit;
        if (Physics.Raycast(shootOrigin.position, point - transform.position,
        out _rayhit, aimAssistRadius, _aimAssistLayerMask))
        {
            if (_rayhit.transform.gameObject != _closestDotObject)
            {
                return null;
            }
        }

        Vector3 _vecToClosest = _closestDotObject.transform.position -
    transform.position;
        if (Vector3.Angle(transform.forward, _vecToClosest) <=
    aimAssistMaxAngleToAssist)
         {
            return new ShootHit { gameObject = _closestDotObject, point = point
 };
        }
        else
        {
            return null;
        }
    }

     IEnumerator ChargeUpBeforeFirePrimary()
    {
        _isChargingPrimary = true;
        yield return new WaitForSeconds(_chargeupTime);
        _isChargingPrimary = false;
        OnPrimaryFireStart.Invoke();
    }

    IEnumerator ChargeUpBeforeFireSecondary()
    {
        _isChargingSecondary = true;
        yield return new WaitForSeconds(_chargeupTime);
        _isChargingSecondary = false;
        OnSecondaryFireStart.Invoke();
    }

    #if UNITY_EDITOR
    private void OnDrawGizmosSelected()
    {
        if (!Application.isPlaying) return;

        Color oldColor = Gizmos.color;

        float halfFeildOfView = aimAssistMaxAngleToAssist * 0.5f;
        float coneDirection = -90f;

        Quaternion leftRayRotation = Quaternion.AngleAxis(-halfFeildOfView + coneDirection, Vector3.up);
        Quaternion rightRayRotation = Quaternion.AngleAxis(halfFeildOfView + coneDirection, Vector3.up);

        Vector3 leftRayDirection = leftRayRotation * transform.right * aimAssistRadius;
        Vector3 rightRayDirection = rightRayRotation * transform.right * aimAssistRadius;

        // Green Arc
        Handles.color = new Color(0f, 1f, 0f, 0.25f);
        Handles.DrawSolidArc(transform.position, Vector3.up, leftRayDirection, aimAssistMaxAngleToAssist, aimAssistRadius);

        Gizmos.color = oldColor;

    }
     #endif

}
`

This is the code attached to the projectile

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
public class ProjectileScript : MonoBehaviour
{

    public GameObject Explosion;

    public Transform Target;

    Rigidbody _rigidbody;

    public float speed = 1.0f;

    void Start()
    {
        _rigidbody = GetComponent<Rigidbody>();

    }

    void FixedUpdate()
    {
        // _rigidbody.AddForce((Target.position - transform.position).normalized, ForceMode.Impulse);
        Collider targetCollider = Target.GetComponent<Collider>();
        Vector3 targetDirection;
        if (targetCollider)
            targetDirection = targetCollider.ClosestPoint(transform.position) - transform.position;
        else
            targetDirection = Target.position - transform.position;

        _rigidbody.velocity = targetDirection.normalized * speed;
        if (Vector3.Distance(transform.position, Target.position) < 1.0f)
        {
            //make the explosion
            GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;

            //destory the projectile
            Destroy(gameObject);
        }
    }

    public void SetTarget(GameObject target)
    {
        this.Target = target.transform;
    }

    public void SetTarget(ShootHit hit) => SetTarget(hit.gameObject);

}

This script is how and where the Projectile Spawns. It is attached to an empty gameobject located on the muzzle of the gun.

public class ProjectileSpawner : MonoBehaviour
{

    public GameObject projectileInsert;

        public GameObject projectileExtract;
        public float projectileSpeed = 1.0f;

        GameObject projectile;

        public void Insert(GameObject target)
        {
            if (projectile) return;

            projectile = Instantiate(projectileInsert, transform.position, Quaternion.identity);
            ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
            projectileScript.SetTarget(target);
            projectileScript.speed = projectileSpeed;

            // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
            // projectileSpawn.parent.GetComponent<Collider>());

        }

        public void Extract(GameObject target)
        {
            if (projectile) return;

            projectile = Instantiate(projectileExtract, target.transform.position, Quaternion.identity);
            ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
            projectileScript.SetTarget(gameObject);
            projectileScript.speed = projectileSpeed;

            // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
            // projectileSpawn.parent.GetComponent<Collider>());

        }

    }

Body:
In the ProjectileSpawner, add a LayerMask field to filter out invalid collisions (set it in the inspector) for the non-homing projectile. You'll set this in the inspector to make the non-homing projectiles collide with the desired layers:

public LayerMask collisionLayers;

In Insert, find the ray going from the screen's center, and use it and the LayerMask as a parameter to SetTarget:

public void Insert(GameObject target)
{
    if (projectile) return;

    Ray centerRay = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2, Screen.height/2, 0f));

    projectile = Instantiate(projectileInsert, transform.position, Quaternion.identity);
    ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
    projectileScript.SetTarget(centerRay, collisionLayers);
    projectileScript.speed = projectileSpeed;

    // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
    // projectileSpawn.parent.GetComponent<Collider>());

}

public void Extract(GameObject target)
{
    if (projectile) return;

    projectile = Instantiate(projectileExtract, target.transform.position, Quaternion.identity);
    ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
    projectileScript.SetTarget(gameObject);
    projectileScript.speed = projectileSpeed;

    // Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
    // projectileSpawn.parent.GetComponent<Collider>());

}

Then in the ProjectileScript, add a bool field to remember if the projectile homes on a gameObject or if it follows a ray, a Ray field to remember such a ray, and a LayerMask field to remember what to collide with:

public bool isHoming;
public Ray TargetRay
public LayerMask collisionLayers;

Then, in public void SetTarget(GameObject target), set that bool to true:

public void SetTarget(GameObject target)
{
    this.Target = target.transform;
    isHoming = true;
}

And make a new public void SetTarget(Ray shootRay) that remembers a Ray and LayerMask and sets the bool to false:

public void SetTarget(Ray shootRay, LayerMask collisionLayers)
{
    this.TargetRay = shootRay;
    this.collisionLayers = collisionLayers;
    isHoming = false;
}

Also, in ProjectileScript, you will need to change the FixedUpdate method to check if the bool is true, and if it is, then do the same as before. Otherwise, move along the ray and destroy it if it travels too far:

public float maxDistanceBeforeDestroy = 100f;

...

void FixedUpdate()
{
    if (isHoming)
    {
        // _rigidbody.AddForce((Target.position - transform.position).normalized, ForceMode.Impulse);
        Collider targetCollider = Target.GetComponent<Collider>();
        Vector3 targetDirection;
        if (targetCollider)
            targetDirection = targetCollider.ClosestPoint(transform.position) - transform.position;
        else
            targetDirection = Target.position - transform.position;

        _rigidbody.velocity = targetDirection.normalized * speed;
        if (Vector3.Distance(transform.position, Target.position) < 1.0f)
        {
            //make the explosion
            GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;

            //destory the projectile
            Destroy(gameObject);
        }
    }
    else
    {
        _rigidbody.velocity = TargetRay.direction.normalized * speed;

        // Check if it has traveled too far

        if ((transform.position - TargetRay.origin).magnitude > maxDistanceBeforeDestroy )
        {
            Destroy(gameObject);
        }
    }
}

Then, add an OnCollisionEnter method that doesn't do anything if the projectile is homing. But if it isn't, it checks if the collision matches the LayerMask, and if it does, it makes the explosion and destroys the projectile:

void OnCollisionEnter(Collision other)
{
     if (isHoming)
     {
         return;
     }

     if( && ((1<<other.gameObject.layer) & collisionLayers) != 0)
     {
         //make the explosion
        GameObject ThisExplosion = Instantiate(Explosion,
                gameObject.transform.position,
                gameObject.transform.rotation) as GameObject;

        //destroy the projectile
        Destroy(gameObject);
     }
}


问:
On change input value not change in jquery
I have ajax. in

```<code>$.each(data, function(i, item) {
    $('.remaining').val(item.arrears)
});
</code>```

.remaining input value not change on change. Anyone know how to do
this. I am new in JQuery. Below you can find the JQuery I am using.

```<code><script type="text/javascript">
  $("select[name='student_detail_id']").change(function() {
      var student_detail_id = $(this).val();
      console.log(student_detail_id);
      var token = $("input[name='_token']").val();
      $.ajax({
          url: "<?php echo url('admin/remaining_fee') ?>",
          method: 'POST',
          data: { student_detail_id: student_detail_id, _token: token },
          success: function(data) {
            console.log(data);
            $(".remaining").each(function() {
                $(this).find('input').not(':first').remove();
            });

            $.each(data, function(i, item) {
                 $('.remaining').val(item.arrears)

            });
          }
      });
  });
  </script>

<div class="form-group">
 <label for="email">Remaining</label>
 <input type="text" class="form-control remaining" name="" id="" required="" Readonly /></div>
</code>```

I want on change select val() change.

答:
I suggest you replace this:

```<code>$.each(data, function(i, item) {
     $('.remaining').val(item.arrears)
});
</code>```

with this:

```<code>  $("select[name='student_detail_id']").change(function() {
      var student_detail_id = $(this).val();
      console.log(student_detail_id);
      var token = $("input[name='_token']").val();
      $.ajax({
          url: "<?php echo url('admin/remaining_fee') ?>",
          method: 'POST',
          data: { student_detail_id: student_detail_id, _token: token },
          success: function(data) {
            console.log(data);
            $(".remaining").each(function() {
                // here we empty the container to make it ready to add items
                $('.inputContainer').html('');
                //$(this).find('input').not(':first').remove();
            });

            $.each(data, function(i, item) {
                 //here we create an element
                 const $input = $('<input />')
                   .addClass('form-control remaining')
                   .attr('name','remaining')
                   .attr('id', 'remaining_'+i)
                   .attr('type', 'text')
                   .attr('readonly', 'readonly')
                   .val(item.arrears)

                 // here we append it into container
                 $('.inputContainer').append($input);

              });

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

and html something like:

```<code><div class="form-group">
 <label for="email">Remaining</label>
 <input type="text" class="form-control remaining" name="" id="" required="" Readonly />
 <div class="inputContainer" >

 </div>
</div>
</code>```

This is how you add an element with jQuery. and then you can do $('#container').append($element)

Body:
I have ajax. in

$.each(data, function(i, item) {
    $('.remaining').val(item.arrears)
});

.remaining input value not change on change. Anyone know how to do
this. I am new in JQuery. Below you can find the JQuery I am using.

 Remaining
 <input type="text" class="form-control remaining" name="" id="" required="" Readonly />

I want on change select val() change.

Body:
I suggest you replace this:

$.each(data, function(i, item) {
     $('.remaining').val(item.arrears)
});

with this:

  $("select[name='student_detail_id']").change(function() {
      var student_detail_id = $(this).val();
      console.log(student_detail_id);
      var token = $("input[name='_token']").val();
      $.ajax({
          url: "<?php echo url('admin/remaining_fee') ?>",
          method: 'POST',
          data: { student_detail_id: student_detail_id, _token: token },
          success: function(data) {
            console.log(data);
            $(".remaining").each(function() {
                // here we empty the container to make it ready to add items
                $('.inputContainer').html('');
                //$(this).find('input').not(':first').remove();
            });

            $.each(data, function(i, item) {
                 //here we create an element
                 const $input = $('<input />')
                   .addClass('form-control remaining')
                   .attr('name','remaining')
                   .attr('id', 'remaining_'+i)
                   .attr('type', 'text')
                   .attr('readonly', 'readonly')
                   .val(item.arrears)

                 // here we append it into container
                 $('.inputContainer').append($input);

              });

          }
      });
  });

and html something like:

<div class="form-group">
 <label for="email">Remaining</label>
 <input type="text" class="form-control remaining" name="" id="" required="" Readonly />
 <div class="inputContainer" >

 </div>
</div>

This is how you add an element with jQuery. and then you can do $('#container').append($element)


问:
Google Analytics : Hit count limit is per account or per tracking ID
I have a Google Analytics 360 account with limit of 500 million per month. I have created two tracking ids(Properties). My question is 500M limit is per tracking id or for account (all tracking ids)?</p>

答: The limit is for all tracking accounts. The hits are registered for your organization. You can see the total usage under billing->usage.</p>


问:
Google Vision API does not recognize single digits
I have a project that make use of Google Vision API DOCUMENT_TEXT_DETECTION in order to extract text from document images.

Often the API has troubles in recognizing single digits, as you can see in this image:

I suppose that the problem could be related to some algorithm of noise removal, that recognizes isolated single digits as noise. Is there a way to improve Vision response in these situations? (for example managing noise threshold or others parameters)

At other times Vision confuses digits with letters:

But if I specify as parameter languageHints = 'en' or 'mt' these digits are ignored by the ocr. Is there a way to force the recognition of digits or latin characters?

答:
Unfortunately I think the Vision API is optimized for both ends of the spectrum -- dense text (DOCUMENT_TEXT_DETECTION) on one end, and arbitrary bits of text (TEXT_DETECTION) on the other. As you noted in the comments, the regular TEXT_DETECTION works better for these stray single digits while DOCUMENT_TEXT_DETECTION works better overall.

As far as I've heard, there are no current plans to try to cover both of these in a single way, but it's possible that this could improve in the future.

I think there have been other requests to do more fine-tuning and hinting on what you're looking to detect (e.g., here and here), but this doesn't seem to be available yet. Perhaps in the future you'll be able to provide more hints on the format of the text that you're looking to find in images (e.g., phone numbers, single digits, etc).


问:
Get browser download path with javascript
I searched quite a lot for an answer on the web and found nothing.

Is there a way to get the download path of a browser via Javascript?

I don't want to set the path myself i just wanna know where my file goes after been downloaded by the user.

答:
Maybe wrong answers. You can do it with some IE versions. It is valid in case you use it for intranet web development as development of products/workflow that requires files. It does not work with other browsers (Schrome, Firefox, Safari, AFAIK).</p>

```<code><input
type="hidden"
id="steel_that_path"
name="steel_that_path" />

<input type="file"
id="this one you use to upload file"
name="this one you use to upload file"
accept="application/octet-stream"
onBlur="document.getElementById('steal_that_path').value=this.value;"/>
</code>```

Body:
Maybe wrong answers. You can do it with some IE versions. It is valid in case you use it for intranet web development as development of products/workflow that requires files. It does not work with other browsers (Schrome, Firefox, Safari, AFAIK).

<input
type="hidden"
id="steel_that_path"
name="steel_that_path" />

<input type="file"
id="this one you use to upload file"
name="this one you use to upload file"
accept="application/octet-stream"
onBlur="document.getElementById('steal_that_path').value=this.value;"/>


问:
$ Composer can't find mongodb extension, required Mongodb extension
I'm using with latest php version 7.2 on macOS Mojave / macOS Big Sur / macOS Monterey / macOS Ventura and receiving error like

```<code> $composer require mongodb/mongodb
Using version ^1.4 for mongodb/mongodb
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
</code>```

For more information about question : see the screenshoot

Your requirements could not be resolved to an installable set of
packages.

Problem 1
- mongodb/mongodb v1.4.x-dev requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.5.x-dev requires ext-mongodb ^1.6 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.4.2 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.4.1 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.4.0 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
**- Installation request for mongodb/mongodb ^1.4 -> satisfiable by mongodb/mongodb[1.4.0, 1.4.1, 1.4.2, 1.5.x-dev, v1.4.x-dev].

Installation failed, reverting ./composer.json to its original content.

I have already installed mongoDB extension still receiving problem

Not sure what I've missed steps to installation. If anyone can help me with this composer problem, I'd greatly appreciate it. in advance Thanks.

答:
Install PHP extension by running this command on your terminal.

```<code>sudo pecl install mongodb
</code>```

At the end, you will see following information.

```<code>Build process completed successfully
Installing '/usr/local/Cellar/php/7.3.3/pecl/20180731/mongodb.so'
install ok: channel://pecl.php.net/mongodb-1.5.3
Extension mongodb enabled in php.ini
</code>```

and then restart your PHP service.

Body:
I'm using with latest php version 7.2 on macOS Mojave / macOS Big Sur / macOS Monterey / macOS Ventura and receiving error like

 $composer require mongodb/mongodb
Using version ^1.4 for mongodb/mongodb
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)

For more information about question : see the screenshoot

Your requirements could not be resolved to an installable set of
packages.

Problem 1
- mongodb/mongodb v1.4.x-dev requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.5.x-dev requires ext-mongodb ^1.6 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.4.2 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.4.1 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.4.0 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
**- Installation request for mongodb/mongodb ^1.4 -> satisfiable by mongodb/mongodb[1.4.0, 1.4.1, 1.4.2, 1.5.x-dev, v1.4.x-dev].

Installation failed, reverting ./composer.json to its original content.

I have already installed mongoDB extension still receiving problem

Not sure what I've missed steps to installation. If anyone can help me with this composer problem, I'd greatly appreciate it. in advance Thanks.

Body:
Install PHP extension by running this command on your terminal.

sudo pecl install mongodb

At the end, you will see following information.

Build process completed successfully
Installing '/usr/local/Cellar/php/7.3.3/pecl/20180731/mongodb.so'
install ok: channel://pecl.php.net/mongodb-1.5.3
Extension mongodb enabled in php.ini

and then restart your PHP service.


问:
Have fixed parameters in Java constructor - possible?
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

```<code>public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}
</code>```

and then call something along the lines of:

```<code>switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}
</code>```

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.

答:
Another approach is to avoid using a constructor here, and create a static factory method which calls a private constructor:</p>

```<code>class MenuNode {
    private MenuNode() {
        // Does nothing important
    }
    public static MenuNode createStatic(param1, param2, param3) {
         MenuNode result = new MenuNode();
         result.setItemType(ITEM_TYPE_STATIC);
         result.setParam1(param1);
         result.setParam2(param2);
         result.setParam3(param3);
         result.doStuffHere();
         return result;
    }
    public static MenuNode createDynamic(paramX, paramY) {
         MenuNode result = new MenuNode();
         result.setItemType(ITEM_TYPE_DYNAMIC);
         result.setParamX(paramX);
         result.setParamY(paramY);
         result.doStuffHere();
         return result;
    }
</code>```

Body:
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}

and then call something along the lines of:

switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.

Body:
Another approach is to avoid using a constructor here, and create a static factory method which calls a private constructor:

class MenuNode {
    private MenuNode() {
        // Does nothing important
    }
    public static MenuNode createStatic(param1, param2, param3) {
         MenuNode result = new MenuNode();
         result.setItemType(ITEM_TYPE_STATIC);
         result.setParam1(param1);
         result.setParam2(param2);
         result.setParam3(param3);
         result.doStuffHere();
         return result;
    }
    public static MenuNode createDynamic(paramX, paramY) {
         MenuNode result = new MenuNode();
         result.setItemType(ITEM_TYPE_DYNAMIC);
         result.setParamX(paramX);
         result.setParamY(paramY);
         result.doStuffHere();
         return result;
    }


问:
How to Capture text for multiple divs with same data attribute?
Multiple divs contains same html5 data attribute

with same values. Inside each divs are b and p tags with same html 5 data attributes and same values.

requirement is to capture each div values in this format.   and so on. Example  result---
 T1 title1  D1 description1 |  T2 title2  D2 description2 |  T3 title3  D3 description3

Here is the div code

```<code><div data-v-46636d4a="" class="panel_2N_jF">
  <div data-v-46636d4a="" data-purpose="selected-prescription">
    <b data-v-46636d4a="" data-purpose="prescription-name">T1 title1</b>
    <p data-v-46636d4a="" data-purpose="prescription-description">D1 description1</p>
  </div>
  <div data-v-46636d4a="" data-purpose="selected-prescription">
    <b data-v-46636d4a="" data-purpose="prescription-name">T2 title 2</b>
    <p data-v-46636d4a="" data-purpose="prescription-description">D2 description2</p>
  </div>
  <div data-v-46636d4a="" data-purpose="selected-prescription">
    <b data-v-46636d4a="" data-purpose="prescription-name">T3 title3</b>
    <p data-v-46636d4a="" data-purpose="prescription-description">D3 description3</p>
  </div>
</div>
</code>```

I have used simple  this code:

```<code>console.log(
  document.querySelector("body > div:nth-child(1) > div:nth-child(1) > b").textContent + ' '
+ document.querySelector("body > div:nth-child(1) > div:nth-child(1) > p").textContent + ' ' + '|'
+ document.querySelector("body > div:nth-child(1) > div:nth-child(2) > b").textContent + ' '
+ document.querySelector("body > div:nth-child(1) > div:nth-child(2) > p").textContent + ' ' + '|'
+ document.querySelector("body > div:nth-child(1) > div:nth-child(3) > b").textContent + ' '
+ document.querySelector("body > div:nth-child(1) > div:nth-child(3) > p").textContent
);
</code>```

But what is the ideal way to do this for multiple divs.

答:
may be this will help you

var Div_Childs = document.querySelector('div[data-v-46636d4a]').children;

var message = [];

for( var i = 0; i < Div_Childs.length; i++ ) {
  message.push(  Div_Childs[i].querySelector('b').textContent + ' '
                + Div_Childs[i].querySelector('p').textContent );
}

console.log (message.join(' | '));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-v-46636d4a class="panel_2N_jF">
  <div data-v-46636d4a data-purpose="selected-prescription">
    <b data-v-46636d4a data-purpose="prescription-name">T1 title1</b>
    <p data-v-46636d4a data-purpose="prescription-description">D1 description1</p>
  </div>
  <div data-v-46636d4a data-purpose="selected-prescription">
    <b data-v-46636d4a data-purpose="prescription-name">T2 title 2</b>
    <p data-v-46636d4a data-purpose="prescription-description">D2 description2</p>
  </div>
  <div data-v-46636d4a data-purpose="selected-prescription">
    <b data-v-46636d4a data-purpose="prescription-name">T3 title3</b>
    <p data-v-46636d4a data-purpose="prescription-description">D3 description3</p>
  </div>
</div></code>```

?

Body:
Multiple divs contains same html5 data attribute

with same values. Inside each divs are b and p tags with same html 5 data attributes and same values.

requirement is to capture each div values in this format.   and so on. Example  result---
 T1 title1  D1 description1 |  T2 title2  D2 description2 |  T3 title3  D3 description3

Here is the div code

    T1 title1

D1 description1

    T2 title 2

D2 description2

    T3 title3

D3 description3

I have used simple  this code:

console.log(
  document.querySelector("body > div:nth-child(1) > div:nth-child(1) > b").textContent + ' '
+ document.querySelector("body > div:nth-child(1) > div:nth-child(1) > p").textContent + ' ' + '|'
+ document.querySelector("body > div:nth-child(1) > div:nth-child(2) > b").textContent + ' '
+ document.querySelector("body > div:nth-child(1) > div:nth-child(2) > p").textContent + ' ' + '|'
+ document.querySelector("body > div:nth-child(1) > div:nth-child(3) > b").textContent + ' '
+ document.querySelector("body > div:nth-child(1) > div:nth-child(3) > p").textContent
);

But what is the ideal way to do this for multiple divs.

Body:
may be this will help you

var Div_Childs = document.querySelector('div[data-v-46636d4a]').children;

var message = [];

for( var i = 0; i < Div_Childs.length; i++ ) {
  message.push(  Div_Childs[i].querySelector('b').textContent + ' '
                + Div_Childs[i].querySelector('p').textContent );
}

console.log (message.join(' | '));

<div data-v-46636d4a class="panel_2N_jF">
  <div data-v-46636d4a data-purpose="selected-prescription">
    <b data-v-46636d4a data-purpose="prescription-name">T1 title1</b>
    <p data-v-46636d4a data-purpose="prescription-description">D1 description1</p>
  </div>
  <div data-v-46636d4a data-purpose="selected-prescription">
    <b data-v-46636d4a data-purpose="prescription-name">T2 title 2</b>
    <p data-v-46636d4a data-purpose="prescription-description">D2 description2</p>
  </div>
  <div data-v-46636d4a data-purpose="selected-prescription">
    <b data-v-46636d4a data-purpose="prescription-name">T3 title3</b>
    <p data-v-46636d4a data-purpose="prescription-description">D3 description3</p>
  </div>
</div>

?