qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
6,288,261 | How can I get values between two dates in Codeigniter query function? Here is my model and sample code.
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= $today
AND event_enddate >= $today');
return $query;
}
```
But it doesn't work, here is the error I got
```
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 ' at line 1
SELECT FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 AND event_enddate >= 2011-06-09
Filename: C:\xampp\htdocs\hotel\system\database\DB_driver.php
Line Number: 330
``` | 2011/06/09 | [
"https://Stackoverflow.com/questions/6288261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415699/"
] | I think you need qoutes around your date (i.e. '2011-06-08'). try this
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query(
"SELECT FROM tbl_event WHERE event_id = {$id} AND event_startdate <= '{$today}'
AND event_enddate >= '{$today}'");
return $query;
}
```
If your columns `event_startdate` and `event_enddate` are `DATETIME` type but you are only interested in the date part you can do `DATE(event\_enddate) to extract the date part | I think u need to user date\_format(), more information in this link <http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format>.
Try this code:
```
$today = date('Y-m-d');
$query = $this->db->query("SELECT FROM tbl_event WHERE event_id = $id AND DATE_FORMAT(event_startdate ,'%Y-%m-%d') >= DATE_FORMAT($today ,'%Y-%m-%d') AND DATE_FORMAT(event_enddate ,'%Y-%m-%d') <= DATE_FORMAT($today ,'%Y-%m-%d')");
``` |
6,288,261 | How can I get values between two dates in Codeigniter query function? Here is my model and sample code.
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= $today
AND event_enddate >= $today');
return $query;
}
```
But it doesn't work, here is the error I got
```
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 ' at line 1
SELECT FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 AND event_enddate >= 2011-06-09
Filename: C:\xampp\htdocs\hotel\system\database\DB_driver.php
Line Number: 330
``` | 2011/06/09 | [
"https://Stackoverflow.com/questions/6288261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415699/"
] | ```
$this->db->where('date_start <=',date('Y-m-d'));
$this->db->where('date_end >=',date('Y-m-d'));
$query = $this->db->get('table');
``` | I think u need to user date\_format(), more information in this link <http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format>.
Try this code:
```
$today = date('Y-m-d');
$query = $this->db->query("SELECT FROM tbl_event WHERE event_id = $id AND DATE_FORMAT(event_startdate ,'%Y-%m-%d') >= DATE_FORMAT($today ,'%Y-%m-%d') AND DATE_FORMAT(event_enddate ,'%Y-%m-%d') <= DATE_FORMAT($today ,'%Y-%m-%d')");
``` |
6,288,261 | How can I get values between two dates in Codeigniter query function? Here is my model and sample code.
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= $today
AND event_enddate >= $today');
return $query;
}
```
But it doesn't work, here is the error I got
```
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 ' at line 1
SELECT FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 AND event_enddate >= 2011-06-09
Filename: C:\xampp\htdocs\hotel\system\database\DB_driver.php
Line Number: 330
``` | 2011/06/09 | [
"https://Stackoverflow.com/questions/6288261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415699/"
] | I think you need qoutes around your date (i.e. '2011-06-08'). try this
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query(
"SELECT FROM tbl_event WHERE event_id = {$id} AND event_startdate <= '{$today}'
AND event_enddate >= '{$today}'");
return $query;
}
```
If your columns `event_startdate` and `event_enddate` are `DATETIME` type but you are only interested in the date part you can do `DATE(event\_enddate) to extract the date part | Looking into the errors, it seems that your queries are not escaped properly. Add single or double quotes to fix it. Check @danneth answer. Use [Query Binding](http://www.codeigniter.com/user_guide/database/queries.html#query-bindings) which is simple and secure or even more use [Active Record](http://www.codeigniter.com/user_guide/database/query_builder.html#selecting-data). Here are examples of both binding and active record based on your code.
**Query Binding Example**
```
$today = date('Y-m-d');
$sql = 'SELECT
*
FROM
tbl_event
WHERE event_id = ?
AND event_startdate <= ?
AND event_enddate >= ?';
$query = $this->db->query($sql, array($id, $today, $today));
return $query;
```
**Active Record Example**
```
$query = $this->db
->select('*')->from('tbl_event')
->where(array(
'event_id' => $id,
'event_startdate <= ' => $today,
'event_enddate >= ' => $today
))
->get();
return $query;
```
Append `->result()` or `->result_array()` etc to get the result in an object or array. Look into the Codeigniter [Database User Guide](http://www.codeigniter.com/user_guide/database/index.html) for more. |
6,288,261 | How can I get values between two dates in Codeigniter query function? Here is my model and sample code.
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= $today
AND event_enddate >= $today');
return $query;
}
```
But it doesn't work, here is the error I got
```
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 ' at line 1
SELECT FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 AND event_enddate >= 2011-06-09
Filename: C:\xampp\htdocs\hotel\system\database\DB_driver.php
Line Number: 330
``` | 2011/06/09 | [
"https://Stackoverflow.com/questions/6288261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415699/"
] | ```
$this->db->where('date_start <=',date('Y-m-d'));
$this->db->where('date_end >=',date('Y-m-d'));
$query = $this->db->get('table');
``` | Looking into the errors, it seems that your queries are not escaped properly. Add single or double quotes to fix it. Check @danneth answer. Use [Query Binding](http://www.codeigniter.com/user_guide/database/queries.html#query-bindings) which is simple and secure or even more use [Active Record](http://www.codeigniter.com/user_guide/database/query_builder.html#selecting-data). Here are examples of both binding and active record based on your code.
**Query Binding Example**
```
$today = date('Y-m-d');
$sql = 'SELECT
*
FROM
tbl_event
WHERE event_id = ?
AND event_startdate <= ?
AND event_enddate >= ?';
$query = $this->db->query($sql, array($id, $today, $today));
return $query;
```
**Active Record Example**
```
$query = $this->db
->select('*')->from('tbl_event')
->where(array(
'event_id' => $id,
'event_startdate <= ' => $today,
'event_enddate >= ' => $today
))
->get();
return $query;
```
Append `->result()` or `->result_array()` etc to get the result in an object or array. Look into the Codeigniter [Database User Guide](http://www.codeigniter.com/user_guide/database/index.html) for more. |
6,288,261 | How can I get values between two dates in Codeigniter query function? Here is my model and sample code.
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= $today
AND event_enddate >= $today');
return $query;
}
```
But it doesn't work, here is the error I got
```
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 ' at line 1
SELECT FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 AND event_enddate >= 2011-06-09
Filename: C:\xampp\htdocs\hotel\system\database\DB_driver.php
Line Number: 330
``` | 2011/06/09 | [
"https://Stackoverflow.com/questions/6288261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415699/"
] | I think you need qoutes around your date (i.e. '2011-06-08'). try this
```
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query(
"SELECT FROM tbl_event WHERE event_id = {$id} AND event_startdate <= '{$today}'
AND event_enddate >= '{$today}'");
return $query;
}
```
If your columns `event_startdate` and `event_enddate` are `DATETIME` type but you are only interested in the date part you can do `DATE(event\_enddate) to extract the date part | ```
$this->db->where('date_start <=',date('Y-m-d'));
$this->db->where('date_end >=',date('Y-m-d'));
$query = $this->db->get('table');
``` |
339,763 | This is a simple linear fit between height as independent variable and density as dependent variable. I want to know if I can trust that I can use simple linear regression. Goodness of fit shows that the model fits very good.
The residual plot shows high residuals on the highest and lowest y values. How can I find out if its likely that this high residuals are random or not?
[](https://i.stack.imgur.com/AAg3r.jpg)
Linear model Poly1:
f(x) = p1\*x + p2
Coefficients (with 95% confidence bounds):
p1 = -0.0001176 (-0.0001208, -0.0001145)
p2 = 1.255 (1.252, 1.258)
Goodness of fit:
SSE: 4.342e-05
R-square: 0.998
Adjusted R-square: 0.9978
RMSE: 0.001827
[](https://i.stack.imgur.com/OCWKu.jpg) | 2018/04/10 | [
"https://stats.stackexchange.com/questions/339763",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/202403/"
] | If you look at the plot of residuals versus fitted values, you will see that most of the residuals are negative (hence located below the horizontal line going through zero). This suggests that your model tends to overestimate the mean value of density at a given height and it can't be trusted for estimation or prediction. Either a linear relationship between the two variables is not appropriate or it may be appropriate after transforming one or both of the variables (e.g., log-transformation). | Consider to **rescale** your independent variable as it's too big for the y-axis. You're forcing your slope to zero, so your model is marginally better than the only-intercept model. Rescale it to something like **Hoyde per 1000.** |
58,621,021 | Assume that i put `' 123abc'` as input in C++ console application.
if i get input as
```
int a; char ch;
scanf("%d", &a);
scanf("%ch", &ch);
```
i got 123 in a, 'a' in ch. Right?
Then, where does 4 blanks go? scanf just blow away blanks?
Is there no way can i get that blanks after i get 123abc?
To sum it up my question,
1. When i get int input with scanf, does scanf blow away blank in buffer?
What does happen i execute that code?
2. Can i get 4 blanks in ' 123abc' after i get '123' and 'a'? | 2019/10/30 | [
"https://Stackoverflow.com/questions/58621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12295807/"
] | Only devices with API29 provide more biometric options than fingerprint.
By checking the `android.hardware.biometrics.BiometricManager.hasBiometrics()` (API29) you can understand how to inspect what biometrics are available:
```
final PackageManager pm = context.getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)
|| pm.hasSystemFeature(PackageManager.FEATURE_IRIS)
|| pm.hasSystemFeature(PackageManager.FEATURE_FACE);
``` | The `BiometricManager` API seems to be designed so that the calling app must be agnostic to the authentication method used. So that it does not make a difference how user authenticates as long as he succeeds (along with this come requirements for strong authentication on the vendor side <https://source.android.com/security/biometric>).
As a result, the bad thing: you cannot have a title matching the authentication method, so you should come up with something generic like "*Please authorize the operation*". The good news is that the dialog prompt is already presenting by in accordance with supported authentication method (e.g. for fingerprint authentication the UI presents text "Touch the fingerprint sensor" along the matching icon). This is done by the platform and cannot be controlled by the calling app.
Partial solution: You can check specifically about the availability of fingerprint authentication by using the (now deprecated) API <https://developer.android.com/reference/android/hardware/fingerprint/FingerprintManager> |
58,621,021 | Assume that i put `' 123abc'` as input in C++ console application.
if i get input as
```
int a; char ch;
scanf("%d", &a);
scanf("%ch", &ch);
```
i got 123 in a, 'a' in ch. Right?
Then, where does 4 blanks go? scanf just blow away blanks?
Is there no way can i get that blanks after i get 123abc?
To sum it up my question,
1. When i get int input with scanf, does scanf blow away blank in buffer?
What does happen i execute that code?
2. Can i get 4 blanks in ' 123abc' after i get '123' and 'a'? | 2019/10/30 | [
"https://Stackoverflow.com/questions/58621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12295807/"
] | It seems that it is not possible to find out the actual biometric method being used on Android (unlike on iOS). But it is possible to detect supported biometric methods on Android 10:
```
PackageManager pm = context.getPackageManager();
boolean hasFingerprint = pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
boolean hasFace = pm.hasSystemFeature(PackageManager.FEATURE_FACE);
boolean hasIris = pm.hasSystemFeature(PackageManager.FEATURE_IRIS);
```
Therefore if the phone supports only face feature you can use "Login with Face" in the GUI. If it supports only fingerprint feature you can use "Login with Fingerprint", etc.
If it supports multiple biometric methods you will have to use some generic text like "Biometric login". | The `BiometricManager` API seems to be designed so that the calling app must be agnostic to the authentication method used. So that it does not make a difference how user authenticates as long as he succeeds (along with this come requirements for strong authentication on the vendor side <https://source.android.com/security/biometric>).
As a result, the bad thing: you cannot have a title matching the authentication method, so you should come up with something generic like "*Please authorize the operation*". The good news is that the dialog prompt is already presenting by in accordance with supported authentication method (e.g. for fingerprint authentication the UI presents text "Touch the fingerprint sensor" along the matching icon). This is done by the platform and cannot be controlled by the calling app.
Partial solution: You can check specifically about the availability of fingerprint authentication by using the (now deprecated) API <https://developer.android.com/reference/android/hardware/fingerprint/FingerprintManager> |
58,621,021 | Assume that i put `' 123abc'` as input in C++ console application.
if i get input as
```
int a; char ch;
scanf("%d", &a);
scanf("%ch", &ch);
```
i got 123 in a, 'a' in ch. Right?
Then, where does 4 blanks go? scanf just blow away blanks?
Is there no way can i get that blanks after i get 123abc?
To sum it up my question,
1. When i get int input with scanf, does scanf blow away blank in buffer?
What does happen i execute that code?
2. Can i get 4 blanks in ' 123abc' after i get '123' and 'a'? | 2019/10/30 | [
"https://Stackoverflow.com/questions/58621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12295807/"
] | The `BiometricManager` API seems to be designed so that the calling app must be agnostic to the authentication method used. So that it does not make a difference how user authenticates as long as he succeeds (along with this come requirements for strong authentication on the vendor side <https://source.android.com/security/biometric>).
As a result, the bad thing: you cannot have a title matching the authentication method, so you should come up with something generic like "*Please authorize the operation*". The good news is that the dialog prompt is already presenting by in accordance with supported authentication method (e.g. for fingerprint authentication the UI presents text "Touch the fingerprint sensor" along the matching icon). This is done by the platform and cannot be controlled by the calling app.
Partial solution: You can check specifically about the availability of fingerprint authentication by using the (now deprecated) API <https://developer.android.com/reference/android/hardware/fingerprint/FingerprintManager> | [The official recommendation](https://medium.com/@isaidamier/migrating-from-fingerprintmanager-to-biometricprompt-4bc5f570dccd) is that you use the [AndroidX Biometric Library](https://developer.android.com/jetpack/androidx/releases/biometric). It comes with a standard UI that handles form-factors for you. Essentially it detects whether a device has fingerprint or face authentication form factor and handles it: as a developer you do not need to create a biometrics authentication UI. To check whether a device supports biometrics at all, you would do
```
override fun onClick(view: View) { // user clicks to authenticate
val promptInfo = createPromptInfo()
if (BiometricManager.from(context)
.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS) {
biometricPrompt.authenticate(promptInfo, cryptoObject)
} else {
loginWithAppAccountPassword()
}
}
```
Reasons you should use the Biometric Support Library:
* Developers no longer need to anticipate different API levels in their code because the library handles all API matching under the hood. For instance, the support library seamlessly uses FingerprintManager on API levels 23 to 27 and BiometricPrompt on API level 28 and above.
* Developers no longer need to create their own authentication UI. The library provides a standard and familiar UI that matches a user’s biometric authentication form factor, such as fingerprint or face authentication.
* Developers can check if a device supports biometric authentication with a single method call. |
58,621,021 | Assume that i put `' 123abc'` as input in C++ console application.
if i get input as
```
int a; char ch;
scanf("%d", &a);
scanf("%ch", &ch);
```
i got 123 in a, 'a' in ch. Right?
Then, where does 4 blanks go? scanf just blow away blanks?
Is there no way can i get that blanks after i get 123abc?
To sum it up my question,
1. When i get int input with scanf, does scanf blow away blank in buffer?
What does happen i execute that code?
2. Can i get 4 blanks in ' 123abc' after i get '123' and 'a'? | 2019/10/30 | [
"https://Stackoverflow.com/questions/58621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12295807/"
] | The `BiometricManager` API seems to be designed so that the calling app must be agnostic to the authentication method used. So that it does not make a difference how user authenticates as long as he succeeds (along with this come requirements for strong authentication on the vendor side <https://source.android.com/security/biometric>).
As a result, the bad thing: you cannot have a title matching the authentication method, so you should come up with something generic like "*Please authorize the operation*". The good news is that the dialog prompt is already presenting by in accordance with supported authentication method (e.g. for fingerprint authentication the UI presents text "Touch the fingerprint sensor" along the matching icon). This is done by the platform and cannot be controlled by the calling app.
Partial solution: You can check specifically about the availability of fingerprint authentication by using the (now deprecated) API <https://developer.android.com/reference/android/hardware/fingerprint/FingerprintManager> | Using `PackageManager` allows to check which biometrics are supported. [Here](https://handstandsam.com/2020/01/03/android-biometrics-ux-guide-user-messaging/) is an article proposing how to deal with showing strings which are understandable for the user. |
58,621,021 | Assume that i put `' 123abc'` as input in C++ console application.
if i get input as
```
int a; char ch;
scanf("%d", &a);
scanf("%ch", &ch);
```
i got 123 in a, 'a' in ch. Right?
Then, where does 4 blanks go? scanf just blow away blanks?
Is there no way can i get that blanks after i get 123abc?
To sum it up my question,
1. When i get int input with scanf, does scanf blow away blank in buffer?
What does happen i execute that code?
2. Can i get 4 blanks in ' 123abc' after i get '123' and 'a'? | 2019/10/30 | [
"https://Stackoverflow.com/questions/58621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12295807/"
] | Only devices with API29 provide more biometric options than fingerprint.
By checking the `android.hardware.biometrics.BiometricManager.hasBiometrics()` (API29) you can understand how to inspect what biometrics are available:
```
final PackageManager pm = context.getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)
|| pm.hasSystemFeature(PackageManager.FEATURE_IRIS)
|| pm.hasSystemFeature(PackageManager.FEATURE_FACE);
``` | It seems that it is not possible to find out the actual biometric method being used on Android (unlike on iOS). But it is possible to detect supported biometric methods on Android 10:
```
PackageManager pm = context.getPackageManager();
boolean hasFingerprint = pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
boolean hasFace = pm.hasSystemFeature(PackageManager.FEATURE_FACE);
boolean hasIris = pm.hasSystemFeature(PackageManager.FEATURE_IRIS);
```
Therefore if the phone supports only face feature you can use "Login with Face" in the GUI. If it supports only fingerprint feature you can use "Login with Fingerprint", etc.
If it supports multiple biometric methods you will have to use some generic text like "Biometric login". |
58,621,021 | Assume that i put `' 123abc'` as input in C++ console application.
if i get input as
```
int a; char ch;
scanf("%d", &a);
scanf("%ch", &ch);
```
i got 123 in a, 'a' in ch. Right?
Then, where does 4 blanks go? scanf just blow away blanks?
Is there no way can i get that blanks after i get 123abc?
To sum it up my question,
1. When i get int input with scanf, does scanf blow away blank in buffer?
What does happen i execute that code?
2. Can i get 4 blanks in ' 123abc' after i get '123' and 'a'? | 2019/10/30 | [
"https://Stackoverflow.com/questions/58621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12295807/"
] | Only devices with API29 provide more biometric options than fingerprint.
By checking the `android.hardware.biometrics.BiometricManager.hasBiometrics()` (API29) you can understand how to inspect what biometrics are available:
```
final PackageManager pm = context.getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)
|| pm.hasSystemFeature(PackageManager.FEATURE_IRIS)
|| pm.hasSystemFeature(PackageManager.FEATURE_FACE);
``` | [The official recommendation](https://medium.com/@isaidamier/migrating-from-fingerprintmanager-to-biometricprompt-4bc5f570dccd) is that you use the [AndroidX Biometric Library](https://developer.android.com/jetpack/androidx/releases/biometric). It comes with a standard UI that handles form-factors for you. Essentially it detects whether a device has fingerprint or face authentication form factor and handles it: as a developer you do not need to create a biometrics authentication UI. To check whether a device supports biometrics at all, you would do
```
override fun onClick(view: View) { // user clicks to authenticate
val promptInfo = createPromptInfo()
if (BiometricManager.from(context)
.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS) {
biometricPrompt.authenticate(promptInfo, cryptoObject)
} else {
loginWithAppAccountPassword()
}
}
```
Reasons you should use the Biometric Support Library:
* Developers no longer need to anticipate different API levels in their code because the library handles all API matching under the hood. For instance, the support library seamlessly uses FingerprintManager on API levels 23 to 27 and BiometricPrompt on API level 28 and above.
* Developers no longer need to create their own authentication UI. The library provides a standard and familiar UI that matches a user’s biometric authentication form factor, such as fingerprint or face authentication.
* Developers can check if a device supports biometric authentication with a single method call. |
58,621,021 | Assume that i put `' 123abc'` as input in C++ console application.
if i get input as
```
int a; char ch;
scanf("%d", &a);
scanf("%ch", &ch);
```
i got 123 in a, 'a' in ch. Right?
Then, where does 4 blanks go? scanf just blow away blanks?
Is there no way can i get that blanks after i get 123abc?
To sum it up my question,
1. When i get int input with scanf, does scanf blow away blank in buffer?
What does happen i execute that code?
2. Can i get 4 blanks in ' 123abc' after i get '123' and 'a'? | 2019/10/30 | [
"https://Stackoverflow.com/questions/58621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12295807/"
] | Only devices with API29 provide more biometric options than fingerprint.
By checking the `android.hardware.biometrics.BiometricManager.hasBiometrics()` (API29) you can understand how to inspect what biometrics are available:
```
final PackageManager pm = context.getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)
|| pm.hasSystemFeature(PackageManager.FEATURE_IRIS)
|| pm.hasSystemFeature(PackageManager.FEATURE_FACE);
``` | Using `PackageManager` allows to check which biometrics are supported. [Here](https://handstandsam.com/2020/01/03/android-biometrics-ux-guide-user-messaging/) is an article proposing how to deal with showing strings which are understandable for the user. |
58,621,021 | Assume that i put `' 123abc'` as input in C++ console application.
if i get input as
```
int a; char ch;
scanf("%d", &a);
scanf("%ch", &ch);
```
i got 123 in a, 'a' in ch. Right?
Then, where does 4 blanks go? scanf just blow away blanks?
Is there no way can i get that blanks after i get 123abc?
To sum it up my question,
1. When i get int input with scanf, does scanf blow away blank in buffer?
What does happen i execute that code?
2. Can i get 4 blanks in ' 123abc' after i get '123' and 'a'? | 2019/10/30 | [
"https://Stackoverflow.com/questions/58621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12295807/"
] | It seems that it is not possible to find out the actual biometric method being used on Android (unlike on iOS). But it is possible to detect supported biometric methods on Android 10:
```
PackageManager pm = context.getPackageManager();
boolean hasFingerprint = pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
boolean hasFace = pm.hasSystemFeature(PackageManager.FEATURE_FACE);
boolean hasIris = pm.hasSystemFeature(PackageManager.FEATURE_IRIS);
```
Therefore if the phone supports only face feature you can use "Login with Face" in the GUI. If it supports only fingerprint feature you can use "Login with Fingerprint", etc.
If it supports multiple biometric methods you will have to use some generic text like "Biometric login". | [The official recommendation](https://medium.com/@isaidamier/migrating-from-fingerprintmanager-to-biometricprompt-4bc5f570dccd) is that you use the [AndroidX Biometric Library](https://developer.android.com/jetpack/androidx/releases/biometric). It comes with a standard UI that handles form-factors for you. Essentially it detects whether a device has fingerprint or face authentication form factor and handles it: as a developer you do not need to create a biometrics authentication UI. To check whether a device supports biometrics at all, you would do
```
override fun onClick(view: View) { // user clicks to authenticate
val promptInfo = createPromptInfo()
if (BiometricManager.from(context)
.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS) {
biometricPrompt.authenticate(promptInfo, cryptoObject)
} else {
loginWithAppAccountPassword()
}
}
```
Reasons you should use the Biometric Support Library:
* Developers no longer need to anticipate different API levels in their code because the library handles all API matching under the hood. For instance, the support library seamlessly uses FingerprintManager on API levels 23 to 27 and BiometricPrompt on API level 28 and above.
* Developers no longer need to create their own authentication UI. The library provides a standard and familiar UI that matches a user’s biometric authentication form factor, such as fingerprint or face authentication.
* Developers can check if a device supports biometric authentication with a single method call. |
58,621,021 | Assume that i put `' 123abc'` as input in C++ console application.
if i get input as
```
int a; char ch;
scanf("%d", &a);
scanf("%ch", &ch);
```
i got 123 in a, 'a' in ch. Right?
Then, where does 4 blanks go? scanf just blow away blanks?
Is there no way can i get that blanks after i get 123abc?
To sum it up my question,
1. When i get int input with scanf, does scanf blow away blank in buffer?
What does happen i execute that code?
2. Can i get 4 blanks in ' 123abc' after i get '123' and 'a'? | 2019/10/30 | [
"https://Stackoverflow.com/questions/58621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12295807/"
] | It seems that it is not possible to find out the actual biometric method being used on Android (unlike on iOS). But it is possible to detect supported biometric methods on Android 10:
```
PackageManager pm = context.getPackageManager();
boolean hasFingerprint = pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
boolean hasFace = pm.hasSystemFeature(PackageManager.FEATURE_FACE);
boolean hasIris = pm.hasSystemFeature(PackageManager.FEATURE_IRIS);
```
Therefore if the phone supports only face feature you can use "Login with Face" in the GUI. If it supports only fingerprint feature you can use "Login with Fingerprint", etc.
If it supports multiple biometric methods you will have to use some generic text like "Biometric login". | Using `PackageManager` allows to check which biometrics are supported. [Here](https://handstandsam.com/2020/01/03/android-biometrics-ux-guide-user-messaging/) is an article proposing how to deal with showing strings which are understandable for the user. |
58,621,021 | Assume that i put `' 123abc'` as input in C++ console application.
if i get input as
```
int a; char ch;
scanf("%d", &a);
scanf("%ch", &ch);
```
i got 123 in a, 'a' in ch. Right?
Then, where does 4 blanks go? scanf just blow away blanks?
Is there no way can i get that blanks after i get 123abc?
To sum it up my question,
1. When i get int input with scanf, does scanf blow away blank in buffer?
What does happen i execute that code?
2. Can i get 4 blanks in ' 123abc' after i get '123' and 'a'? | 2019/10/30 | [
"https://Stackoverflow.com/questions/58621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12295807/"
] | [The official recommendation](https://medium.com/@isaidamier/migrating-from-fingerprintmanager-to-biometricprompt-4bc5f570dccd) is that you use the [AndroidX Biometric Library](https://developer.android.com/jetpack/androidx/releases/biometric). It comes with a standard UI that handles form-factors for you. Essentially it detects whether a device has fingerprint or face authentication form factor and handles it: as a developer you do not need to create a biometrics authentication UI. To check whether a device supports biometrics at all, you would do
```
override fun onClick(view: View) { // user clicks to authenticate
val promptInfo = createPromptInfo()
if (BiometricManager.from(context)
.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS) {
biometricPrompt.authenticate(promptInfo, cryptoObject)
} else {
loginWithAppAccountPassword()
}
}
```
Reasons you should use the Biometric Support Library:
* Developers no longer need to anticipate different API levels in their code because the library handles all API matching under the hood. For instance, the support library seamlessly uses FingerprintManager on API levels 23 to 27 and BiometricPrompt on API level 28 and above.
* Developers no longer need to create their own authentication UI. The library provides a standard and familiar UI that matches a user’s biometric authentication form factor, such as fingerprint or face authentication.
* Developers can check if a device supports biometric authentication with a single method call. | Using `PackageManager` allows to check which biometrics are supported. [Here](https://handstandsam.com/2020/01/03/android-biometrics-ux-guide-user-messaging/) is an article proposing how to deal with showing strings which are understandable for the user. |
173,506 | I want to get a **prefab asset** (that resides in **Project Window**) and assign it to a field like the one you get when you manually drag the prefab asset from **Project Window** to GameObject field:
[](https://i.stack.imgur.com/TRDwa.png)
But when I try to do the same thing in code (and in Edit Mode) with this function:
```
GameObject prefab_instance = PrefabUtility.GetNearestPrefabInstanceRoot(gameobj) as GameObject;
```
I get a **prefab instance** but not a **prefab asset**:
[](https://i.stack.imgur.com/YoPAM.png) [](https://i.stack.imgur.com/TRDwa.png)
How do I get a reference to **prefab asset** from the gameobject that was created from it? | 2019/07/07 | [
"https://gamedev.stackexchange.com/questions/173506",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/123486/"
] | If I understand what you want to do, then I think you want to use PrefabUtility.[GetPrefabAssetPathOfNearestInstanceRoot](https://docs.unity3d.com/ScriptReference/PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot.html) in combination with AssetDatabase.[LoadAssetAtPath](https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html).
Like so:
```
string path = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(gameobj);
GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path);
Debug.Log(go.name, go);
``` | If you want to find prefab variant of an instance you should use
```
PrefabUtility.GetCorrespondingObjectFromSource(YourPrefabInstance)
```
If you want to find orginal prefab of an instance you should use
```
PrefabUtility.GetCorrespondingObjectFromOriginalSource(YourPrefabInstance)
```
It will work only in Editor mode. |
28,728,891 | Have the following C# code for loading and unloading a C++ DLL.
I load DLL only once, but code has to unload DLL 2 times. Also after unloading DLL, when I load it again, and I call DLL's exported function, I get the following error message:
>
> Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
>
>
>
DLL depends on other DLLs.
```
/// //////////////handle of FDD DLL:
System.IntPtr SystemIntPtr_handle_of_DLL=System.IntPtr.Zero;
private void button4_Click(object sender, EventArgs e)
{
try
{
string string_Dependency_path = ".\\DLL_Dependencies\\";
Call_DLL.SetDllDirectory(string_Dependency_path);
SystemIntPtr_handle_of_DLL = Call_DLL.LoadLibrary("DLL.dll");
if (SystemIntPtr_handle_of_DLL == System.IntPtr.Zero) { throw new Exception("DLL did not load"); }
}
catch (Exception Exception_Object) { MessageBox.Show(Exception_Object.Message); }
}
private void button5_Click(object sender, EventArgs e)
{
try
{
int int_FreeLibrary_counter = 0;
while (Call_DLL.FreeLibrary(SystemIntPtr_handle_of_DLL))
{
int_FreeLibrary_counter++;
}
MessageBox.Show("DLL unloaded. You will have to load it again. (Unloaded" + int_FreeLibrary_counter + " times)");
}
catch (Exception Exception_Object) { MessageBox.Show(Exception_Object.Message); }
}
```
The invoke method:
```
class Call_DLL
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDllDirectory(string string_Dependency_path);
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string string_DLL_name);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FreeLibrary(IntPtr IntPtr_handle_of_DLL);
}
```
EDIT
----
I forgot to include the following which call DLL exported functions, after loading DLL and before unloading DLL. It makes sense to think that something else is going on inside these exported functions which is causing strange behavior (i.e. loading 1 time, having to unload 2 times):
```
[DllImport(@"DLL.dll", EntryPoint = "getFreq")]
public static extern System.IntPtr getFreq([In, Out, MarshalAs(UnmanagedType.LPStr)] string char_Address, [In, Out, MarshalAs(UnmanagedType.I4)]int int_Num, [In, Out, MarshalAs(UnmanagedType.I4)]int int_Samp);
[DllImport(@"DLL.dll", EntryPoint = "setNat")]
public static extern System.IntPtr setNat([In, Out, MarshalAs(UnmanagedType.LPStr)]string char_Address_File_nat);
[DllImport(@"DLL.dll", EntryPoint = "getMode")]
public static extern System.IntPtr getMode();
``` | 2015/02/25 | [
"https://Stackoverflow.com/questions/28728891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3405291/"
] | If you only call LoadLibrary once then you only need to call FreeLibrary once as well. Calling it a second time is moving into undefined behavior.
If you look at the MSDN docs <https://msdn.microsoft.com/en-us/library/windows/desktop/ms683152%28v=vs.85%29.aspx> the function returns a non zero value if it succeeds, or 0 if there is an error.
If you want to be sure that its unloaded then you can call GetModuleHandle on it after the call to FreeLibrary and it should return null.
<https://msdn.microsoft.com/en-us/library/windows/desktop/ms683199(v=vs.85).aspx>
Updated your invoke method class to include:
```
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
```
Then change your button5 click handler to the following:
```
private void button5_Click(object sender, EventArgs e)
{
try
{
int freeCount = 0;
while(Call_DLL.GetModuleHandle("DLL.dll") != System.IntPtr.Zero)
{
Call_DLL.FreeLibrary(SystemIntPtr_handle_of_DLL);
freeCount++;
}
MessageBox.Show("DLL unloaded. You will have to load it again. (Unloaded" + int_FreeLibrary_counter + " times)");
}
catch(Exception Exception_Object)
{
MessageBox.Show(Exception_Object.Message);
}
}
``` | According to <https://msdn.microsoft.com/en-us/library/windows/desktop/ms683152%28v=vs.85%29.aspx> (the first google hit) `If the function succeeds, the return value is nonzero.` Your unload loop basically says "as long as freeing the library worked, free it again, until the unload fails". |
28,728,891 | Have the following C# code for loading and unloading a C++ DLL.
I load DLL only once, but code has to unload DLL 2 times. Also after unloading DLL, when I load it again, and I call DLL's exported function, I get the following error message:
>
> Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
>
>
>
DLL depends on other DLLs.
```
/// //////////////handle of FDD DLL:
System.IntPtr SystemIntPtr_handle_of_DLL=System.IntPtr.Zero;
private void button4_Click(object sender, EventArgs e)
{
try
{
string string_Dependency_path = ".\\DLL_Dependencies\\";
Call_DLL.SetDllDirectory(string_Dependency_path);
SystemIntPtr_handle_of_DLL = Call_DLL.LoadLibrary("DLL.dll");
if (SystemIntPtr_handle_of_DLL == System.IntPtr.Zero) { throw new Exception("DLL did not load"); }
}
catch (Exception Exception_Object) { MessageBox.Show(Exception_Object.Message); }
}
private void button5_Click(object sender, EventArgs e)
{
try
{
int int_FreeLibrary_counter = 0;
while (Call_DLL.FreeLibrary(SystemIntPtr_handle_of_DLL))
{
int_FreeLibrary_counter++;
}
MessageBox.Show("DLL unloaded. You will have to load it again. (Unloaded" + int_FreeLibrary_counter + " times)");
}
catch (Exception Exception_Object) { MessageBox.Show(Exception_Object.Message); }
}
```
The invoke method:
```
class Call_DLL
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDllDirectory(string string_Dependency_path);
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string string_DLL_name);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FreeLibrary(IntPtr IntPtr_handle_of_DLL);
}
```
EDIT
----
I forgot to include the following which call DLL exported functions, after loading DLL and before unloading DLL. It makes sense to think that something else is going on inside these exported functions which is causing strange behavior (i.e. loading 1 time, having to unload 2 times):
```
[DllImport(@"DLL.dll", EntryPoint = "getFreq")]
public static extern System.IntPtr getFreq([In, Out, MarshalAs(UnmanagedType.LPStr)] string char_Address, [In, Out, MarshalAs(UnmanagedType.I4)]int int_Num, [In, Out, MarshalAs(UnmanagedType.I4)]int int_Samp);
[DllImport(@"DLL.dll", EntryPoint = "setNat")]
public static extern System.IntPtr setNat([In, Out, MarshalAs(UnmanagedType.LPStr)]string char_Address_File_nat);
[DllImport(@"DLL.dll", EntryPoint = "getMode")]
public static extern System.IntPtr getMode();
``` | 2015/02/25 | [
"https://Stackoverflow.com/questions/28728891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3405291/"
] | The update to your question provides enough information to explain the behaviour.
1. You call `LoadLibrary` to load your DLL which accounts for one of the references.
2. You call `DllImport` p/invoke functions which in turn lead to a call to `LoadLibrary`. That's the other reference to the library.
3. Then when you call `FreeLibrary`, this succeeds twice since there were two calls to `LoadLibrary`.
But now you are in trouble because you've gone behind the back of the p/invoke system and it still believes that it owns one of the references to the DLL. A reference that you stole from it with your second call to `FreeLibrary`.
I guess that the information you are missing is how the `DllImport` p/invokes bind to the function. You are hoping that they will obtain a module handle by calling `GetModuleHandle`. They don't. They call `LoadLibrary`. They do this the first time they are called and the module they load stays loaded until the assembly itself unloads.
What you have to do, above all else, is follow the rules. The rules state that each call to `LoadLibrary` is to be matched by a call to `FreeLibrary`. You call `LoadLibrary` once. So you must call `FreeLibrary` exactly once also. Stop calling it twice and all is well.
I suspect that you are actually trying to arrange a system whereby you can load and unload DLLs. This prevents you from using p/invoke via `DllImport`. You'll have to do it all with `LoadLibrary` and `GetProcAddress`.
Your usage of `SetDllDirectory` looks somewhat messed up. What do you expect `".\\DLL_Dependencies\\"` to be relative to? Supply a full path. | According to <https://msdn.microsoft.com/en-us/library/windows/desktop/ms683152%28v=vs.85%29.aspx> (the first google hit) `If the function succeeds, the return value is nonzero.` Your unload loop basically says "as long as freeing the library worked, free it again, until the unload fails". |
28,728,891 | Have the following C# code for loading and unloading a C++ DLL.
I load DLL only once, but code has to unload DLL 2 times. Also after unloading DLL, when I load it again, and I call DLL's exported function, I get the following error message:
>
> Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
>
>
>
DLL depends on other DLLs.
```
/// //////////////handle of FDD DLL:
System.IntPtr SystemIntPtr_handle_of_DLL=System.IntPtr.Zero;
private void button4_Click(object sender, EventArgs e)
{
try
{
string string_Dependency_path = ".\\DLL_Dependencies\\";
Call_DLL.SetDllDirectory(string_Dependency_path);
SystemIntPtr_handle_of_DLL = Call_DLL.LoadLibrary("DLL.dll");
if (SystemIntPtr_handle_of_DLL == System.IntPtr.Zero) { throw new Exception("DLL did not load"); }
}
catch (Exception Exception_Object) { MessageBox.Show(Exception_Object.Message); }
}
private void button5_Click(object sender, EventArgs e)
{
try
{
int int_FreeLibrary_counter = 0;
while (Call_DLL.FreeLibrary(SystemIntPtr_handle_of_DLL))
{
int_FreeLibrary_counter++;
}
MessageBox.Show("DLL unloaded. You will have to load it again. (Unloaded" + int_FreeLibrary_counter + " times)");
}
catch (Exception Exception_Object) { MessageBox.Show(Exception_Object.Message); }
}
```
The invoke method:
```
class Call_DLL
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDllDirectory(string string_Dependency_path);
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string string_DLL_name);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FreeLibrary(IntPtr IntPtr_handle_of_DLL);
}
```
EDIT
----
I forgot to include the following which call DLL exported functions, after loading DLL and before unloading DLL. It makes sense to think that something else is going on inside these exported functions which is causing strange behavior (i.e. loading 1 time, having to unload 2 times):
```
[DllImport(@"DLL.dll", EntryPoint = "getFreq")]
public static extern System.IntPtr getFreq([In, Out, MarshalAs(UnmanagedType.LPStr)] string char_Address, [In, Out, MarshalAs(UnmanagedType.I4)]int int_Num, [In, Out, MarshalAs(UnmanagedType.I4)]int int_Samp);
[DllImport(@"DLL.dll", EntryPoint = "setNat")]
public static extern System.IntPtr setNat([In, Out, MarshalAs(UnmanagedType.LPStr)]string char_Address_File_nat);
[DllImport(@"DLL.dll", EntryPoint = "getMode")]
public static extern System.IntPtr getMode();
``` | 2015/02/25 | [
"https://Stackoverflow.com/questions/28728891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3405291/"
] | I know that this question come to completion, but working on a similar problem I have found a way to load and unload library dynamically using DllImport and without exceptions.
The approach is based on these stakeholders:
**- the DllImport load the library on the first call to a method wrapped.
- if a library is alredy loaded on the stack the call to a method will use this instance of the library instead load another one**
based on these considerations you can manage your module in this way:
1. implement your class which wrap the library
```
public class MyWrapper
{
int _libraryHandle = 0;
[DllImport("mylibrary.dll")]
public external static void MyMethod();
}
```
2. in the constructor load the library using LoadLibrary:
```
public MyWrapper()
{
_libraryHandle = LoadLibrary("mylibrary.dll");
}
```
3. in the dispose method unload the library using FreeLibrary:
```
public Dispose()
{
FreeLibrary(_libraryHandle);
}
```
in this way everytime you'll instance your wrapper a new occurrence of the library will be loaded on the stack without any exception. | According to <https://msdn.microsoft.com/en-us/library/windows/desktop/ms683152%28v=vs.85%29.aspx> (the first google hit) `If the function succeeds, the return value is nonzero.` Your unload loop basically says "as long as freeing the library worked, free it again, until the unload fails". |
28,728,891 | Have the following C# code for loading and unloading a C++ DLL.
I load DLL only once, but code has to unload DLL 2 times. Also after unloading DLL, when I load it again, and I call DLL's exported function, I get the following error message:
>
> Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
>
>
>
DLL depends on other DLLs.
```
/// //////////////handle of FDD DLL:
System.IntPtr SystemIntPtr_handle_of_DLL=System.IntPtr.Zero;
private void button4_Click(object sender, EventArgs e)
{
try
{
string string_Dependency_path = ".\\DLL_Dependencies\\";
Call_DLL.SetDllDirectory(string_Dependency_path);
SystemIntPtr_handle_of_DLL = Call_DLL.LoadLibrary("DLL.dll");
if (SystemIntPtr_handle_of_DLL == System.IntPtr.Zero) { throw new Exception("DLL did not load"); }
}
catch (Exception Exception_Object) { MessageBox.Show(Exception_Object.Message); }
}
private void button5_Click(object sender, EventArgs e)
{
try
{
int int_FreeLibrary_counter = 0;
while (Call_DLL.FreeLibrary(SystemIntPtr_handle_of_DLL))
{
int_FreeLibrary_counter++;
}
MessageBox.Show("DLL unloaded. You will have to load it again. (Unloaded" + int_FreeLibrary_counter + " times)");
}
catch (Exception Exception_Object) { MessageBox.Show(Exception_Object.Message); }
}
```
The invoke method:
```
class Call_DLL
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDllDirectory(string string_Dependency_path);
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string string_DLL_name);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FreeLibrary(IntPtr IntPtr_handle_of_DLL);
}
```
EDIT
----
I forgot to include the following which call DLL exported functions, after loading DLL and before unloading DLL. It makes sense to think that something else is going on inside these exported functions which is causing strange behavior (i.e. loading 1 time, having to unload 2 times):
```
[DllImport(@"DLL.dll", EntryPoint = "getFreq")]
public static extern System.IntPtr getFreq([In, Out, MarshalAs(UnmanagedType.LPStr)] string char_Address, [In, Out, MarshalAs(UnmanagedType.I4)]int int_Num, [In, Out, MarshalAs(UnmanagedType.I4)]int int_Samp);
[DllImport(@"DLL.dll", EntryPoint = "setNat")]
public static extern System.IntPtr setNat([In, Out, MarshalAs(UnmanagedType.LPStr)]string char_Address_File_nat);
[DllImport(@"DLL.dll", EntryPoint = "getMode")]
public static extern System.IntPtr getMode();
``` | 2015/02/25 | [
"https://Stackoverflow.com/questions/28728891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3405291/"
] | The update to your question provides enough information to explain the behaviour.
1. You call `LoadLibrary` to load your DLL which accounts for one of the references.
2. You call `DllImport` p/invoke functions which in turn lead to a call to `LoadLibrary`. That's the other reference to the library.
3. Then when you call `FreeLibrary`, this succeeds twice since there were two calls to `LoadLibrary`.
But now you are in trouble because you've gone behind the back of the p/invoke system and it still believes that it owns one of the references to the DLL. A reference that you stole from it with your second call to `FreeLibrary`.
I guess that the information you are missing is how the `DllImport` p/invokes bind to the function. You are hoping that they will obtain a module handle by calling `GetModuleHandle`. They don't. They call `LoadLibrary`. They do this the first time they are called and the module they load stays loaded until the assembly itself unloads.
What you have to do, above all else, is follow the rules. The rules state that each call to `LoadLibrary` is to be matched by a call to `FreeLibrary`. You call `LoadLibrary` once. So you must call `FreeLibrary` exactly once also. Stop calling it twice and all is well.
I suspect that you are actually trying to arrange a system whereby you can load and unload DLLs. This prevents you from using p/invoke via `DllImport`. You'll have to do it all with `LoadLibrary` and `GetProcAddress`.
Your usage of `SetDllDirectory` looks somewhat messed up. What do you expect `".\\DLL_Dependencies\\"` to be relative to? Supply a full path. | If you only call LoadLibrary once then you only need to call FreeLibrary once as well. Calling it a second time is moving into undefined behavior.
If you look at the MSDN docs <https://msdn.microsoft.com/en-us/library/windows/desktop/ms683152%28v=vs.85%29.aspx> the function returns a non zero value if it succeeds, or 0 if there is an error.
If you want to be sure that its unloaded then you can call GetModuleHandle on it after the call to FreeLibrary and it should return null.
<https://msdn.microsoft.com/en-us/library/windows/desktop/ms683199(v=vs.85).aspx>
Updated your invoke method class to include:
```
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
```
Then change your button5 click handler to the following:
```
private void button5_Click(object sender, EventArgs e)
{
try
{
int freeCount = 0;
while(Call_DLL.GetModuleHandle("DLL.dll") != System.IntPtr.Zero)
{
Call_DLL.FreeLibrary(SystemIntPtr_handle_of_DLL);
freeCount++;
}
MessageBox.Show("DLL unloaded. You will have to load it again. (Unloaded" + int_FreeLibrary_counter + " times)");
}
catch(Exception Exception_Object)
{
MessageBox.Show(Exception_Object.Message);
}
}
``` |
28,728,891 | Have the following C# code for loading and unloading a C++ DLL.
I load DLL only once, but code has to unload DLL 2 times. Also after unloading DLL, when I load it again, and I call DLL's exported function, I get the following error message:
>
> Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
>
>
>
DLL depends on other DLLs.
```
/// //////////////handle of FDD DLL:
System.IntPtr SystemIntPtr_handle_of_DLL=System.IntPtr.Zero;
private void button4_Click(object sender, EventArgs e)
{
try
{
string string_Dependency_path = ".\\DLL_Dependencies\\";
Call_DLL.SetDllDirectory(string_Dependency_path);
SystemIntPtr_handle_of_DLL = Call_DLL.LoadLibrary("DLL.dll");
if (SystemIntPtr_handle_of_DLL == System.IntPtr.Zero) { throw new Exception("DLL did not load"); }
}
catch (Exception Exception_Object) { MessageBox.Show(Exception_Object.Message); }
}
private void button5_Click(object sender, EventArgs e)
{
try
{
int int_FreeLibrary_counter = 0;
while (Call_DLL.FreeLibrary(SystemIntPtr_handle_of_DLL))
{
int_FreeLibrary_counter++;
}
MessageBox.Show("DLL unloaded. You will have to load it again. (Unloaded" + int_FreeLibrary_counter + " times)");
}
catch (Exception Exception_Object) { MessageBox.Show(Exception_Object.Message); }
}
```
The invoke method:
```
class Call_DLL
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDllDirectory(string string_Dependency_path);
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string string_DLL_name);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FreeLibrary(IntPtr IntPtr_handle_of_DLL);
}
```
EDIT
----
I forgot to include the following which call DLL exported functions, after loading DLL and before unloading DLL. It makes sense to think that something else is going on inside these exported functions which is causing strange behavior (i.e. loading 1 time, having to unload 2 times):
```
[DllImport(@"DLL.dll", EntryPoint = "getFreq")]
public static extern System.IntPtr getFreq([In, Out, MarshalAs(UnmanagedType.LPStr)] string char_Address, [In, Out, MarshalAs(UnmanagedType.I4)]int int_Num, [In, Out, MarshalAs(UnmanagedType.I4)]int int_Samp);
[DllImport(@"DLL.dll", EntryPoint = "setNat")]
public static extern System.IntPtr setNat([In, Out, MarshalAs(UnmanagedType.LPStr)]string char_Address_File_nat);
[DllImport(@"DLL.dll", EntryPoint = "getMode")]
public static extern System.IntPtr getMode();
``` | 2015/02/25 | [
"https://Stackoverflow.com/questions/28728891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3405291/"
] | The update to your question provides enough information to explain the behaviour.
1. You call `LoadLibrary` to load your DLL which accounts for one of the references.
2. You call `DllImport` p/invoke functions which in turn lead to a call to `LoadLibrary`. That's the other reference to the library.
3. Then when you call `FreeLibrary`, this succeeds twice since there were two calls to `LoadLibrary`.
But now you are in trouble because you've gone behind the back of the p/invoke system and it still believes that it owns one of the references to the DLL. A reference that you stole from it with your second call to `FreeLibrary`.
I guess that the information you are missing is how the `DllImport` p/invokes bind to the function. You are hoping that they will obtain a module handle by calling `GetModuleHandle`. They don't. They call `LoadLibrary`. They do this the first time they are called and the module they load stays loaded until the assembly itself unloads.
What you have to do, above all else, is follow the rules. The rules state that each call to `LoadLibrary` is to be matched by a call to `FreeLibrary`. You call `LoadLibrary` once. So you must call `FreeLibrary` exactly once also. Stop calling it twice and all is well.
I suspect that you are actually trying to arrange a system whereby you can load and unload DLLs. This prevents you from using p/invoke via `DllImport`. You'll have to do it all with `LoadLibrary` and `GetProcAddress`.
Your usage of `SetDllDirectory` looks somewhat messed up. What do you expect `".\\DLL_Dependencies\\"` to be relative to? Supply a full path. | I know that this question come to completion, but working on a similar problem I have found a way to load and unload library dynamically using DllImport and without exceptions.
The approach is based on these stakeholders:
**- the DllImport load the library on the first call to a method wrapped.
- if a library is alredy loaded on the stack the call to a method will use this instance of the library instead load another one**
based on these considerations you can manage your module in this way:
1. implement your class which wrap the library
```
public class MyWrapper
{
int _libraryHandle = 0;
[DllImport("mylibrary.dll")]
public external static void MyMethod();
}
```
2. in the constructor load the library using LoadLibrary:
```
public MyWrapper()
{
_libraryHandle = LoadLibrary("mylibrary.dll");
}
```
3. in the dispose method unload the library using FreeLibrary:
```
public Dispose()
{
FreeLibrary(_libraryHandle);
}
```
in this way everytime you'll instance your wrapper a new occurrence of the library will be loaded on the stack without any exception. |
50,145 | I began working at this place in June 2013. Had a steady relationship with the employer for at least a year. So much so that the supervisor, indirect supervisors, and a senior colleague provided B-School recommendations which I'm very thankful for.
Around late fall of last year the supervisor found some performance issues, and gave me a performance feedback. Worked on the feedback and had the next review during February of this year; this time things went way worse, and I was marked "performance below expectations." During the meeting I let the supervisor know that I'm not the right fit for this position, and I would like to start looking for other jobs; he was fine with it.
I started the interviews around that time, however, I didn't land any position yet. I kept regularly taking time-off for interviews which caused excessive absence.
Consequently, this past Friday I was handed the dreadful Performance Improvement Plan (PIP). The document says "Attendance will be monitored over the next 90 days," and the firm wants to see "Improved accuracy and independence over the next 30 days." My supervisor gave me enough time searching for jobs, and I'm not in a position again to keep taking time-off for interviews. Salary is not that high where I work, so I have to look around.
I have some interviews lined up and am positive I will have something under my belt in these two months; contract work is fine too. Have some emergency savings too so no need to worry about bills for a few months.
At this time, I would like to resign when the PIP clock starts ticking this week. This is much better than getting fired and burn the bridges. I need my supervisor and a senior colleague for recommendation, and especially the supervisor for B-School recommendation.
What's your take - resign or wait to get fired? | 2015/07/25 | [
"https://workplace.stackexchange.com/questions/50145",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/38374/"
] | >
> People, what's your take on this? Resign as I know my performance will
> not get better or wait to get fired?
>
>
>
For me, I'd do neither. **I would neither resign nor wait.**
I'd work really hard to get a new job (or land a contract gig) over the next 90 days before getting fired. That way, I wouldn't ever have to answer the question "Why were you fired?" nor would I have to answer the question "Why did you quit without having a new job?". I'd also work as hard as I could to meet the terms of my Performance Improvement Plan, although I don't see many of those ending up well.
I'm not sure why you haven't been able to land a new job since February despite having lots of time off to search. You might wish to reflect on that, try to see what you were doing wrong, and correct it - so as to put you on a better path to success.
I suspect your Supervisor would support you in this approach - few supervisors like to fire employees. He/she may not be in a position to give you more time off, but might still be willing to be a decent reference now or in the future - particularly if you try hard at work.
These things happen - individuals aren't always a good fit for the specific needs of a company. Try hard to land a new job soon, and keep anything negative from your background as much as possible. | Note that a proper PIP should spell out exactly what you have to accomplish, in how much time, to pass it. You may want to wait until you see the details before you panic. A PIP *can* be survived, if the problem was one of misunderstood requirements rather than your not being able to handle the job; it's likely to be painful but I wouldn't give up prematurely -- and as others have noted there are advantages to staying employed while job hunting, not least that you're still being paid until they actually fire you.
(Been there, survived that, long story and I think it was more a matter of management being stupid than anything else.) |
15,351,127 | I want to generate a `<select>` menu of `Vendor` options in my `_navigation.html.erb` partial that will show up on every page.
This is the HTML I would like to produce:
```
<form>
<select>
<option value="">Browse by Store</option>
<option value="Apple">Apple</option>
<option value="Deisel">Deisel</option>
<option value="NIke">Nike </option>
</select>
</form>
```
Then once someone chooses a vendor, it takes them to the equivalent of `vendors_path(@vendor)`. If I were trying to do this in a regular form\_partial, I would simply do something like:
```
<%= simple_form_for(@product) do |f| %>
<%= f.association :vendors %>
<% end %>
```
But...I would then declare some way for that `@product` to be handled in the controller that governs the view that this form is rendered on.
How do I do that in the `/layouts/_navigation.html.erb`?
And...how do I generate the link functionality, that when they choose the `vendor` they want, it automatically redirects them to that `vendor/:id` page? | 2013/03/12 | [
"https://Stackoverflow.com/questions/15351127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91970/"
] | I don't understand why you do you want to use a form to build theses links, and also why use theses links with your application controller. If you want to change links displayed by each product page you can do it this way :
```
<ul class="nav nav-pills">
<li class="dropdown">
<a class="dropdown-toggle"
data-toggle="dropdown"
href="#">
Navigation with Vendors by Product
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<% @product.vendors.each do |vendor| %>
<li><%= link_to vendor.name, vendor %></li>
<%end%>
</ul>
</li>
</ul>
```
Use this partial into your show view product.
Assuming those models :
product.rb
```
has_many :brands
has_many :vendors, :through => :brands
```
vendor.rb
```
has_many :brands
has_many :products, :through => :brands
```
brand.rb
```
belongs_to :product
belongs_to :vendor
```
If you just need a partial menu with all vendors you can also do it this way :
```
<ul class="nav nav-pills">
<li class="dropdown">
<a class="dropdown-toggle"
data-toggle="dropdown"
href="#">
General Navigation Vendors
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<% Vendor.all.each do |vendor| %>
<li><%= link_to vendor.name, vendor %></li>
<%end%>
</ul>
```
If you want to load all Vendors into your application\_controller, maybe you can use before\_filter :load\_vendors
```
def load_vendors
@vendors = Vendor.all
end
``` | Put your controller code in your application\_controller.rb then create a folder in your views folder called application and put your partial files inside that.
<http://railscasts.com/episodes/269-template-inheritance>
I'm not familiar with simple form but railscasts also has a nice how to on using simple form.
<http://railscasts.com/episodes/234-simple-form-revised> |
60,759,318 | I'm using [azure-sdk-js](https://github.com/Azure/azure-sdk-for-js) for reading and sending messages to Azure Service Bus Queues.
I've successfully managed to connect to queues, reading messages, reading DLQ and sending messages. I would like to extend this to show information about how many messages that exist in each queue, how many are being processed and how many DLs there are. I found that [`QueueDetails`](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/interfaces/queuedetails.html) hold this information. But I do not understand how to obtains those `QueueDetails`. `QueueDetails` is implemented by [`QueueResponse`](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/interfaces/queueresponse.html), so basically I am looking for a method that is `GetQueue(queueName)`, but I can't seem to find it.
Has anyone implemented something like this before and knows what method I need to use? | 2020/03/19 | [
"https://Stackoverflow.com/questions/60759318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760402/"
] | So `@azure/service-bus` package essentially provides AMQP based connectivity to Azure Service Bus and has only methods to mainly work with messages. Functionality to manage entities (Queues, Topics, and Subscriptions) has been removed from this package.
You basically have three options:
1. Use `@azure/arm-servicebus` package: Azure Service Bus team has moved the functionality to manage entities from data plane to control plane. So you have to use this package to get details about a queue. The method you would want to call is [`get`](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/servicebus/arm-servicebus/src/operations/queues.ts#L152)
2. Use `azure-sb` package: This is really an old package which is a wrapper over REST API. You can find more details about this package here: <https://github.com/Azure/azure-sdk-for-node/tree/master/lib/services/serviceBus>.
3. Use REST API directly: As mentioned in the other answer, you can use REST API directly to get details about a queue. | You can use REST Api and the GET operation:
<https://learn.microsoft.com/en-us/rest/api/servicebus/queues/get>
The information you're looking for is inside Message Count Details:
<https://learn.microsoft.com/en-us/rest/api/servicebus/queues/get#messagecountdetails> |
60,759,318 | I'm using [azure-sdk-js](https://github.com/Azure/azure-sdk-for-js) for reading and sending messages to Azure Service Bus Queues.
I've successfully managed to connect to queues, reading messages, reading DLQ and sending messages. I would like to extend this to show information about how many messages that exist in each queue, how many are being processed and how many DLs there are. I found that [`QueueDetails`](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/interfaces/queuedetails.html) hold this information. But I do not understand how to obtains those `QueueDetails`. `QueueDetails` is implemented by [`QueueResponse`](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/interfaces/queueresponse.html), so basically I am looking for a method that is `GetQueue(queueName)`, but I can't seem to find it.
Has anyone implemented something like this before and knows what method I need to use? | 2020/03/19 | [
"https://Stackoverflow.com/questions/60759318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760402/"
] | A few interfaces like `QueueDetails` got exposed by accident from the `@azure/service-bus` package in version 1.1.3. The ATOM management client that uses these interfaces is still under works and therefore is not part of the exported public facing API surface. We have a working implementation, but the final design for it is still under discussion and the APIs might change.
Follow <https://github.com/Azure/azure-sdk-for-js/issues/7991> and <https://github.com/Azure/azure-sdk-for-js/issues/7938> for more on this.
For now, please use the `@azure/arm-servicebus` package to fetch details on the queue. If you want these features by using a connection string, then `azure-sb` is the recommended package until `@azure/service-bus` offers similar capabilities in the near future.
**Update as of June 8th, 2020:**
Hello all,
We are happy to share that the third preview to v7 (7.0.0-preview.3) of the `@azure/service-bus` package now supports the CRUD & list operations on queues, topics, subscriptions and rules via a separate "client" that can be instantiated either via a connection string or an AAD credential.
Please checkout the [sample for management operations](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/servicebus/service-bus/samples/javascript/advanced/managementClient.js) for more details.
Please note that this is still in preview and the next preview might have some changes in the API based on internal and external feedback.
Please give it a try and let us know if you have any feedback by logging issues at <https://github.com/Azure/azure-sdk-for-js> | You can use REST Api and the GET operation:
<https://learn.microsoft.com/en-us/rest/api/servicebus/queues/get>
The information you're looking for is inside Message Count Details:
<https://learn.microsoft.com/en-us/rest/api/servicebus/queues/get#messagecountdetails> |
60,759,318 | I'm using [azure-sdk-js](https://github.com/Azure/azure-sdk-for-js) for reading and sending messages to Azure Service Bus Queues.
I've successfully managed to connect to queues, reading messages, reading DLQ and sending messages. I would like to extend this to show information about how many messages that exist in each queue, how many are being processed and how many DLs there are. I found that [`QueueDetails`](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/interfaces/queuedetails.html) hold this information. But I do not understand how to obtains those `QueueDetails`. `QueueDetails` is implemented by [`QueueResponse`](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/interfaces/queueresponse.html), so basically I am looking for a method that is `GetQueue(queueName)`, but I can't seem to find it.
Has anyone implemented something like this before and knows what method I need to use? | 2020/03/19 | [
"https://Stackoverflow.com/questions/60759318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760402/"
] | So `@azure/service-bus` package essentially provides AMQP based connectivity to Azure Service Bus and has only methods to mainly work with messages. Functionality to manage entities (Queues, Topics, and Subscriptions) has been removed from this package.
You basically have three options:
1. Use `@azure/arm-servicebus` package: Azure Service Bus team has moved the functionality to manage entities from data plane to control plane. So you have to use this package to get details about a queue. The method you would want to call is [`get`](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/servicebus/arm-servicebus/src/operations/queues.ts#L152)
2. Use `azure-sb` package: This is really an old package which is a wrapper over REST API. You can find more details about this package here: <https://github.com/Azure/azure-sdk-for-node/tree/master/lib/services/serviceBus>.
3. Use REST API directly: As mentioned in the other answer, you can use REST API directly to get details about a queue. | I check the sdk, there is a [serviceBusAtomManagementClient](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/classes/servicebusatommanagementclient.html), it has the [getQueueDetails](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/classes/servicebusatommanagementclient.html#getqueuedetails) method, in the sdk it use the [GetQueueResponse](https://github.com/Azure/azure-sdk-for-js/blob/b2a067636d2e8fef8104342a8a616c8c0785d2b2/sdk/servicebus/service-bus/src/serviceBusAtomManagementClient.ts#L441) extend the [QueueDetails](https://github.com/Azure/azure-sdk-for-js/blob/b2a067636d2e8fef8104342a8a616c8c0785d2b2/sdk/servicebus/service-bus/src/serviceBusAtomManagementClient.ts#L109) , you could refer to here.
And in the github there is a sample about atomManagement, more details refer to [atomManagementApi](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/servicebus/service-bus/samples/javascript/atomManagementApi.js). |
60,759,318 | I'm using [azure-sdk-js](https://github.com/Azure/azure-sdk-for-js) for reading and sending messages to Azure Service Bus Queues.
I've successfully managed to connect to queues, reading messages, reading DLQ and sending messages. I would like to extend this to show information about how many messages that exist in each queue, how many are being processed and how many DLs there are. I found that [`QueueDetails`](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/interfaces/queuedetails.html) hold this information. But I do not understand how to obtains those `QueueDetails`. `QueueDetails` is implemented by [`QueueResponse`](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/interfaces/queueresponse.html), so basically I am looking for a method that is `GetQueue(queueName)`, but I can't seem to find it.
Has anyone implemented something like this before and knows what method I need to use? | 2020/03/19 | [
"https://Stackoverflow.com/questions/60759318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760402/"
] | A few interfaces like `QueueDetails` got exposed by accident from the `@azure/service-bus` package in version 1.1.3. The ATOM management client that uses these interfaces is still under works and therefore is not part of the exported public facing API surface. We have a working implementation, but the final design for it is still under discussion and the APIs might change.
Follow <https://github.com/Azure/azure-sdk-for-js/issues/7991> and <https://github.com/Azure/azure-sdk-for-js/issues/7938> for more on this.
For now, please use the `@azure/arm-servicebus` package to fetch details on the queue. If you want these features by using a connection string, then `azure-sb` is the recommended package until `@azure/service-bus` offers similar capabilities in the near future.
**Update as of June 8th, 2020:**
Hello all,
We are happy to share that the third preview to v7 (7.0.0-preview.3) of the `@azure/service-bus` package now supports the CRUD & list operations on queues, topics, subscriptions and rules via a separate "client" that can be instantiated either via a connection string or an AAD credential.
Please checkout the [sample for management operations](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/servicebus/service-bus/samples/javascript/advanced/managementClient.js) for more details.
Please note that this is still in preview and the next preview might have some changes in the API based on internal and external feedback.
Please give it a try and let us know if you have any feedback by logging issues at <https://github.com/Azure/azure-sdk-for-js> | I check the sdk, there is a [serviceBusAtomManagementClient](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/classes/servicebusatommanagementclient.html), it has the [getQueueDetails](https://azuresdkdocs.blob.core.windows.net/$web/javascript/azure-service-bus/1.1.3/classes/servicebusatommanagementclient.html#getqueuedetails) method, in the sdk it use the [GetQueueResponse](https://github.com/Azure/azure-sdk-for-js/blob/b2a067636d2e8fef8104342a8a616c8c0785d2b2/sdk/servicebus/service-bus/src/serviceBusAtomManagementClient.ts#L441) extend the [QueueDetails](https://github.com/Azure/azure-sdk-for-js/blob/b2a067636d2e8fef8104342a8a616c8c0785d2b2/sdk/servicebus/service-bus/src/serviceBusAtomManagementClient.ts#L109) , you could refer to here.
And in the github there is a sample about atomManagement, more details refer to [atomManagementApi](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/servicebus/service-bus/samples/javascript/atomManagementApi.js). |
105,997 | I want put right headed double arrow between first two columns of the table

My code:
```
\documentclass[12pt,a4paper]{article}
\usepackage{algorithmic,algorithm,amsmath} %for mathematics %
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{booktabs}
\usepackage{array}
\usepackage{paralist}
\usepackage{bigstrut}
\usepackage{multirow}
\usepackage{dcolumn}
\begin{document}
\newcolumntype{d}[1]{D{.}{.}{#1}}
{\setlength{\extrarowheight}{1.5pt}
\setlength{\tabcolsep}{1pt}
\begin{table}[htbp]
\centering
\caption{The Results of Granger and MWALD tests}
\begin{tabular}{llccccc}
\toprule
\multirow{2}[4]{*}{Null Hypothesis} & \multicolumn{2}{c}{Grangers’ test (Short run)} & & \multicolumn{2}{c}{MWALD test (Long run)} \\
\cmidrule(r){3-4} \cmidrule(r){6-7}
\multicolumn{1}{l}{} & \multicolumn{1}{l}{} &\multicolumn{1}{c}{F-Statistics} &\multicolumn{1}{c}{p-values} & &\multicolumn{1}{c}{$\chi^{2}$-Statistics} & \multicolumn{1}{c}{p-values} \\
\midrule
\multicolumn{1}{l}{LTC} & \multicolumn{1}{l}{LGDP} & 7.736** & 0.021 & & 0.169 & 0.919 \\
\multicolumn{1}{l}{LGDP} & \multicolumn{1}{l}{LTC} & 0.504 & 0.777 & & 1.763 & 0.414 \\
\multicolumn{1}{l}{LCO2} & \multicolumn{1}{l}{LGDP} & 10.829* & 0.005 & & .324 & & 6.490 & 0.039 \\
\multicolumn{1}{l}{LCO2} & \multicolumn{1}{l}{LCC} & 10.673* & 0.014 & & 7.378** & 0.025 \\
\bottomrule
\end{tabular}%
\label{tab:addlabel}%
\end{table}%
\end{document}
``` | 2013/03/30 | [
"https://tex.stackexchange.com/questions/105997",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/28186/"
] | You can use `@{<symbol>}` as in `\begin{tabular}{l@{$\Longrightarrow\,\,\,$}ld{5}d{3}d{5}d{3}}`. This won't work if you use `\multicolumn{1}{l}{LCO2}` as in the last line. I have used `dcolumn` and aligned numbers around `.` .
```
\documentclass[12pt,a4paper]{article}
\usepackage{mathtools}
\usepackage{booktabs}
\usepackage{array,dcolumn}
\begin{document}
\newcolumntype{d}[1]{D{.}{\cdot}{#1}}
%\newcolumntype{d}[1]{D{.}{.}{#1}}
{\setlength{\extrarowheight}{1.5pt}
%\setlength{\tabcolsep}{.3em}
\begin{table}[htbp]
\centering
\caption{The Results of Granger and MWALD tests}
\begin{tabular}{l@{$\Longrightarrow\,\,\,$}ld{5}d{3}d{5}d{3}}
\toprule
\multicolumn{1}{l}{Null} & \multicolumn{1}{l}{} & \multicolumn{2}{c}{Grangers’ test (Short run)} & \multicolumn{2}{c}{MWALD test (Long run)} \\
\cmidrule(r){3-4} \cmidrule(r){5-6}
\multicolumn{1}{l}{Hypothesis} & \multicolumn{1}{l}{} &\multicolumn{1}{c}{F-Statistics} &\multicolumn{1}{c}{p-values} & \multicolumn{1}{c}{$\chi^{2}$-Statistics} & \multicolumn{1}{c}{p-values} \\
\midrule
LTC & LGDP & 7.736** & 0.021 & 0.169 & 0.919 \\
LGDP & LTC & 0.504 & 0.777 & 1.763 & 0.414 \\
LCO2 & LGDP & 10.829* & 0.005 & 10.321* & 0.006 \\
LGDP & LCO2 & 1.793 & 0.408 & 3.694 & 0.158 \\
LTC & LCO2 & 8.652* & 0.013 & 5.775*** & 0.056 \\
LCO2 & LTC & 6.405** & 0.041 & 4.704*** & 0.095 \\
LIC & LGDP & 5.235*** & 0.073 & 0.681 & 0.711 \\
LGDP & LIC & 1.555 & 0.460 & 3.732 & 0.155 \\
LCO2 & LGDP & 16.186* & 0.000 & 8.900* & 0.012 \\
LGDP & LCO2 & 1.818 & 0.403 & 2.086 & 0.352 \\
\multicolumn{1}{l}{LCO2} & LCC & 10.673* & 0.014 & 7.378** & 0.025 \\
\bottomrule
\end{tabular}%
\label{tab:addlabel}%
\end{table}%
\end{document}
```
 | You can always add a new column in between and populate it with the symbol you want.
How to look up a symbol?
[How to look up a symbol?](https://tex.stackexchange.com/q/14)
Importing a Single Symbol From a Different Font
[Importing a Single Symbol From a Different Font](https://tex.stackexchange.com/q/14386)
How do I find out what fonts are used in a document/picture?
[How do I find out what fonts are used in a document/picture?](https://tex.stackexchange.com/q/45919) |
8,574,347 | I need to get user download some file (for example, PDF). What will be longer:
* send this file by PHP (with specific headers),
* or put it in http public folder, and get user the public link to download it (without PHP help)?
In 1st case the original file could be in private zone.
But I'm thinking it will take some time to send this file by PHP.
So how I can measure PHP spent time to sending file and how much memory it can consumed?
P.S. in the 1st case, when PHP sends headers and browser (if pdf plugin is installed) will try to opening it inside browser, is PHP still working, or it push out whole file after headers sent immediately? Or if plugin not installed and browser will show "save as" dialog PHP still working ? | 2011/12/20 | [
"https://Stackoverflow.com/questions/8574347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016265/"
] | To add to the answers above, the App Domain is required for security reasons. For example, your app has been sending the browser to `"www.example.com/PAGE_NAME_HERE"`, but suddenly a third party application (or something else) sends the user to `"www.supposedlymaliciouswebsite.com/PAGE_HERE"`, then a 191 error is thrown saying that this wasn't part of the app domains you listed in your Facebook application settings. | it stands for your website where your app is running on.
like you have made an app www.xyz.pqr
then you will type this www.xyz.pqr in App domain
the site where your app is running on should be secure and valid |
8,574,347 | I need to get user download some file (for example, PDF). What will be longer:
* send this file by PHP (with specific headers),
* or put it in http public folder, and get user the public link to download it (without PHP help)?
In 1st case the original file could be in private zone.
But I'm thinking it will take some time to send this file by PHP.
So how I can measure PHP spent time to sending file and how much memory it can consumed?
P.S. in the 1st case, when PHP sends headers and browser (if pdf plugin is installed) will try to opening it inside browser, is PHP still working, or it push out whole file after headers sent immediately? Or if plugin not installed and browser will show "save as" dialog PHP still working ? | 2011/12/20 | [
"https://Stackoverflow.com/questions/8574347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016265/"
] | the app domain is your domain name.
Before you enter your domain, first click on Add Platform, select website, enter your site URL and mobile site url. Save the settings.
Thereafter, you can enter the domain name in the App domains field.
See more at my blog: <http://www.ogbongeblog.com/2014/03/unable-to-add-app-domains-to-new.html> | To add to the answers above, the App Domain is required for security reasons. For example, your app has been sending the browser to `"www.example.com/PAGE_NAME_HERE"`, but suddenly a third party application (or something else) sends the user to `"www.supposedlymaliciouswebsite.com/PAGE_HERE"`, then a 191 error is thrown saying that this wasn't part of the app domains you listed in your Facebook application settings. |
8,574,347 | I need to get user download some file (for example, PDF). What will be longer:
* send this file by PHP (with specific headers),
* or put it in http public folder, and get user the public link to download it (without PHP help)?
In 1st case the original file could be in private zone.
But I'm thinking it will take some time to send this file by PHP.
So how I can measure PHP spent time to sending file and how much memory it can consumed?
P.S. in the 1st case, when PHP sends headers and browser (if pdf plugin is installed) will try to opening it inside browser, is PHP still working, or it push out whole file after headers sent immediately? Or if plugin not installed and browser will show "save as" dialog PHP still working ? | 2011/12/20 | [
"https://Stackoverflow.com/questions/8574347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016265/"
] | it stands for your website where your app is running on.
like you have made an app www.xyz.pqr
then you will type this www.xyz.pqr in App domain
the site where your app is running on should be secure and valid | I think it is the domain that you run your app.
For example, your canvas URL is facebook.yourdomain.com, you should give App domain as .yourdomain.com |
8,574,347 | I need to get user download some file (for example, PDF). What will be longer:
* send this file by PHP (with specific headers),
* or put it in http public folder, and get user the public link to download it (without PHP help)?
In 1st case the original file could be in private zone.
But I'm thinking it will take some time to send this file by PHP.
So how I can measure PHP spent time to sending file and how much memory it can consumed?
P.S. in the 1st case, when PHP sends headers and browser (if pdf plugin is installed) will try to opening it inside browser, is PHP still working, or it push out whole file after headers sent immediately? Or if plugin not installed and browser will show "save as" dialog PHP still working ? | 2011/12/20 | [
"https://Stackoverflow.com/questions/8574347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016265/"
] | the app domain is your domain name.
Before you enter your domain, first click on Add Platform, select website, enter your site URL and mobile site url. Save the settings.
Thereafter, you can enter the domain name in the App domains field.
See more at my blog: <http://www.ogbongeblog.com/2014/03/unable-to-add-app-domains-to-new.html> | I think it is the domain that you run your app.
For example, your canvas URL is facebook.yourdomain.com, you should give App domain as .yourdomain.com |
8,574,347 | I need to get user download some file (for example, PDF). What will be longer:
* send this file by PHP (with specific headers),
* or put it in http public folder, and get user the public link to download it (without PHP help)?
In 1st case the original file could be in private zone.
But I'm thinking it will take some time to send this file by PHP.
So how I can measure PHP spent time to sending file and how much memory it can consumed?
P.S. in the 1st case, when PHP sends headers and browser (if pdf plugin is installed) will try to opening it inside browser, is PHP still working, or it push out whole file after headers sent immediately? Or if plugin not installed and browser will show "save as" dialog PHP still working ? | 2011/12/20 | [
"https://Stackoverflow.com/questions/8574347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016265/"
] | To add to the answers above, the App Domain is required for security reasons. For example, your app has been sending the browser to `"www.example.com/PAGE_NAME_HERE"`, but suddenly a third party application (or something else) sends the user to `"www.supposedlymaliciouswebsite.com/PAGE_HERE"`, then a 191 error is thrown saying that this wasn't part of the app domains you listed in your Facebook application settings. | It's simply the domain that your "facebook" application (wich means application visible on facebook but hosted on the website www.xyz.com) will be hosted. So you can put App Domain = www.xyz.com |
8,574,347 | I need to get user download some file (for example, PDF). What will be longer:
* send this file by PHP (with specific headers),
* or put it in http public folder, and get user the public link to download it (without PHP help)?
In 1st case the original file could be in private zone.
But I'm thinking it will take some time to send this file by PHP.
So how I can measure PHP spent time to sending file and how much memory it can consumed?
P.S. in the 1st case, when PHP sends headers and browser (if pdf plugin is installed) will try to opening it inside browser, is PHP still working, or it push out whole file after headers sent immediately? Or if plugin not installed and browser will show "save as" dialog PHP still working ? | 2011/12/20 | [
"https://Stackoverflow.com/questions/8574347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016265/"
] | If you don't specify the ***platform*** for the app you won't able to add app domain correctly.
Here is an example -- validate that its a type a website platform.
[](https://i.stack.imgur.com/Tapwm.png) | In this example:
http://**www.example.com:80**/somepage?parameter1="hello"¶meter2="world"
the bold part is the Domainname. 80 is rarely included. I post it since many people may wonder if 3000 or some other port is part of the domain if their not staging their app for production yet. Normally you don't specify it since 80 is the default, but if you just want to specify `localhost` just do it without the port number, it works just as fine. The adress, though, should be `http://localhost:3000` (if you have it on that port). |
8,574,347 | I need to get user download some file (for example, PDF). What will be longer:
* send this file by PHP (with specific headers),
* or put it in http public folder, and get user the public link to download it (without PHP help)?
In 1st case the original file could be in private zone.
But I'm thinking it will take some time to send this file by PHP.
So how I can measure PHP spent time to sending file and how much memory it can consumed?
P.S. in the 1st case, when PHP sends headers and browser (if pdf plugin is installed) will try to opening it inside browser, is PHP still working, or it push out whole file after headers sent immediately? Or if plugin not installed and browser will show "save as" dialog PHP still working ? | 2011/12/20 | [
"https://Stackoverflow.com/questions/8574347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016265/"
] | It's simply the domain that your "facebook" application (wich means application visible on facebook but hosted on the website www.xyz.com) will be hosted. So you can put App Domain = www.xyz.com | I think it is the domain that you run your app.
For example, your canvas URL is facebook.yourdomain.com, you should give App domain as .yourdomain.com |
8,574,347 | I need to get user download some file (for example, PDF). What will be longer:
* send this file by PHP (with specific headers),
* or put it in http public folder, and get user the public link to download it (without PHP help)?
In 1st case the original file could be in private zone.
But I'm thinking it will take some time to send this file by PHP.
So how I can measure PHP spent time to sending file and how much memory it can consumed?
P.S. in the 1st case, when PHP sends headers and browser (if pdf plugin is installed) will try to opening it inside browser, is PHP still working, or it push out whole file after headers sent immediately? Or if plugin not installed and browser will show "save as" dialog PHP still working ? | 2011/12/20 | [
"https://Stackoverflow.com/questions/8574347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016265/"
] | the app domain is your domain name.
Before you enter your domain, first click on Add Platform, select website, enter your site URL and mobile site url. Save the settings.
Thereafter, you can enter the domain name in the App domains field.
See more at my blog: <http://www.ogbongeblog.com/2014/03/unable-to-add-app-domains-to-new.html> | it stands for your website where your app is running on.
like you have made an app www.xyz.pqr
then you will type this www.xyz.pqr in App domain
the site where your app is running on should be secure and valid |
8,574,347 | I need to get user download some file (for example, PDF). What will be longer:
* send this file by PHP (with specific headers),
* or put it in http public folder, and get user the public link to download it (without PHP help)?
In 1st case the original file could be in private zone.
But I'm thinking it will take some time to send this file by PHP.
So how I can measure PHP spent time to sending file and how much memory it can consumed?
P.S. in the 1st case, when PHP sends headers and browser (if pdf plugin is installed) will try to opening it inside browser, is PHP still working, or it push out whole file after headers sent immediately? Or if plugin not installed and browser will show "save as" dialog PHP still working ? | 2011/12/20 | [
"https://Stackoverflow.com/questions/8574347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016265/"
] | If you don't specify the ***platform*** for the app you won't able to add app domain correctly.
Here is an example -- validate that its a type a website platform.
[](https://i.stack.imgur.com/Tapwm.png) | I think it is the domain that you run your app.
For example, your canvas URL is facebook.yourdomain.com, you should give App domain as .yourdomain.com |
8,574,347 | I need to get user download some file (for example, PDF). What will be longer:
* send this file by PHP (with specific headers),
* or put it in http public folder, and get user the public link to download it (without PHP help)?
In 1st case the original file could be in private zone.
But I'm thinking it will take some time to send this file by PHP.
So how I can measure PHP spent time to sending file and how much memory it can consumed?
P.S. in the 1st case, when PHP sends headers and browser (if pdf plugin is installed) will try to opening it inside browser, is PHP still working, or it push out whole file after headers sent immediately? Or if plugin not installed and browser will show "save as" dialog PHP still working ? | 2011/12/20 | [
"https://Stackoverflow.com/questions/8574347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016265/"
] | the app domain is your domain name.
Before you enter your domain, first click on Add Platform, select website, enter your site URL and mobile site url. Save the settings.
Thereafter, you can enter the domain name in the App domains field.
See more at my blog: <http://www.ogbongeblog.com/2014/03/unable-to-add-app-domains-to-new.html> | If you don't specify the ***platform*** for the app you won't able to add app domain correctly.
Here is an example -- validate that its a type a website platform.
[](https://i.stack.imgur.com/Tapwm.png) |
42,405,653 | My python script is like this:
```
def main():
ret = [1, 2]
return ret
```
and I call the python script from ruby like this:
```
output = system("python script.py")
print output
```
However the value of output is true. I want to get [1, 2]. My question is how I can get the return value of the python script? | 2017/02/23 | [
"https://Stackoverflow.com/questions/42405653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319283/"
] | First, have your Python script print the value rather than returning it, or add `print main()` at the bottom so the return value of `main()` gets printed.
Second, on the Ruby side, execute it with backticks rather than the `system()` function, like this:
```
output = `python script.py`
```
This captures the output of the Python script as a string. If you want it as a Ruby array, you'll need to parse it. Ruby's array literal syntax is similar to Python's list literal syntax, so this is not as tough as it might seem. If you can find something that parses strings into Ruby arrays (besides `eval()` because it's dangerous) you should be covered. Problems will arise when you have things besides simple types, `None`, or potentially strings with escapes in them.
I am more a Python guy than a Ruby guy, but Ruby doesn't seem to have anything like Python's `ast.literal_eval` (a safe `eval()` that only accepts literals) in its standard library. However, I did find [parsr](https://rubygems.org/gems/parsr/versions/0.0.4) which appears to be exactly that.
If the Python list literals you're getting aren't valid Ruby, you can use JSON as the interchange format:
```
# Python side
import json, sys
json.dump(main(), sys.stdout)
# Ruby side
require 'json'
output = JSON.parse(`python script.py`)
``` | If you have the Python script `print` its result, then then it will be captured in `result`. This is the "standard out" i.e. StdOut, it's what ruby's `system` reads.
You also need to have the python script actually call the method when it's run from the command line.
*edit*
My mistake, use backticks instead of `system`. And rather than using regex or string manipulation to pass data between python and ruby, use a standard serialization format like json or yaml. |
42,405,653 | My python script is like this:
```
def main():
ret = [1, 2]
return ret
```
and I call the python script from ruby like this:
```
output = system("python script.py")
print output
```
However the value of output is true. I want to get [1, 2]. My question is how I can get the return value of the python script? | 2017/02/23 | [
"https://Stackoverflow.com/questions/42405653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319283/"
] | This is python test.py
```
import sys
def main():
ret = [1, 2]
print >> sys.stdout, ret
main()
```
This is ruby code test.rb
```
require 'open3'
require 'json'
stdin, stdout, stderr = Open3.popen3("python test.py")
stdout.each do |ele|
p ele #=> "[1, 2]\n"
p JSON.parse(ele) #=> [1, 2]
end
```
Then execute ruby script in shell
```
ruby test.rb
```
You need by the `stdout` to get the python return value in ruby script, and by the some ugly tips, I didn't find the other better way in this time, but the code can work and accept the python return value at least now, maybe you can try it and search the better solution continuously. | If you have the Python script `print` its result, then then it will be captured in `result`. This is the "standard out" i.e. StdOut, it's what ruby's `system` reads.
You also need to have the python script actually call the method when it's run from the command line.
*edit*
My mistake, use backticks instead of `system`. And rather than using regex or string manipulation to pass data between python and ruby, use a standard serialization format like json or yaml. |
42,405,653 | My python script is like this:
```
def main():
ret = [1, 2]
return ret
```
and I call the python script from ruby like this:
```
output = system("python script.py")
print output
```
However the value of output is true. I want to get [1, 2]. My question is how I can get the return value of the python script? | 2017/02/23 | [
"https://Stackoverflow.com/questions/42405653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319283/"
] | First, have your Python script print the value rather than returning it, or add `print main()` at the bottom so the return value of `main()` gets printed.
Second, on the Ruby side, execute it with backticks rather than the `system()` function, like this:
```
output = `python script.py`
```
This captures the output of the Python script as a string. If you want it as a Ruby array, you'll need to parse it. Ruby's array literal syntax is similar to Python's list literal syntax, so this is not as tough as it might seem. If you can find something that parses strings into Ruby arrays (besides `eval()` because it's dangerous) you should be covered. Problems will arise when you have things besides simple types, `None`, or potentially strings with escapes in them.
I am more a Python guy than a Ruby guy, but Ruby doesn't seem to have anything like Python's `ast.literal_eval` (a safe `eval()` that only accepts literals) in its standard library. However, I did find [parsr](https://rubygems.org/gems/parsr/versions/0.0.4) which appears to be exactly that.
If the Python list literals you're getting aren't valid Ruby, you can use JSON as the interchange format:
```
# Python side
import json, sys
json.dump(main(), sys.stdout)
# Ruby side
require 'json'
output = JSON.parse(`python script.py`)
``` | This is python test.py
```
import sys
def main():
ret = [1, 2]
print >> sys.stdout, ret
main()
```
This is ruby code test.rb
```
require 'open3'
require 'json'
stdin, stdout, stderr = Open3.popen3("python test.py")
stdout.each do |ele|
p ele #=> "[1, 2]\n"
p JSON.parse(ele) #=> [1, 2]
end
```
Then execute ruby script in shell
```
ruby test.rb
```
You need by the `stdout` to get the python return value in ruby script, and by the some ugly tips, I didn't find the other better way in this time, but the code can work and accept the python return value at least now, maybe you can try it and search the better solution continuously. |
69,887,072 | I am working on a node project where I have imported pg library for database operations. I have a Kafka queue from where I fetch events and store them in the database. I am fetching orders from kafka and every time an order is updated a new event is generated, I need to delete the old order details and replace them with new ones.
Below is the code
```
async function saveOrders(orders: Array<TransactionOnOrders>) {
const client = await pool.connect()
try {
await client.query('BEGIN')
if (orders.length) {
const deleted = await deleteOrders(client, orders[0].orderId)
logger.debug(`deleted rowCount ${deleted.rowCount} ${orders[0].orderId}`)
}
const queries = orders.map(ord => saveTransactionOnOrders(client, ord))
await Promise.all(queries)
await client.query('COMMIT')
} catch (e) {
await client.query('ROLLBACK')
throw e
} finally {
client.release()
}
}
```
The orders are getting updated very frequently and we are receiving lots of events creating a race condition leading to records not being deleted and insertion of extra records.
For eg: let's say we received an event for order123 and the transaction is in process, till the time it completes another event for order123 is received so the deletion query returns 0 rows affected and the insertion query inserts another row leading to 2 rows while there should be only one record present.
I have tried to change the isolation level that didn't work well and resulted in an error
```
await client.query('BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ')
await client.query('BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE')
```
Is there any mistake I am doing here or is there a better to handle the above situation? | 2021/11/08 | [
"https://Stackoverflow.com/questions/69887072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5759359/"
] | ```
alias(summarize(sumSeries(exclude(stats.checkout-*.*.*.*.*),"checkout-es"), '$time', 'sum', false), 'checkout')
```
This should be work.
<https://graphite.readthedocs.io/en/latest/functions.html#graphite.render.functions.exclude> | If you don't need alerts you could use transformations
Filter data by name
Filter data by query
Filter data by value
<https://grafana.com/docs/grafana/latest/panels/transformations/> |
13,763,522 | I've developed a service that allows users to search for stores on www.mysite.com.
I also have partners that uses my service. To the user, it looks like they are on my partners web site, when in fact they are on my site. I have only replaced my own header and footer, with my partners header and footer.
For the user, it looks like they are on `mysite.partner.com` when in reality they are on `partner.mysite.com`.
If you understood what I tried to explain, my question is:
Will Google and other search engines consider this duplicate content?
**Update - canonical page**
If I understand canonical pages correctly, `www.mysite.com` is my canonical page.
So when my partner uses `mysite.partner.com?store=wallmart&id=123` which "redirects" (CNAME) to `partner.mysite.com?store=wallmart&id=123`, my server recognize my sub-domain.
So what I need to do, is to dynamically add the following in my `<HEAD>` section:
```
<link rel="canonical" href="mysite.com?store=wallmart&id=123">
```
Is this correct? | 2012/12/07 | [
"https://Stackoverflow.com/questions/13763522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91612/"
] | Definitely. You'll want to use canonical tagging to stop this happening.
<http://support.google.com/webmasters/bin/answer.py?hl=en&answer=139394> | Yes. It will be considered as duplicate content by Google. Cause you have replaced only footer and header. By recent Google algorithm, content should be unique for website or even blog. If content is not unique, your website will be penalized by Google. |
13,763,522 | I've developed a service that allows users to search for stores on www.mysite.com.
I also have partners that uses my service. To the user, it looks like they are on my partners web site, when in fact they are on my site. I have only replaced my own header and footer, with my partners header and footer.
For the user, it looks like they are on `mysite.partner.com` when in reality they are on `partner.mysite.com`.
If you understood what I tried to explain, my question is:
Will Google and other search engines consider this duplicate content?
**Update - canonical page**
If I understand canonical pages correctly, `www.mysite.com` is my canonical page.
So when my partner uses `mysite.partner.com?store=wallmart&id=123` which "redirects" (CNAME) to `partner.mysite.com?store=wallmart&id=123`, my server recognize my sub-domain.
So what I need to do, is to dynamically add the following in my `<HEAD>` section:
```
<link rel="canonical" href="mysite.com?store=wallmart&id=123">
```
Is this correct? | 2012/12/07 | [
"https://Stackoverflow.com/questions/13763522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91612/"
] | It's duplicate content but there is no penalty as such.
The problem is, for a specific search Google will pick one version of a page and filter out the others from the results. If your partner is targeting the same region then you are in direct competition.
The canonical tag is a way to tell Google which is the official version. If you use it then only the canonical page will show up in search results. So if you canonicalise back to your domain then your partners will be excluded from search results. Only your domains pages will ever show up. Not good for your partners.
There is no win. The only way your partners will do well is if they have their own content or target a different region and you don't do the canonical tag.
So your partners have a chance, I would not add the canonical. Then it's down to the Google gods to decide which of your duplicate pages gets shown. | Yes. It will be considered as duplicate content by Google. Cause you have replaced only footer and header. By recent Google algorithm, content should be unique for website or even blog. If content is not unique, your website will be penalized by Google. |
13,763,522 | I've developed a service that allows users to search for stores on www.mysite.com.
I also have partners that uses my service. To the user, it looks like they are on my partners web site, when in fact they are on my site. I have only replaced my own header and footer, with my partners header and footer.
For the user, it looks like they are on `mysite.partner.com` when in reality they are on `partner.mysite.com`.
If you understood what I tried to explain, my question is:
Will Google and other search engines consider this duplicate content?
**Update - canonical page**
If I understand canonical pages correctly, `www.mysite.com` is my canonical page.
So when my partner uses `mysite.partner.com?store=wallmart&id=123` which "redirects" (CNAME) to `partner.mysite.com?store=wallmart&id=123`, my server recognize my sub-domain.
So what I need to do, is to dynamically add the following in my `<HEAD>` section:
```
<link rel="canonical" href="mysite.com?store=wallmart&id=123">
```
Is this correct? | 2012/12/07 | [
"https://Stackoverflow.com/questions/13763522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91612/"
] | It's duplicate content but there is no penalty as such.
The problem is, for a specific search Google will pick one version of a page and filter out the others from the results. If your partner is targeting the same region then you are in direct competition.
The canonical tag is a way to tell Google which is the official version. If you use it then only the canonical page will show up in search results. So if you canonicalise back to your domain then your partners will be excluded from search results. Only your domains pages will ever show up. Not good for your partners.
There is no win. The only way your partners will do well is if they have their own content or target a different region and you don't do the canonical tag.
So your partners have a chance, I would not add the canonical. Then it's down to the Google gods to decide which of your duplicate pages gets shown. | Definitely. You'll want to use canonical tagging to stop this happening.
<http://support.google.com/webmasters/bin/answer.py?hl=en&answer=139394> |
6,894,117 | I'm writing a program where I'm having to test if one set of unique integers `A` belongs to another set of unique numbers `B`. However, this operation might be done several hundred times per second, so I'm looking for an efficient algorithm to do it.
For example, if `A = [1 2 3]` and `B = [1 2 3 4]`, it is true, but if `B = [1 2 4 5 6]`, it's false.
I'm not sure how efficient it is to just sort and compare, so I'm wondering if there are any more efficient algorithms.
One idea I came up with, was to give each number `n` their corresponding `n`'th prime: that is 1 = 2, 2 = 3, 3 = 5, 4 = 7 etc. Then I could calculate the product of `A`, and if that product is a factor of the similar product of `B`, we could say that `A` is a subset of similar `B` with certainty. For example, if `A = [1 2 3]`, `B = [1 2 3 4]` the primes are [2 3 5] and [2 3 5 7] and the products 2\*3\*5=30 and 2\*3\*5\*7=210. Since 210%30=0, `A` is a subset of `B`. I'm expecting the largest integer to be couple of million at most, so I think it's doable.
Are there any more efficient algorithms? | 2011/08/01 | [
"https://Stackoverflow.com/questions/6894117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/377160/"
] | The asymptotically fastest approach would be to just put each set in a hash table and query each element, which is `O(N)` time. You cannot do better (since it will take that much time to read the data).
Most set datastructures already support expected and/or amortized O(1) query time. Some languages even support this operation. For example in python, you could just do
```
A < B
```
Of course the picture changes drastically depending on what you mean by "this operation is repeated". If you have the ability to do precalculations on the data as you add it to the set (which presumably you have the ability to do so), this will allow you to subsume the minimal `O(N)` time into other operations such as constructing the set. But we can't advise without knowing much more.
Assuming you had full control of the set datastructure, your approach to keep a running product (whenever you add an element, you do a single `O(1)` multiplication) is a very good idea IF there exists a divisibility test that is faster than `O(N)`... in fact your solution is really smart, because we can just do a single ALU division and hope we're within float tolerance. Do note however this will only allow you roughly a speedup factor of `20x` max I think, since `21! > 2^64`. There might be tricks to play with congruence-modulo-an-integer, but I can't think of any. I have a slight hunch though that there is no divisibility test that is faster than `O(#primes)`, though I'd like to be proved wrong!
If you are doing this repeatedly on duplicates, you may benefit from caching depending on what exactly you are doing; give each set a unique ID (though since this makes updates hard, you may ironically wish to do something exactly like your scheme to make fingerprints, but mod max\_int\_size with detection-collision). To manage memory, you can pin extremely expensive set comparison (e.g. checking if a giant set is part of itself) into the cache, while otherwise using a most-recent policy if you run into memory issues. This nice thing about this is it synergizes with an element-by-element rejection test. That is, you will be throwing out sets quickly if they don't have many overlapping elements, but if they have many overlapping elements the calculations will take a long time, and if you repeat these calculations, caching could come in handy. | Let A and B be two sets, and you want to check if A is a subset of B. The first idea that pops into my mind is to sort both sets and then simply check if every element of A is contained in B, as following:
Let n\_A and n\_B be the cardinality of A and B, respectively. Let i\_A = 1, i\_B = 1. Then the following algorithm (that is O(n\_A + n\_B)) will solve the problem:
```
// A and B assumed to be sorted
i_A = 1;
i_B = 1;
n_A = size(A);
n_B = size(B);
while (i_A <= n_A) {
while (A[i_A] > B[i_B]) {
i_B++;
if (i_B > n_B) return false;
}
if (A[i_A] != B[i_B}) return false;
i_A++;
}
return true;
```
The same thing, but in a more functional, recursive way (some will find the previous easier to understand, others might find this one easier to understand):
```
// A and B assumed to be sorted
function subset(A, B)
n_A = size(A)
n_B = size(B)
function subset0(i_A, i_B)
if (i_A > n_A) true
else if (i_B > n_B) false
else
if (A[i_A] <= B[i_B]) return (A[i_A] == B[i_B]) && subset0(i_A + 1, i_B + 1);
else return subset0(i_A, i_B + 1);
subset0(1, 1)
```
In this last example, notice that subset0 is tail recursive, since if `(A[i_A] == B[i_B])` is false then there will be no recursive call, otherwise, if `(A[i_A] == B[i_B])` is true, than there's no need to keep this information, since the result of `true && subset0(...)` is exactly the same as `subset0(...)`. So, any smart compiler will be able to transform this into a loop, avoiding stack overflows or any performance hits caused by function calls.
This will certainly work, but we might be able to optimize it a lot in the average case if you have and provide more information about your sets, such as the probability distribution of the values in the sets, if you somehow expect the answer to be biased (ie, it will more often be true, or more often be false), etc.
Also, have you already written any code to actually measure its performance? Or are you trying to pre-optimize?
You should start by writing the simplest and most straightforward solution that works, and measure its performance. If it's not already satisfactory, only then you should start trying to optimize it. |
6,894,117 | I'm writing a program where I'm having to test if one set of unique integers `A` belongs to another set of unique numbers `B`. However, this operation might be done several hundred times per second, so I'm looking for an efficient algorithm to do it.
For example, if `A = [1 2 3]` and `B = [1 2 3 4]`, it is true, but if `B = [1 2 4 5 6]`, it's false.
I'm not sure how efficient it is to just sort and compare, so I'm wondering if there are any more efficient algorithms.
One idea I came up with, was to give each number `n` their corresponding `n`'th prime: that is 1 = 2, 2 = 3, 3 = 5, 4 = 7 etc. Then I could calculate the product of `A`, and if that product is a factor of the similar product of `B`, we could say that `A` is a subset of similar `B` with certainty. For example, if `A = [1 2 3]`, `B = [1 2 3 4]` the primes are [2 3 5] and [2 3 5 7] and the products 2\*3\*5=30 and 2\*3\*5\*7=210. Since 210%30=0, `A` is a subset of `B`. I'm expecting the largest integer to be couple of million at most, so I think it's doable.
Are there any more efficient algorithms? | 2011/08/01 | [
"https://Stackoverflow.com/questions/6894117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/377160/"
] | The asymptotically fastest approach would be to just put each set in a hash table and query each element, which is `O(N)` time. You cannot do better (since it will take that much time to read the data).
Most set datastructures already support expected and/or amortized O(1) query time. Some languages even support this operation. For example in python, you could just do
```
A < B
```
Of course the picture changes drastically depending on what you mean by "this operation is repeated". If you have the ability to do precalculations on the data as you add it to the set (which presumably you have the ability to do so), this will allow you to subsume the minimal `O(N)` time into other operations such as constructing the set. But we can't advise without knowing much more.
Assuming you had full control of the set datastructure, your approach to keep a running product (whenever you add an element, you do a single `O(1)` multiplication) is a very good idea IF there exists a divisibility test that is faster than `O(N)`... in fact your solution is really smart, because we can just do a single ALU division and hope we're within float tolerance. Do note however this will only allow you roughly a speedup factor of `20x` max I think, since `21! > 2^64`. There might be tricks to play with congruence-modulo-an-integer, but I can't think of any. I have a slight hunch though that there is no divisibility test that is faster than `O(#primes)`, though I'd like to be proved wrong!
If you are doing this repeatedly on duplicates, you may benefit from caching depending on what exactly you are doing; give each set a unique ID (though since this makes updates hard, you may ironically wish to do something exactly like your scheme to make fingerprints, but mod max\_int\_size with detection-collision). To manage memory, you can pin extremely expensive set comparison (e.g. checking if a giant set is part of itself) into the cache, while otherwise using a most-recent policy if you run into memory issues. This nice thing about this is it synergizes with an element-by-element rejection test. That is, you will be throwing out sets quickly if they don't have many overlapping elements, but if they have many overlapping elements the calculations will take a long time, and if you repeat these calculations, caching could come in handy. | I'll present an O(m+n) time-per-test algorithm. But first, two notes regarding the problem statement:
Note 1 - Your edits say that set sizes may be a few thousand, and numbers may range up to a million or two.
In following, let m, n denote the sizes of sets A, B and let R denote the size of the largest numbers allowed in sets.
Note 2 - The multiplication method you proposed is quite inefficient. Although it uses O(m+n) multiplies, it is not an O(m+n) method because the product lengths are worse than O(m) and O(n), so it would take more than O(m^2 + n^2) time, which is worse than the O(m ln(m) + n ln(n)) time required for sorting-based methods, which in turn is worse than the O(m+n) time of the following method.
For the presentation below, I suppose that sets A, B can completely change between tests, which you say can occur several hundred times per second. If there are partial changes, and you know which p elements change in A from one test to next, and which q change in B, then the method can be revised to run in O(p+q) time per test.
Step 0. (Performed one time only, at outset.) Clear an array F, containing R bits or bytes, as you prefer.
Step 1. (Initial step of per-test code.) For i from 0 to n-1, set F[B[i]], where B[i] denotes the i'th element of set B. This is O(n).
Step 2. For i from 0 to m-1, { test F[A[i]]. If it is clear, report that A is not a subset of B, and go to step 4; else continue }. This is O(m).
Step 3. Report that A is a subset of B.
Step 4. (Clear used bits) For i from 0 to n-1, clear F[B[i]]. This is O(n).
The initial step (clearing array F) is O(R) but steps 1-4 amount to O(m+n) time. |
6,894,117 | I'm writing a program where I'm having to test if one set of unique integers `A` belongs to another set of unique numbers `B`. However, this operation might be done several hundred times per second, so I'm looking for an efficient algorithm to do it.
For example, if `A = [1 2 3]` and `B = [1 2 3 4]`, it is true, but if `B = [1 2 4 5 6]`, it's false.
I'm not sure how efficient it is to just sort and compare, so I'm wondering if there are any more efficient algorithms.
One idea I came up with, was to give each number `n` their corresponding `n`'th prime: that is 1 = 2, 2 = 3, 3 = 5, 4 = 7 etc. Then I could calculate the product of `A`, and if that product is a factor of the similar product of `B`, we could say that `A` is a subset of similar `B` with certainty. For example, if `A = [1 2 3]`, `B = [1 2 3 4]` the primes are [2 3 5] and [2 3 5 7] and the products 2\*3\*5=30 and 2\*3\*5\*7=210. Since 210%30=0, `A` is a subset of `B`. I'm expecting the largest integer to be couple of million at most, so I think it's doable.
Are there any more efficient algorithms? | 2011/08/01 | [
"https://Stackoverflow.com/questions/6894117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/377160/"
] | The asymptotically fastest approach would be to just put each set in a hash table and query each element, which is `O(N)` time. You cannot do better (since it will take that much time to read the data).
Most set datastructures already support expected and/or amortized O(1) query time. Some languages even support this operation. For example in python, you could just do
```
A < B
```
Of course the picture changes drastically depending on what you mean by "this operation is repeated". If you have the ability to do precalculations on the data as you add it to the set (which presumably you have the ability to do so), this will allow you to subsume the minimal `O(N)` time into other operations such as constructing the set. But we can't advise without knowing much more.
Assuming you had full control of the set datastructure, your approach to keep a running product (whenever you add an element, you do a single `O(1)` multiplication) is a very good idea IF there exists a divisibility test that is faster than `O(N)`... in fact your solution is really smart, because we can just do a single ALU division and hope we're within float tolerance. Do note however this will only allow you roughly a speedup factor of `20x` max I think, since `21! > 2^64`. There might be tricks to play with congruence-modulo-an-integer, but I can't think of any. I have a slight hunch though that there is no divisibility test that is faster than `O(#primes)`, though I'd like to be proved wrong!
If you are doing this repeatedly on duplicates, you may benefit from caching depending on what exactly you are doing; give each set a unique ID (though since this makes updates hard, you may ironically wish to do something exactly like your scheme to make fingerprints, but mod max\_int\_size with detection-collision). To manage memory, you can pin extremely expensive set comparison (e.g. checking if a giant set is part of itself) into the cache, while otherwise using a most-recent policy if you run into memory issues. This nice thing about this is it synergizes with an element-by-element rejection test. That is, you will be throwing out sets quickly if they don't have many overlapping elements, but if they have many overlapping elements the calculations will take a long time, and if you repeat these calculations, caching could come in handy. | Given the limit on the size of the integers, if the set of B sets is small and changes seldom, consider representing the B sets as bitsets (bit arrays indexed by integer set member). This doesn't require sorting, and the test for each element is very fast.
If the A members are sorted and tend to be clustered together, then get another speedup by testing all the element in one word of the bitset at a time. |
37,122,348 | This is my situation in psuedo code
```
<div data-ng-controller="test">
<div isolated-directive>
<select ng-model="testControllerScopeVar">...</select>
</div>
<div ng-if="some condition that uses testControllerScopeVar"></div>
</div>
```
This worked perfectly before I added `isolated-directive`, now that it is added (`scope: true`) the `ng-if` no longer works because I think it is getting eat up inside of the directive.
What is the most efficient way to get this working without touching the structure of the html and `isolated-directive`? | 2016/05/09 | [
"https://Stackoverflow.com/questions/37122348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058134/"
] | Well it seems once I know the solution, it is so simple
```
<div data-ng-controller="test as testCtrl">
<div isolated-directive>
<select ng-model="testCtrl.testControllerScopeVar">...</select>
</div>
<div ng-if="testCtrl.testControllerScopeVar == 'whatever'"></div>
</div>
```
ControllerAs allows me to specifically access the right scope and works perfectly, thanks all for your time and input | One approach is to map the controller variable into your isolated scope and attach the isolated scope variable to your internal `ng-model`.
So your HTML would look like this:
```
<div data-ng-controller="test">
<div isolated-directive="testControllerScopeVar">
<select ng-model="isolatedScopeVar">...</select>
</div>
<div ng-if="some condition that uses testControllerScopeVar"></div>
</div>
```
And your directive declaration would look like this:
```
app.directive('isolatedDirective', function () {
return {
scope: {
isolatedScopeVar: '=isolatedDirective'
}
};
});
``` |
37,122,348 | This is my situation in psuedo code
```
<div data-ng-controller="test">
<div isolated-directive>
<select ng-model="testControllerScopeVar">...</select>
</div>
<div ng-if="some condition that uses testControllerScopeVar"></div>
</div>
```
This worked perfectly before I added `isolated-directive`, now that it is added (`scope: true`) the `ng-if` no longer works because I think it is getting eat up inside of the directive.
What is the most efficient way to get this working without touching the structure of the html and `isolated-directive`? | 2016/05/09 | [
"https://Stackoverflow.com/questions/37122348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058134/"
] | Well it seems once I know the solution, it is so simple
```
<div data-ng-controller="test as testCtrl">
<div isolated-directive>
<select ng-model="testCtrl.testControllerScopeVar">...</select>
</div>
<div ng-if="testCtrl.testControllerScopeVar == 'whatever'"></div>
</div>
```
ControllerAs allows me to specifically access the right scope and works perfectly, thanks all for your time and input | You can try jQuery to get the value and assign it to a new scope variable. Something like this
HTML
```
<div ng-app="TestApp">
<div data-ng-controller="test">
<div isolated-directive>
<input id="isolatedVar" ng-model="testControllerScopeVar" />
</div>
<div>
{{isolatedVar}}
</div>
</div>
</div>
```
JS
```
var app = angular.module('TestApp', []);
app.controller('test', function($scope) {
var element = angular.element(document.querySelector('#isolatedVar'));
element.bind('keyup', function() {
$scope.isolatedVar = element.val();
console.log($scope.isolatedVar);
$scope.$watch('isolatedVar', function() {});
});
});
app.directive('isolatedDirective', function() {
return {
scope: true
};
});
```
Working fiddle <https://jsfiddle.net/kavinio/yzb8ouzd/1/> |
343,820 | So, I am trying to create an English language trie data structure implementation in C++. I have created a `Trie` and `TrieNode` class. The `TrieNode` class takes in its constructor a `vector<string>` that is a list of words to construct the Trie from.
My solution to getting this `vector<string>` was to use an `EnglishWordsListGenerator` class, which in its constructor, takes in a string of the file name of a file which presumably contains a list of valid English words. (The ever popular `enable1.txt` file).
I'm new to C++, so I don't know if it is considered good practice or not to read the file directly from the constructor when initializing the object. After all, what if the operation fails? On the other hand though, I know Bjarne heavily pushes for RAII. What is the right thing to do here? | 2017/03/09 | [
"https://softwareengineering.stackexchange.com/questions/343820",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/145002/"
] | If you are new to C++, it may be desirable to shy away from doing big work in a constructor. Constructors are wedded tightly to the way the language behaves, and you really don't want the constructor getting called unexpectedly (`explicit` is your friend!). Constructors are also rather unique in that they cannot return a value. This can make error handling more complicated.
This sort of recommendation becomes less important as you learn more about C++ and all the different things which can cause constructors to get called. In the perfect world, the correct answer is that your library should do exactly what the user wanted it to at all times. Quite often in C++ that is best implemented by doing things inside constructors. However, you just want to make sure that you understand constructors enough not to trap your users in a corner. Debugging why the program operates poorly because a constructor got invoked when a user did not intend it to be invoked can be a pain.
Likewise exception handling in constructors can be more difficult because the scope where the exception occurs is entwined with the scope where a variable gets created, rather than where you want to use it. Exceptions can be infuriating when they occur *before* `main()` is run, denying you the ability to handle that exception for the user. This can happen if you use global variables and the errors can be cryptic.
One option that sits between the extremes is to use factory methods. If your users expect to use factory methods, it makes sense that they could do a little extra initialization at that point. A factory method won't be called by accident like a constructor might, so it's harder to mess it up.
Once you are confident you understand the consequences of doing work in a constructor, it can be a powerful tool. The ultimate example of doing work in a constructor might be the `lock_guard` class. Lock guards are constructed by passing them a lock such as a mutex. They call `.lock()` on it during their constructor (aka doing real work) and `.unlock()` on it during their destructor.
These classes get away with doing real work in the constructor because they are designed to be used that way. Anyone working with a `lock_guard` is well aware that the constructor does work because code that uses it looks something like:
```
{
lock_guard guardMe(myLock); // locks myLock
doSomeStuff();
doMoreStuff();
// as I leave this block, guardMe will unlock myLock. It will do so
// even if I leave via an exception!
}
```
If you look at the implementations of `lock_guard` classes, you will find easily 80% of their attention or more is focused on how to manage the constructors correctly to prevent surprises. Properly implemented, they're very powerful. Improperly implemented `lock_guards` can be the bane of your existence because they can appear to do one thing when they actually do another. | I don't think I would read a file in the constructor for a couple of reasons:
1. it will significantly slow down object creation and potentially the
startup of your program.
2. as you mentioned, there are limited options for error handling. You would have to either put the entire program in a try...catch block or set some sort of flag if something
goes wrong.
3. what if you need to read it in more than once? You
would have to have a duplicate of the code, or split the code out to
a function the constructor calls, in which case just do it after the
object is created anyway.
I'm sure there are other reason, those are just the first ones that came to my mind. If its a small file and you are only reading it the once, you are probably ok. |
343,820 | So, I am trying to create an English language trie data structure implementation in C++. I have created a `Trie` and `TrieNode` class. The `TrieNode` class takes in its constructor a `vector<string>` that is a list of words to construct the Trie from.
My solution to getting this `vector<string>` was to use an `EnglishWordsListGenerator` class, which in its constructor, takes in a string of the file name of a file which presumably contains a list of valid English words. (The ever popular `enable1.txt` file).
I'm new to C++, so I don't know if it is considered good practice or not to read the file directly from the constructor when initializing the object. After all, what if the operation fails? On the other hand though, I know Bjarne heavily pushes for RAII. What is the right thing to do here? | 2017/03/09 | [
"https://softwareengineering.stackexchange.com/questions/343820",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/145002/"
] | When seeing a class with a constructor signature like
```
EnglishWordsListGenerator(const std::string &wordFileName)
```
I think it is pretty obvious that this constructor will read the given file (and so need some time), and it should not be to hard to understand that the caller has to care for possible exceptions from this (because file IO can fail). So despite what other answers are saying, **this design is ok**.
Don't get me wrong, in the future you might get requirements where this design might not be sufficient any more, but as long as this simple interface and behaviour is all your program needs, I would stick to the KISS and YAGNI principles and avoid overcomplicating things by providing a separate initialization method "just in case". | I don't think I would read a file in the constructor for a couple of reasons:
1. it will significantly slow down object creation and potentially the
startup of your program.
2. as you mentioned, there are limited options for error handling. You would have to either put the entire program in a try...catch block or set some sort of flag if something
goes wrong.
3. what if you need to read it in more than once? You
would have to have a duplicate of the code, or split the code out to
a function the constructor calls, in which case just do it after the
object is created anyway.
I'm sure there are other reason, those are just the first ones that came to my mind. If its a small file and you are only reading it the once, you are probably ok. |
343,820 | So, I am trying to create an English language trie data structure implementation in C++. I have created a `Trie` and `TrieNode` class. The `TrieNode` class takes in its constructor a `vector<string>` that is a list of words to construct the Trie from.
My solution to getting this `vector<string>` was to use an `EnglishWordsListGenerator` class, which in its constructor, takes in a string of the file name of a file which presumably contains a list of valid English words. (The ever popular `enable1.txt` file).
I'm new to C++, so I don't know if it is considered good practice or not to read the file directly from the constructor when initializing the object. After all, what if the operation fails? On the other hand though, I know Bjarne heavily pushes for RAII. What is the right thing to do here? | 2017/03/09 | [
"https://softwareengineering.stackexchange.com/questions/343820",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/145002/"
] | It's not a good practice to load an object from a file in the constructor.
Beyond the good C++ arguments in the other answers, I'd add a clean code principle: *[a function should do only one thing](http://www.itiseezee.com/?p=119)*. Ok, the constructor is not a normal function, but the principle still applies.
I suggest the following:
* keep the `Trie` as general as possible to aim at reuse. There are plenty of other applications that could use it.
* keep it independent of the way you feed it: ideally. Different application could use different approaches, for example to feed it from a `string` or from an `istream`. After all, future versions of your app could querry the words from a database with different languages.
* use a [builder design pattern](http://www.oodesign.com/builder-pattern.html), to assemble the pieces of the construction process. The builder would then load the trie from a source, using some kind of general approach (e.g. Create the trie, Open the source, iterate through source data and inserting it into the trie, once it is done return the trie). You could then make a concrete builder for loading from a file, and easily opt for other alternatives. | I don't think I would read a file in the constructor for a couple of reasons:
1. it will significantly slow down object creation and potentially the
startup of your program.
2. as you mentioned, there are limited options for error handling. You would have to either put the entire program in a try...catch block or set some sort of flag if something
goes wrong.
3. what if you need to read it in more than once? You
would have to have a duplicate of the code, or split the code out to
a function the constructor calls, in which case just do it after the
object is created anyway.
I'm sure there are other reason, those are just the first ones that came to my mind. If its a small file and you are only reading it the once, you are probably ok. |
343,820 | So, I am trying to create an English language trie data structure implementation in C++. I have created a `Trie` and `TrieNode` class. The `TrieNode` class takes in its constructor a `vector<string>` that is a list of words to construct the Trie from.
My solution to getting this `vector<string>` was to use an `EnglishWordsListGenerator` class, which in its constructor, takes in a string of the file name of a file which presumably contains a list of valid English words. (The ever popular `enable1.txt` file).
I'm new to C++, so I don't know if it is considered good practice or not to read the file directly from the constructor when initializing the object. After all, what if the operation fails? On the other hand though, I know Bjarne heavily pushes for RAII. What is the right thing to do here? | 2017/03/09 | [
"https://softwareengineering.stackexchange.com/questions/343820",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/145002/"
] | I don't think I would read a file in the constructor for a couple of reasons:
1. it will significantly slow down object creation and potentially the
startup of your program.
2. as you mentioned, there are limited options for error handling. You would have to either put the entire program in a try...catch block or set some sort of flag if something
goes wrong.
3. what if you need to read it in more than once? You
would have to have a duplicate of the code, or split the code out to
a function the constructor calls, in which case just do it after the
object is created anyway.
I'm sure there are other reason, those are just the first ones that came to my mind. If its a small file and you are only reading it the once, you are probably ok. | If the constructor does a lot of work, then there can be exceptions. In C++, exception in a constructor can be handled, but in practice you wouldn’t know how to do it correctly, and it is an absolute pain.
Much easier to write a factory method or even just a plain function that creates an object on the heap, reads a file while handling exceptions, and returns a pointer to the object or a null pointer. |
343,820 | So, I am trying to create an English language trie data structure implementation in C++. I have created a `Trie` and `TrieNode` class. The `TrieNode` class takes in its constructor a `vector<string>` that is a list of words to construct the Trie from.
My solution to getting this `vector<string>` was to use an `EnglishWordsListGenerator` class, which in its constructor, takes in a string of the file name of a file which presumably contains a list of valid English words. (The ever popular `enable1.txt` file).
I'm new to C++, so I don't know if it is considered good practice or not to read the file directly from the constructor when initializing the object. After all, what if the operation fails? On the other hand though, I know Bjarne heavily pushes for RAII. What is the right thing to do here? | 2017/03/09 | [
"https://softwareengineering.stackexchange.com/questions/343820",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/145002/"
] | When seeing a class with a constructor signature like
```
EnglishWordsListGenerator(const std::string &wordFileName)
```
I think it is pretty obvious that this constructor will read the given file (and so need some time), and it should not be to hard to understand that the caller has to care for possible exceptions from this (because file IO can fail). So despite what other answers are saying, **this design is ok**.
Don't get me wrong, in the future you might get requirements where this design might not be sufficient any more, but as long as this simple interface and behaviour is all your program needs, I would stick to the KISS and YAGNI principles and avoid overcomplicating things by providing a separate initialization method "just in case". | If you are new to C++, it may be desirable to shy away from doing big work in a constructor. Constructors are wedded tightly to the way the language behaves, and you really don't want the constructor getting called unexpectedly (`explicit` is your friend!). Constructors are also rather unique in that they cannot return a value. This can make error handling more complicated.
This sort of recommendation becomes less important as you learn more about C++ and all the different things which can cause constructors to get called. In the perfect world, the correct answer is that your library should do exactly what the user wanted it to at all times. Quite often in C++ that is best implemented by doing things inside constructors. However, you just want to make sure that you understand constructors enough not to trap your users in a corner. Debugging why the program operates poorly because a constructor got invoked when a user did not intend it to be invoked can be a pain.
Likewise exception handling in constructors can be more difficult because the scope where the exception occurs is entwined with the scope where a variable gets created, rather than where you want to use it. Exceptions can be infuriating when they occur *before* `main()` is run, denying you the ability to handle that exception for the user. This can happen if you use global variables and the errors can be cryptic.
One option that sits between the extremes is to use factory methods. If your users expect to use factory methods, it makes sense that they could do a little extra initialization at that point. A factory method won't be called by accident like a constructor might, so it's harder to mess it up.
Once you are confident you understand the consequences of doing work in a constructor, it can be a powerful tool. The ultimate example of doing work in a constructor might be the `lock_guard` class. Lock guards are constructed by passing them a lock such as a mutex. They call `.lock()` on it during their constructor (aka doing real work) and `.unlock()` on it during their destructor.
These classes get away with doing real work in the constructor because they are designed to be used that way. Anyone working with a `lock_guard` is well aware that the constructor does work because code that uses it looks something like:
```
{
lock_guard guardMe(myLock); // locks myLock
doSomeStuff();
doMoreStuff();
// as I leave this block, guardMe will unlock myLock. It will do so
// even if I leave via an exception!
}
```
If you look at the implementations of `lock_guard` classes, you will find easily 80% of their attention or more is focused on how to manage the constructors correctly to prevent surprises. Properly implemented, they're very powerful. Improperly implemented `lock_guards` can be the bane of your existence because they can appear to do one thing when they actually do another. |
343,820 | So, I am trying to create an English language trie data structure implementation in C++. I have created a `Trie` and `TrieNode` class. The `TrieNode` class takes in its constructor a `vector<string>` that is a list of words to construct the Trie from.
My solution to getting this `vector<string>` was to use an `EnglishWordsListGenerator` class, which in its constructor, takes in a string of the file name of a file which presumably contains a list of valid English words. (The ever popular `enable1.txt` file).
I'm new to C++, so I don't know if it is considered good practice or not to read the file directly from the constructor when initializing the object. After all, what if the operation fails? On the other hand though, I know Bjarne heavily pushes for RAII. What is the right thing to do here? | 2017/03/09 | [
"https://softwareengineering.stackexchange.com/questions/343820",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/145002/"
] | If you are new to C++, it may be desirable to shy away from doing big work in a constructor. Constructors are wedded tightly to the way the language behaves, and you really don't want the constructor getting called unexpectedly (`explicit` is your friend!). Constructors are also rather unique in that they cannot return a value. This can make error handling more complicated.
This sort of recommendation becomes less important as you learn more about C++ and all the different things which can cause constructors to get called. In the perfect world, the correct answer is that your library should do exactly what the user wanted it to at all times. Quite often in C++ that is best implemented by doing things inside constructors. However, you just want to make sure that you understand constructors enough not to trap your users in a corner. Debugging why the program operates poorly because a constructor got invoked when a user did not intend it to be invoked can be a pain.
Likewise exception handling in constructors can be more difficult because the scope where the exception occurs is entwined with the scope where a variable gets created, rather than where you want to use it. Exceptions can be infuriating when they occur *before* `main()` is run, denying you the ability to handle that exception for the user. This can happen if you use global variables and the errors can be cryptic.
One option that sits between the extremes is to use factory methods. If your users expect to use factory methods, it makes sense that they could do a little extra initialization at that point. A factory method won't be called by accident like a constructor might, so it's harder to mess it up.
Once you are confident you understand the consequences of doing work in a constructor, it can be a powerful tool. The ultimate example of doing work in a constructor might be the `lock_guard` class. Lock guards are constructed by passing them a lock such as a mutex. They call `.lock()` on it during their constructor (aka doing real work) and `.unlock()` on it during their destructor.
These classes get away with doing real work in the constructor because they are designed to be used that way. Anyone working with a `lock_guard` is well aware that the constructor does work because code that uses it looks something like:
```
{
lock_guard guardMe(myLock); // locks myLock
doSomeStuff();
doMoreStuff();
// as I leave this block, guardMe will unlock myLock. It will do so
// even if I leave via an exception!
}
```
If you look at the implementations of `lock_guard` classes, you will find easily 80% of their attention or more is focused on how to manage the constructors correctly to prevent surprises. Properly implemented, they're very powerful. Improperly implemented `lock_guards` can be the bane of your existence because they can appear to do one thing when they actually do another. | If the constructor does a lot of work, then there can be exceptions. In C++, exception in a constructor can be handled, but in practice you wouldn’t know how to do it correctly, and it is an absolute pain.
Much easier to write a factory method or even just a plain function that creates an object on the heap, reads a file while handling exceptions, and returns a pointer to the object or a null pointer. |
343,820 | So, I am trying to create an English language trie data structure implementation in C++. I have created a `Trie` and `TrieNode` class. The `TrieNode` class takes in its constructor a `vector<string>` that is a list of words to construct the Trie from.
My solution to getting this `vector<string>` was to use an `EnglishWordsListGenerator` class, which in its constructor, takes in a string of the file name of a file which presumably contains a list of valid English words. (The ever popular `enable1.txt` file).
I'm new to C++, so I don't know if it is considered good practice or not to read the file directly from the constructor when initializing the object. After all, what if the operation fails? On the other hand though, I know Bjarne heavily pushes for RAII. What is the right thing to do here? | 2017/03/09 | [
"https://softwareengineering.stackexchange.com/questions/343820",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/145002/"
] | When seeing a class with a constructor signature like
```
EnglishWordsListGenerator(const std::string &wordFileName)
```
I think it is pretty obvious that this constructor will read the given file (and so need some time), and it should not be to hard to understand that the caller has to care for possible exceptions from this (because file IO can fail). So despite what other answers are saying, **this design is ok**.
Don't get me wrong, in the future you might get requirements where this design might not be sufficient any more, but as long as this simple interface and behaviour is all your program needs, I would stick to the KISS and YAGNI principles and avoid overcomplicating things by providing a separate initialization method "just in case". | It's not a good practice to load an object from a file in the constructor.
Beyond the good C++ arguments in the other answers, I'd add a clean code principle: *[a function should do only one thing](http://www.itiseezee.com/?p=119)*. Ok, the constructor is not a normal function, but the principle still applies.
I suggest the following:
* keep the `Trie` as general as possible to aim at reuse. There are plenty of other applications that could use it.
* keep it independent of the way you feed it: ideally. Different application could use different approaches, for example to feed it from a `string` or from an `istream`. After all, future versions of your app could querry the words from a database with different languages.
* use a [builder design pattern](http://www.oodesign.com/builder-pattern.html), to assemble the pieces of the construction process. The builder would then load the trie from a source, using some kind of general approach (e.g. Create the trie, Open the source, iterate through source data and inserting it into the trie, once it is done return the trie). You could then make a concrete builder for loading from a file, and easily opt for other alternatives. |
343,820 | So, I am trying to create an English language trie data structure implementation in C++. I have created a `Trie` and `TrieNode` class. The `TrieNode` class takes in its constructor a `vector<string>` that is a list of words to construct the Trie from.
My solution to getting this `vector<string>` was to use an `EnglishWordsListGenerator` class, which in its constructor, takes in a string of the file name of a file which presumably contains a list of valid English words. (The ever popular `enable1.txt` file).
I'm new to C++, so I don't know if it is considered good practice or not to read the file directly from the constructor when initializing the object. After all, what if the operation fails? On the other hand though, I know Bjarne heavily pushes for RAII. What is the right thing to do here? | 2017/03/09 | [
"https://softwareengineering.stackexchange.com/questions/343820",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/145002/"
] | When seeing a class with a constructor signature like
```
EnglishWordsListGenerator(const std::string &wordFileName)
```
I think it is pretty obvious that this constructor will read the given file (and so need some time), and it should not be to hard to understand that the caller has to care for possible exceptions from this (because file IO can fail). So despite what other answers are saying, **this design is ok**.
Don't get me wrong, in the future you might get requirements where this design might not be sufficient any more, but as long as this simple interface and behaviour is all your program needs, I would stick to the KISS and YAGNI principles and avoid overcomplicating things by providing a separate initialization method "just in case". | If the constructor does a lot of work, then there can be exceptions. In C++, exception in a constructor can be handled, but in practice you wouldn’t know how to do it correctly, and it is an absolute pain.
Much easier to write a factory method or even just a plain function that creates an object on the heap, reads a file while handling exceptions, and returns a pointer to the object or a null pointer. |
343,820 | So, I am trying to create an English language trie data structure implementation in C++. I have created a `Trie` and `TrieNode` class. The `TrieNode` class takes in its constructor a `vector<string>` that is a list of words to construct the Trie from.
My solution to getting this `vector<string>` was to use an `EnglishWordsListGenerator` class, which in its constructor, takes in a string of the file name of a file which presumably contains a list of valid English words. (The ever popular `enable1.txt` file).
I'm new to C++, so I don't know if it is considered good practice or not to read the file directly from the constructor when initializing the object. After all, what if the operation fails? On the other hand though, I know Bjarne heavily pushes for RAII. What is the right thing to do here? | 2017/03/09 | [
"https://softwareengineering.stackexchange.com/questions/343820",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/145002/"
] | It's not a good practice to load an object from a file in the constructor.
Beyond the good C++ arguments in the other answers, I'd add a clean code principle: *[a function should do only one thing](http://www.itiseezee.com/?p=119)*. Ok, the constructor is not a normal function, but the principle still applies.
I suggest the following:
* keep the `Trie` as general as possible to aim at reuse. There are plenty of other applications that could use it.
* keep it independent of the way you feed it: ideally. Different application could use different approaches, for example to feed it from a `string` or from an `istream`. After all, future versions of your app could querry the words from a database with different languages.
* use a [builder design pattern](http://www.oodesign.com/builder-pattern.html), to assemble the pieces of the construction process. The builder would then load the trie from a source, using some kind of general approach (e.g. Create the trie, Open the source, iterate through source data and inserting it into the trie, once it is done return the trie). You could then make a concrete builder for loading from a file, and easily opt for other alternatives. | If the constructor does a lot of work, then there can be exceptions. In C++, exception in a constructor can be handled, but in practice you wouldn’t know how to do it correctly, and it is an absolute pain.
Much easier to write a factory method or even just a plain function that creates an object on the heap, reads a file while handling exceptions, and returns a pointer to the object or a null pointer. |
161,941 | I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With [Vo'Toyias Spiker](http://us.battle.net/d3/en/item/votoyias-spiker) equipped and using [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) with Reflective Skin and [Provoke](http://us.battle.net/d3/en/class/crusader/active/provoke) with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns? | 2014/03/27 | [
"https://gaming.stackexchange.com/questions/161941",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1719/"
] | In the [2.0.5 patch notes](http://us.battle.net/d3/en/blog/14138344/patch-205-now-live-5-13-2014#items), they mention changing the item [Sanguinary Vambraces](http://us.battle.net/d3/en/item/sanguinary-vambraces-1385JU). Inside this change they mention the modifier.
>
> The Thorns damage dealt by these bracers will now benefit from your
> main stat damage increase at a 25% rate, as normal Thorns damage does
>
>
>
Therefore, it is modified by 25% of your primary attribute. Confirmed. | I have analyzed the source code of the [crusader thorns DPS calculator](http://www.ring.lt/crusader/) mentioned in [user77988's answer](https://gaming.stackexchange.com/a/170463/74333). The important lines are
```
var damage = Math.round(((parseInt(strength)/400)+1)*parseInt(thorns));
var rsdamage = Math.round(((parseInt(strength)/100)+1)*2*parseInt(thorns)*(phy/100+1));
```
Where `damage` is regular Thorns damage, `rsdamage` is Reflective Skin Damage. Converting from Javascript to regular Math, that is
```
D = (S/400+1)*T
RS = (S/100+1)*2*T*(P/100+1)
```
where `S` is strength, `T` is thorns and `P` is the bonus damage to physical skills in %
This is identical to the formulas in [TheCheeseGod's answer](https://gaming.stackexchange.com/a/163658/74333). |
161,941 | I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With [Vo'Toyias Spiker](http://us.battle.net/d3/en/item/votoyias-spiker) equipped and using [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) with Reflective Skin and [Provoke](http://us.battle.net/d3/en/class/crusader/active/provoke) with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns? | 2014/03/27 | [
"https://gaming.stackexchange.com/questions/161941",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1719/"
] | After doing some math, I arrived at the following formulas for thorns damage:
**Regular Attack**
* ((S / 100 / 4) + 1) \* T
**Reflective Skin Attack**
* ((S / 100) + 1) \* 2T \* (P / 100 + 1)
where
* S is Strength (or mainstat)
* T is your thorns damage
* P is your Physical Damage bonus (as a percent)
It does not appear that regular thorns damage can crit, nor is it based off your weapon damage or the damage done to you. It did not to appear to be affected by any damage reduction modifiers nor is it improved by bonuses to Physical Damage Skills. It is scaled according to your mainstat by 1/4
Reflective Skin does indeed double your base thorns damage. However, because it is a skill doing the damage and not the thorns mechanic, it scales off your mainstat like all other skills (not at a 1/4 ratio). It is also then eligible to crit and receive your "+X% Damage to Physical Skills" bonuses. This is the reason for the (more than 2x) large spike in damage when using Reflective Skin.
An example:
For a crusader with 5000 Strength and 10000 Thorns and 20% Bonus to Physical Skills:
* A regular attack would deal 135,000 damage.
* An attack while Reflective Skin is active would deal 1,224,000 damage
(with the option to crit). | I have analyzed the source code of the [crusader thorns DPS calculator](http://www.ring.lt/crusader/) mentioned in [user77988's answer](https://gaming.stackexchange.com/a/170463/74333). The important lines are
```
var damage = Math.round(((parseInt(strength)/400)+1)*parseInt(thorns));
var rsdamage = Math.round(((parseInt(strength)/100)+1)*2*parseInt(thorns)*(phy/100+1));
```
Where `damage` is regular Thorns damage, `rsdamage` is Reflective Skin Damage. Converting from Javascript to regular Math, that is
```
D = (S/400+1)*T
RS = (S/100+1)*2*T*(P/100+1)
```
where `S` is strength, `T` is thorns and `P` is the bonus damage to physical skills in %
This is identical to the formulas in [TheCheeseGod's answer](https://gaming.stackexchange.com/a/163658/74333). |
161,941 | I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With [Vo'Toyias Spiker](http://us.battle.net/d3/en/item/votoyias-spiker) equipped and using [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) with Reflective Skin and [Provoke](http://us.battle.net/d3/en/class/crusader/active/provoke) with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns? | 2014/03/27 | [
"https://gaming.stackexchange.com/questions/161941",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1719/"
] | Here's a thorns crusader damage calculator:
<http://www.ring.lt/crusader/> | I have analyzed the source code of the [crusader thorns DPS calculator](http://www.ring.lt/crusader/) mentioned in [user77988's answer](https://gaming.stackexchange.com/a/170463/74333). The important lines are
```
var damage = Math.round(((parseInt(strength)/400)+1)*parseInt(thorns));
var rsdamage = Math.round(((parseInt(strength)/100)+1)*2*parseInt(thorns)*(phy/100+1));
```
Where `damage` is regular Thorns damage, `rsdamage` is Reflective Skin Damage. Converting from Javascript to regular Math, that is
```
D = (S/400+1)*T
RS = (S/100+1)*2*T*(P/100+1)
```
where `S` is strength, `T` is thorns and `P` is the bonus damage to physical skills in %
This is identical to the formulas in [TheCheeseGod's answer](https://gaming.stackexchange.com/a/163658/74333). |
161,941 | I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With [Vo'Toyias Spiker](http://us.battle.net/d3/en/item/votoyias-spiker) equipped and using [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) with Reflective Skin and [Provoke](http://us.battle.net/d3/en/class/crusader/active/provoke) with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns? | 2014/03/27 | [
"https://gaming.stackexchange.com/questions/161941",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1719/"
] | After doing some math, I arrived at the following formulas for thorns damage:
**Regular Attack**
* ((S / 100 / 4) + 1) \* T
**Reflective Skin Attack**
* ((S / 100) + 1) \* 2T \* (P / 100 + 1)
where
* S is Strength (or mainstat)
* T is your thorns damage
* P is your Physical Damage bonus (as a percent)
It does not appear that regular thorns damage can crit, nor is it based off your weapon damage or the damage done to you. It did not to appear to be affected by any damage reduction modifiers nor is it improved by bonuses to Physical Damage Skills. It is scaled according to your mainstat by 1/4
Reflective Skin does indeed double your base thorns damage. However, because it is a skill doing the damage and not the thorns mechanic, it scales off your mainstat like all other skills (not at a 1/4 ratio). It is also then eligible to crit and receive your "+X% Damage to Physical Skills" bonuses. This is the reason for the (more than 2x) large spike in damage when using Reflective Skin.
An example:
For a crusader with 5000 Strength and 10000 Thorns and 20% Bonus to Physical Skills:
* A regular attack would deal 135,000 damage.
* An attack while Reflective Skin is active would deal 1,224,000 damage
(with the option to crit). | In the [2.0.5 patch notes](http://us.battle.net/d3/en/blog/14138344/patch-205-now-live-5-13-2014#items), they mention changing the item [Sanguinary Vambraces](http://us.battle.net/d3/en/item/sanguinary-vambraces-1385JU). Inside this change they mention the modifier.
>
> The Thorns damage dealt by these bracers will now benefit from your
> main stat damage increase at a 25% rate, as normal Thorns damage does
>
>
>
Therefore, it is modified by 25% of your primary attribute. Confirmed. |
161,941 | I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With [Vo'Toyias Spiker](http://us.battle.net/d3/en/item/votoyias-spiker) equipped and using [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) with Reflective Skin and [Provoke](http://us.battle.net/d3/en/class/crusader/active/provoke) with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns? | 2014/03/27 | [
"https://gaming.stackexchange.com/questions/161941",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1719/"
] | After doing some research, I have reached a few conclusions, plus found how the approximate damage works.
Thorns return damage does *not* depend on how much damage the attack against you does. It's calculated by your base thorns times a multiplier based on your primary stat. The multiplier is one quarter of the bonus provided to your attacking damage. For example, if you have 20,000 thorns, and 6,000 strength, then you'll get 1500% bonus thorns damage (6000 / 4 as a percentage), which amounts to 320,000 thorns damage to enemies when they attack you (20,000 base plus 300,000 bonus from primary stat). This can then crit based on your normal crit chance and crit damage.
All of the insanely high damage numbers occur using the [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) skill with the Reflective Skin rune, which appears to be bugged currently and do lots of wonky stuff ([including killing allied Crusaders](http://www.reddit.com/r/Diablo/comments/21l721/hardcore_beware_crusader_bug_lets_you_kill_allied/)). | I did some testing because I was wondering the same question and came to the conclusion that only your main stat and dmg taken debuffs on the target affect thorns damage (dmg buffs on yourself do not increase thorns dmg, atleast not the ones I tested with), dmg taken debuff affects thorns dmg by 75% the normal amount and main stat increases thorns dmg about 25% of the normal dmg increase. |
161,941 | I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With [Vo'Toyias Spiker](http://us.battle.net/d3/en/item/votoyias-spiker) equipped and using [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) with Reflective Skin and [Provoke](http://us.battle.net/d3/en/class/crusader/active/provoke) with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns? | 2014/03/27 | [
"https://gaming.stackexchange.com/questions/161941",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1719/"
] | After doing some research, I have reached a few conclusions, plus found how the approximate damage works.
Thorns return damage does *not* depend on how much damage the attack against you does. It's calculated by your base thorns times a multiplier based on your primary stat. The multiplier is one quarter of the bonus provided to your attacking damage. For example, if you have 20,000 thorns, and 6,000 strength, then you'll get 1500% bonus thorns damage (6000 / 4 as a percentage), which amounts to 320,000 thorns damage to enemies when they attack you (20,000 base plus 300,000 bonus from primary stat). This can then crit based on your normal crit chance and crit damage.
All of the insanely high damage numbers occur using the [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) skill with the Reflective Skin rune, which appears to be bugged currently and do lots of wonky stuff ([including killing allied Crusaders](http://www.reddit.com/r/Diablo/comments/21l721/hardcore_beware_crusader_bug_lets_you_kill_allied/)). | I have analyzed the source code of the [crusader thorns DPS calculator](http://www.ring.lt/crusader/) mentioned in [user77988's answer](https://gaming.stackexchange.com/a/170463/74333). The important lines are
```
var damage = Math.round(((parseInt(strength)/400)+1)*parseInt(thorns));
var rsdamage = Math.round(((parseInt(strength)/100)+1)*2*parseInt(thorns)*(phy/100+1));
```
Where `damage` is regular Thorns damage, `rsdamage` is Reflective Skin Damage. Converting from Javascript to regular Math, that is
```
D = (S/400+1)*T
RS = (S/100+1)*2*T*(P/100+1)
```
where `S` is strength, `T` is thorns and `P` is the bonus damage to physical skills in %
This is identical to the formulas in [TheCheeseGod's answer](https://gaming.stackexchange.com/a/163658/74333). |
161,941 | I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With [Vo'Toyias Spiker](http://us.battle.net/d3/en/item/votoyias-spiker) equipped and using [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) with Reflective Skin and [Provoke](http://us.battle.net/d3/en/class/crusader/active/provoke) with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns? | 2014/03/27 | [
"https://gaming.stackexchange.com/questions/161941",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1719/"
] | After doing some research, I have reached a few conclusions, plus found how the approximate damage works.
Thorns return damage does *not* depend on how much damage the attack against you does. It's calculated by your base thorns times a multiplier based on your primary stat. The multiplier is one quarter of the bonus provided to your attacking damage. For example, if you have 20,000 thorns, and 6,000 strength, then you'll get 1500% bonus thorns damage (6000 / 4 as a percentage), which amounts to 320,000 thorns damage to enemies when they attack you (20,000 base plus 300,000 bonus from primary stat). This can then crit based on your normal crit chance and crit damage.
All of the insanely high damage numbers occur using the [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) skill with the Reflective Skin rune, which appears to be bugged currently and do lots of wonky stuff ([including killing allied Crusaders](http://www.reddit.com/r/Diablo/comments/21l721/hardcore_beware_crusader_bug_lets_you_kill_allied/)). | Here's a thorns crusader damage calculator:
<http://www.ring.lt/crusader/> |
161,941 | I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With [Vo'Toyias Spiker](http://us.battle.net/d3/en/item/votoyias-spiker) equipped and using [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) with Reflective Skin and [Provoke](http://us.battle.net/d3/en/class/crusader/active/provoke) with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns? | 2014/03/27 | [
"https://gaming.stackexchange.com/questions/161941",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1719/"
] | After doing some research, I have reached a few conclusions, plus found how the approximate damage works.
Thorns return damage does *not* depend on how much damage the attack against you does. It's calculated by your base thorns times a multiplier based on your primary stat. The multiplier is one quarter of the bonus provided to your attacking damage. For example, if you have 20,000 thorns, and 6,000 strength, then you'll get 1500% bonus thorns damage (6000 / 4 as a percentage), which amounts to 320,000 thorns damage to enemies when they attack you (20,000 base plus 300,000 bonus from primary stat). This can then crit based on your normal crit chance and crit damage.
All of the insanely high damage numbers occur using the [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) skill with the Reflective Skin rune, which appears to be bugged currently and do lots of wonky stuff ([including killing allied Crusaders](http://www.reddit.com/r/Diablo/comments/21l721/hardcore_beware_crusader_bug_lets_you_kill_allied/)). | In the [2.0.5 patch notes](http://us.battle.net/d3/en/blog/14138344/patch-205-now-live-5-13-2014#items), they mention changing the item [Sanguinary Vambraces](http://us.battle.net/d3/en/item/sanguinary-vambraces-1385JU). Inside this change they mention the modifier.
>
> The Thorns damage dealt by these bracers will now benefit from your
> main stat damage increase at a 25% rate, as normal Thorns damage does
>
>
>
Therefore, it is modified by 25% of your primary attribute. Confirmed. |
161,941 | I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With [Vo'Toyias Spiker](http://us.battle.net/d3/en/item/votoyias-spiker) equipped and using [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) with Reflective Skin and [Provoke](http://us.battle.net/d3/en/class/crusader/active/provoke) with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns? | 2014/03/27 | [
"https://gaming.stackexchange.com/questions/161941",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1719/"
] | After doing some math, I arrived at the following formulas for thorns damage:
**Regular Attack**
* ((S / 100 / 4) + 1) \* T
**Reflective Skin Attack**
* ((S / 100) + 1) \* 2T \* (P / 100 + 1)
where
* S is Strength (or mainstat)
* T is your thorns damage
* P is your Physical Damage bonus (as a percent)
It does not appear that regular thorns damage can crit, nor is it based off your weapon damage or the damage done to you. It did not to appear to be affected by any damage reduction modifiers nor is it improved by bonuses to Physical Damage Skills. It is scaled according to your mainstat by 1/4
Reflective Skin does indeed double your base thorns damage. However, because it is a skill doing the damage and not the thorns mechanic, it scales off your mainstat like all other skills (not at a 1/4 ratio). It is also then eligible to crit and receive your "+X% Damage to Physical Skills" bonuses. This is the reason for the (more than 2x) large spike in damage when using Reflective Skin.
An example:
For a crusader with 5000 Strength and 10000 Thorns and 20% Bonus to Physical Skills:
* A regular attack would deal 135,000 damage.
* An attack while Reflective Skin is active would deal 1,224,000 damage
(with the option to crit). | Here's a thorns crusader damage calculator:
<http://www.ring.lt/crusader/> |
161,941 | I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With [Vo'Toyias Spiker](http://us.battle.net/d3/en/item/votoyias-spiker) equipped and using [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) with Reflective Skin and [Provoke](http://us.battle.net/d3/en/class/crusader/active/provoke) with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns? | 2014/03/27 | [
"https://gaming.stackexchange.com/questions/161941",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/1719/"
] | After doing some math, I arrived at the following formulas for thorns damage:
**Regular Attack**
* ((S / 100 / 4) + 1) \* T
**Reflective Skin Attack**
* ((S / 100) + 1) \* 2T \* (P / 100 + 1)
where
* S is Strength (or mainstat)
* T is your thorns damage
* P is your Physical Damage bonus (as a percent)
It does not appear that regular thorns damage can crit, nor is it based off your weapon damage or the damage done to you. It did not to appear to be affected by any damage reduction modifiers nor is it improved by bonuses to Physical Damage Skills. It is scaled according to your mainstat by 1/4
Reflective Skin does indeed double your base thorns damage. However, because it is a skill doing the damage and not the thorns mechanic, it scales off your mainstat like all other skills (not at a 1/4 ratio). It is also then eligible to crit and receive your "+X% Damage to Physical Skills" bonuses. This is the reason for the (more than 2x) large spike in damage when using Reflective Skin.
An example:
For a crusader with 5000 Strength and 10000 Thorns and 20% Bonus to Physical Skills:
* A regular attack would deal 135,000 damage.
* An attack while Reflective Skin is active would deal 1,224,000 damage
(with the option to crit). | After doing some research, I have reached a few conclusions, plus found how the approximate damage works.
Thorns return damage does *not* depend on how much damage the attack against you does. It's calculated by your base thorns times a multiplier based on your primary stat. The multiplier is one quarter of the bonus provided to your attacking damage. For example, if you have 20,000 thorns, and 6,000 strength, then you'll get 1500% bonus thorns damage (6000 / 4 as a percentage), which amounts to 320,000 thorns damage to enemies when they attack you (20,000 base plus 300,000 bonus from primary stat). This can then crit based on your normal crit chance and crit damage.
All of the insanely high damage numbers occur using the [Iron Skin](http://us.battle.net/d3/en/class/crusader/active/iron-skin) skill with the Reflective Skin rune, which appears to be bugged currently and do lots of wonky stuff ([including killing allied Crusaders](http://www.reddit.com/r/Diablo/comments/21l721/hardcore_beware_crusader_bug_lets_you_kill_allied/)). |
29,179,000 | I am trying to use a variable to select from an array:
This works:
```
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
function One() {
alert(myarray.bricks);
}
```
But this does not work:
```
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
var myvalue = "bricks"
function Two() {
alert(myarray.myvalue);
}
```
How do I do this properly? Here is a fiddle to show what I am trying to accomplish: <https://jsfiddle.net/chrislascelles/xhmx7hgc/2/> | 2015/03/21 | [
"https://Stackoverflow.com/questions/29179000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1218172/"
] | If its not too late, you may try this:
<https://jsfiddle.net/rradik/kuqdwuyd/>
```
<canvas id="canvas" width="200" height="200" />
var canvas;
var ctx;
var lastend = 0;
var pieColor = ["#ECD078","#D95B43","#C02942","#542437","#53777A"];
var pieData = [10,30,20,60,40];
var pieTotal = 10 + 30 + 20 + 60 + 40; // done manually for demo
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
var hwidth = ctx.canvas.width/2;
var hheight = ctx.canvas.height/2;
for (var i = 0; i < pieData.length; i++) {
ctx.fillStyle = pieColor[i];
ctx.beginPath();
ctx.moveTo(hwidth,hheight);
ctx.arc(hwidth,hheight,hheight,lastend,lastend+
(Math.PI*2*(pieData[i]/pieTotal)),false);
ctx.lineTo(hwidth,hheight);
ctx.fill();
//Labels on pie slices (fully transparent circle within outer pie circle, to get middle of pie slice)
//ctx.fillStyle = "rgba(255, 255, 255, 0.5)"; //uncomment for debugging
// ctx.beginPath();
// ctx.moveTo(hwidth,hheight);
// ctx.arc(hwidth,hheight,hheight/1.25,lastend,lastend+
// (Math.PI*(pieData[i]/pieTotal)),false); //uncomment for debugging
var radius = hheight/1.5; //use suitable radius
var endAngle = lastend + (Math.PI*(pieData[i]/pieTotal));
var setX = hwidth + Math.cos(endAngle) * radius;
var setY = hheight + Math.sin(endAngle) * radius;
ctx.fillStyle = "#ffffff";
ctx.font = '14px Calibri';
ctx.fillText(pieData[i],setX,setY);
// ctx.lineTo(hwidth,hheight);
//ctx.fill(); //uncomment for debugging
lastend += Math.PI*2*(pieData[i]/pieTotal);
}
```
May not be perfect and very efficient one, but does the job nevertheless | The problem was that all your text was overlapping.
I simply changed the order of execution. The text is now drawn after the pie chart. One more thing, I added an offset to the text, each time the loop runs I offset by 50.
[Working Example](http://jsfiddle.net/t9zka7rn/1/)
```
var offset = 50;
for (var e = 0; e < data.length; e++) {
ctx.font = 'bold 15pt Calibri';
ctx.fillText(labels[e],offset*e,180);
}
``` |
305,029 | Lets say I have two strips of leather, or other material, one black and one white. If I paint over the surface of the black leather (material) in white and the white leather (material) in black which will be cooler in the sun? | 2017/01/14 | [
"https://physics.stackexchange.com/questions/305029",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/142014/"
] | The black leather painted in white should be cooler when exposed to sunlight.
Here's why: the layer of white paint reflects a large part of the sunlight and transmits and absorbs a small amount.
$$I\_{incident} = I\_{absorbed} + I\_{transmitted} + I\_{reflected}$$
For the white paint layer, $I\_{absorbed}$ and $I\_{transmitted}$ are small, while $I\_{reflected}$ is a large value. The intensity is proportional to the power that is dissipated inside the material. Therefore, the white paint layer heats up only a bit ($I\_{absorbed}$ is small).
The black leather underneath is heated by $I\_{transmitted}$. Since it is a black surface, we can assume all of the incoming light is absorbed and heats the leather. So in total, both the paint and the leather are heated by a small fraction of the incoming intensity and therefore stay relatively cool.
On the other hand, the black paint layer on the white leather will absorb most of the incoming intensity and therefore heat up a great deal. The heated layer transmits its heat to the leather, because they are in close thermal contact (touching). | A black object absorbs all wavelengths of light and converts them into heat, so the object gets warm. A white object reflects all wavelengths of light, so the light is not converted into heat and the temperature of the object does not increase noticeably. |
305,029 | Lets say I have two strips of leather, or other material, one black and one white. If I paint over the surface of the black leather (material) in white and the white leather (material) in black which will be cooler in the sun? | 2017/01/14 | [
"https://physics.stackexchange.com/questions/305029",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/142014/"
] | The black leather painted in white should be cooler when exposed to sunlight.
Here's why: the layer of white paint reflects a large part of the sunlight and transmits and absorbs a small amount.
$$I\_{incident} = I\_{absorbed} + I\_{transmitted} + I\_{reflected}$$
For the white paint layer, $I\_{absorbed}$ and $I\_{transmitted}$ are small, while $I\_{reflected}$ is a large value. The intensity is proportional to the power that is dissipated inside the material. Therefore, the white paint layer heats up only a bit ($I\_{absorbed}$ is small).
The black leather underneath is heated by $I\_{transmitted}$. Since it is a black surface, we can assume all of the incoming light is absorbed and heats the leather. So in total, both the paint and the leather are heated by a small fraction of the incoming intensity and therefore stay relatively cool.
On the other hand, the black paint layer on the white leather will absorb most of the incoming intensity and therefore heat up a great deal. The heated layer transmits its heat to the leather, because they are in close thermal contact (touching). | The only thing that matters is the color of the surface, not of the material inside, or the previous surface color. |
70,526,371 | I have this special case. I have an Oracle stored-procedure that doesn't receive IN parameters but returns 4 OUT parameters.
My entity class is this ...
```
@Entity
@Table(name = "TABLE_NAME")
@NamedStoredProcedureQueries({
@NamedStoredProcedureQuery(
name = "MyPackage.spName",
procedureName = "MYPACKAGE.SPNAME",
parameters = {
@StoredProcedureParameter(mode = ParameterMode.OUT, name = "PO_VALUE1", type = String.class),
@StoredProcedureParameter(mode = ParameterMode.OUT, name = "PO_VALUE2", type = String.class),
@StoredProcedureParameter(mode = ParameterMode.OUT, name = "PO_VALUE3", type = String.class),
@StoredProcedureParameter(mode = ParameterMode.OUT, name = "PO_VALUE4", type = String.class)
})
})
public class Tablename {
// omitted properties ...
}
```
My Repository class is this ...
```
@Repository
public interface TableNameRepository extends JpaRepository<TableName, Long> {
@Procedure(name = "MyPackage.spName")
Map<String, Object> spName();
}
```
And I'm calling the stored procedure like this ...
```
Map<String, Object> spNameMap = tableNameRepository.spName();
String value1 = spNameMap.get("PO_VALUE1").toString();
String value2 = spNameMap.get("PO_VALUE2").toString();
// more values ...
```
But it throws this exception ...
>
> Positional parameter [1] is not registered with this procedure call;
>
>
>
```
2021-12-29 18:55:13,630 ERROR [http-nio-3000-exec-1] pe.gob.onpe.wsonpe.service.VersionService: InvalidDataAccessApiUsageException: Positional parameter [1] is not registered with this procedure call; nested exception is java.lang.IllegalArgumentException: Positional parameter [1] is not registered with this procedure call
2021-12-29 18:55:13,633 ERROR [http-nio-3000-exec-1] pe.gob.onpe.wsonpe.service.VersionService: org.springframework.dao.InvalidDataAccessApiUsageException: Positional parameter [1] is not registered with this procedure call; nested exception is java.lang.IllegalArgumentException: Positional parameter [1] is not registered with this procedure call
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:374)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:235)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:145)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at com.sun.proxy.$Proxy123.spFecha(Unknown Source)
at pe.gob.onpe.wsonpe.service.VersionService.verificarVersion(VersionService.java:32)
at pe.gob.onpe.wsonpe.controller.VersionController.userLogin(VersionController.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: Positional parameter [1] is not registered with this procedure call
at org.hibernate.query.procedure.internal.ProcedureParameterMetadata.getQueryParameter(ProcedureParameterMetadata.java:141)
at org.hibernate.procedure.internal.ProcedureCallImpl.getParameterRegistration(ProcedureCallImpl.java:311)
at org.hibernate.procedure.internal.ProcedureOutputsImpl.getOutputParameterValue(ProcedureOutputsImpl.java:53)
at org.hibernate.procedure.internal.ProcedureCallImpl.getOutputParameterValue(ProcedureCallImpl.java:656)
at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.extractOutputParameterValue(StoredProcedureJpaQuery.java:158)
at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.extractOutputValue(StoredProcedureJpaQuery.java:142)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$ProcedureExecution.doExecute(JpaQueryExecution.java:335)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:90)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:155)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:143)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:159)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
... 61 more
```
It seems that JPA is trying to map parameters by **order** instead by **name**. This behaviour is weird, since I'm using parameter names with the annotation **@StoredProcedureParameter**
Please internet, help me with this. | 2021/12/30 | [
"https://Stackoverflow.com/questions/70526371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2805479/"
] | Spring boot JPA starter calls `StoredProcedureJpaQuery` class on initialization.
That class contains a property called `useNamedParameters`.
Calling your stored procedure like this ...
```
@Procedure(name = "MyPackage.spName")
Map<String, Object> spName();
```
means that spring JPA will map your IN and OUT parameters by **position**
To avoid this, you have to use the annotation **@Param** in your repository, like this ...
```
@Procedure(name = "MyPackage.spName")
Map<String, Object> spName(@Param("PO_VALUE1") String value1);
```
using the **@Param** annotation will set the `useNamedParameters` property to **true** and Spring JPA will not start looking by **position** instead by **name**. But, I don't have any IN parameters in my query. So I changed the method to **INOUT** like this ...
```
@StoredProcedureParameter(mode = ParameterMode.INOUT, name = "PO_VALUE1", type = String.class)
```
and passing an empty string when I call the repository ...
```
Map<String, Object> spNameMap = tableNameRepository.spName("");
```
That solution works for me, but I'm open to see a better solution for this. | I can't really answer your *specific* question about how to do these things with JPA and Spring Data, although maybe, you don't have to?
### Using JDBC for this, directly
JPA and Spring Data don't really offer too much value on top of JDBC for ordinary stored procedures. It's just a different way to manually configure the bindings. So, in JDBC, you'd write this:
```java
try (CallableStatement s = c.prepareCall(
"{ call mypackage.spname(?, ?, ?, ?) }"
)) {
s.registerOutParameter(1, Types.VARCHAR);
s.registerOutParameter(2, Types.VARCHAR);
s.registerOutParameter(3, Types.VARCHAR);
s.registerOutParameter(4, Types.VARCHAR);
s.executeUpdate();
String value1 = s.getString(1);
String value2 = s.getString(2);
}
```
I can empathise with the idea that once you use Spring Data JPA and JPA in some areas, you want to use it everywhere. But I just want to remind folks that Spring Data just wraps JDBC, and in the case of stored procedure calls (unless the procedure returns a set of entities), it doesn't really simplify anything, it just consolidates the programming model.
### Using a third party library for stored procedure calls
If using another third party library is an option for you, why not try [jOOQ, which has a code generator](https://blog.jooq.org/the-best-way-to-call-stored-procedures-from-java-with-jooq/) to represent your entire schema, including packages, functions, procedures, UDTs, etc as Java code. With jOOQ, you can just write:
```java
Configuration configuration = // Wrapping your JDBC Connection;
Spname result = Mypackage.spname(configuration);
String value1 = result.getPoValue1();
String value2 = result.getPoValue2();
```
Thanks to code generation, everything is type safe, just like when you use XJC to generate stubs for your WSDL endpoints. When you modify the procedure signature, your Java code stops compiling and you can refactor your call code.
Disclaimer: I work for the company behind jOOQ. |
68,806,043 | I have 2 dataframes:
df1 and df2 ,df1 is used to be a reference or lookups file for df2.It means we need use each row of df1 to match with each row of df2 and then merge df1 into df2 and then out put new df2.
df1:
```
RB BeginDate EndDate Valindex0
0 00 19000100 19811231 45
1 00 19820100 19841299 47
2 00 19850100 20010699 50
3 00 20010700 99999999 39
```
df2:
```
RB IssueDate gs
0 L3 19990201 8
1 00 19820101 G
2 48 19820101 G
3 50 19820101 G
4 50 19820101 G
5 00 19860101 G
6 52 19820101 G
7 53 19820101 G
8 00 19500201 G
```
how to merge this 2 dataframes base on condition:
```
if df1['BeginDate'] <= df2['IssueDate'] <= df1['EndDate'] and df1['RB']==df2['RB']:
merge the value of df1['Valindex0'] to df2
```
Notice the final out put is merge df1 into df2,because df1 is just like a reference or lookup file for df2.It means we need use each row of df1 to match with each row of df2,then output new df2
The output should looks like:
df2:
```
RB IssueDate gs Valindex0
0 L3 19990201 8 None
1 00 19820101 G 47 # df2['RB']==df1['RB'] and df2['IssueDate'] between df1['BeginDate'] and df1['EndDate'] of this row
2 48 19820101 G None
3 50 19820101 G None
4 50 19820101 G None
5 00 19860101 G 50
6 52 19820101 G None
7 53 19820101 G None
8 00 19500201 G 45
```
I know one method to do this,but it is extremally slow, especially when the length of d1 is big:
```
conditions = []
for index, row in df1.iterrows():
conditions.append((df2['IssueDate']>= df1['BeginDate']) &
(df2['IssueDate']<= df1['BeginDate'])&
(df2['RB']==df1['RB']))
df2['Valindex0'] = np.select(conditions, df1['Valindex0'], default=None)
```
Any faster solution? | 2021/08/16 | [
"https://Stackoverflow.com/questions/68806043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7984318/"
] | Use [IntervalIndex](https://pandas.pydata.org/docs/reference/api/pandas.IntervalIndex.html) -
```
idx = pd.IntervalIndex.from_arrays(df1['BeginDate'],df1['EndDate'],closed='both')
for x in df1['RB'].unique():
mask = df2['RB']==x
df2.loc[mask, 'Valindex0'] = df1.loc[idx.get_indexer(df2.loc[mask, 'IssueDate']), 'Valindex0'].values
```
**Output**
```
RB IssueDate gs Valindex0
0 L3 19990201 8 NaN
1 00 19820101 G 47.0
2 48 19820101 G NaN
3 50 19820101 G NaN
4 50 19820101 G NaN
5 00 19860101 G 50.0
6 52 19820101 G NaN
7 53 19820101 G NaN
8 00 19500201 G 45.0
``` | If you dont care about the ordering of the records or index you could do this
```
df1 = pd.read_clipboard()
df2 = pd.read_clipboard()
# pandas wants to cast this column as int
df1['RB'] = '00'
new_df = df2.merge(df1, how='outer', on='RB')
mask = ((new_df['BeginDate'] <= new_df['IssueDate']) & (new_df['IssueDate'] <= new_df['EndDate'])
)| new_df['Valindex0'].isnull()
new_df[['RB','IssueDate', 'gs', 'Valindex0']][mask]
```
The idea is to do a full outer join first and then filter the dataset after.
Results:
```
RB IssueDate gs Valindex0
0 L3 19990201 8 NaN
2 00 19820101 G 47.0
7 00 19860101 G 50.0
9 00 19500201 G 45.0
13 48 19820101 G NaN
14 50 19820101 G NaN
15 50 19820101 G NaN
16 52 19820101 G NaN
17 53 19820101 G NaN
``` |
5,458,102 | I want to show `UIImagePickerController` in fullscreen mode for iPad2.
`presentModalViewController:` appears not work for me.
It show the frame with capture button but not show video preview of what is being capture?
Anyone got same problem before and now how to solve?
Thanks | 2011/03/28 | [
"https://Stackoverflow.com/questions/5458102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192800/"
] | The *recommended* practice is not do something like this. Try to redesign so that the background image isn't/doesn't need to be of fixed height and the text doesn't need to be limited to exactly three lines. If this is some kind of requirement imposed on you by your boss/customer, you'll need to talk with them and explain, that this isn't something one can or should do in HTML/CSS.
Keep in mind, that not only the width of the characters will be different in each browser resulting in different wrapping, but browsers will display the text **lines** in different heights, too, so it can be that your element can't contain three lines.
If you have no other choice, consider using `overflow: hidden` on the fixed-size element, however this will most likely lead to cut off letters and/or words.
---
**EDIT re comment:**
I don't think the available space would variate between browsers. If you were using relative units (`em`, `%`), then maybe there would be rounding differences of one pixel max. However you are using pixels, which should be identical in all current browsers (in Standards Mode).
Anyway I'm not saying you should restrict the amount of text you want to display, just give the text some space to "breath" and don't give the element a fixed height in pixels. Instead:
* Set a `line-height` (for example `1.25`) and a `min-height` three times the amount (here `3.75em`).
* Use your best estimate to limit the text you want to put in there to three lines.
* Add some JavaScript that shortens the text, in case it does happen to go over three lines.
* Adjust your layout (including a flexible background for that element), so it can survive both a few pixels difference due to different browser's (and more importantly the user's preferred) font size **and** can survive an additional line of text just in the seldom case that you mis-estimated the text length and JavaScript isn't available. | Make sure you are using a good CSS reset as most browsers have different defaults for various tags. Assuming your reset is good, you can use browser specific CSS to account for differences in rendering. |
32,166,562 | I saw a couple of days ago [this tutorial on youtube](https://www.youtube.com/watch?v=hJBYojK7DO4).
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
```
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
```
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that `$update = file_get_contents('php://input');` is the right way, to be used before `$update = file_get_contents($website."/getupdates");`. My question how can I use `php://input` to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com". | 2015/08/23 | [
"https://Stackoverflow.com/questions/32166562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5257071/"
] | If you use selfsigned ssl you have to point to the ssl path ,,
use the ssh to run this command after filling it with your real data ,,
```
curl -F "url=https://example.com/myscript.php" -F "certificate=@/etc/apache2/ssl/apache.crt" https://api.telegram.org/bot<SECRETTOKEN>/setWebhook
``` | After change to WebHook method, you need to put as follows, since now we are going to handle one message at time. For me works perfectly.
instead
```
$chatId = $updateArray["result"][0]["message"]["chat"]["id"];
```
to
```
$chatID = $update["message"]["chat"]["id"];
``` |
32,166,562 | I saw a couple of days ago [this tutorial on youtube](https://www.youtube.com/watch?v=hJBYojK7DO4).
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
```
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
```
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that `$update = file_get_contents('php://input');` is the right way, to be used before `$update = file_get_contents($website."/getupdates");`. My question how can I use `php://input` to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com". | 2015/08/23 | [
"https://Stackoverflow.com/questions/32166562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5257071/"
] | If you use selfsigned ssl you have to point to the ssl path ,,
use the ssh to run this command after filling it with your real data ,,
```
curl -F "url=https://example.com/myscript.php" -F "certificate=@/etc/apache2/ssl/apache.crt" https://api.telegram.org/bot<SECRETTOKEN>/setWebhook
``` | Sorry for digging up this old question so enthusiastically, I had exactly the same question as you.
I think actually the answer may be easier yet less satisfying as we hoped: I don't think it's possible to get a list of previous messages to the bot while using the webhook.
Namely: what this does, is run the PHP script directly as soon as the bot receives a message. Nothing is stored in an accessible database, hence no updateArray is returned.
I came across [this example](https://core.telegram.org/bots/samples/hellobot), which shows how php://input works. I guess the solution to display a list of messages would be, let the php script store the message in a database everytime a message is 'forwarded' via the webhook.
If anyone found something else: I'm very interested. |
32,166,562 | I saw a couple of days ago [this tutorial on youtube](https://www.youtube.com/watch?v=hJBYojK7DO4).
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
```
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
```
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that `$update = file_get_contents('php://input');` is the right way, to be used before `$update = file_get_contents($website."/getupdates");`. My question how can I use `php://input` to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com". | 2015/08/23 | [
"https://Stackoverflow.com/questions/32166562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5257071/"
] | If you use selfsigned ssl you have to point to the ssl path ,,
use the ssh to run this command after filling it with your real data ,,
```
curl -F "url=https://example.com/myscript.php" -F "certificate=@/etc/apache2/ssl/apache.crt" https://api.telegram.org/bot<SECRETTOKEN>/setWebhook
``` | As per my understanding from your code snippet above, you need to use php://input within double quotes instead of single quotes. In php, we are having bing difference in this use case. |
32,166,562 | I saw a couple of days ago [this tutorial on youtube](https://www.youtube.com/watch?v=hJBYojK7DO4).
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
```
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
```
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that `$update = file_get_contents('php://input');` is the right way, to be used before `$update = file_get_contents($website."/getupdates");`. My question how can I use `php://input` to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com". | 2015/08/23 | [
"https://Stackoverflow.com/questions/32166562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5257071/"
] | If you use selfsigned ssl you have to point to the ssl path ,,
use the ssh to run this command after filling it with your real data ,,
```
curl -F "url=https://example.com/myscript.php" -F "certificate=@/etc/apache2/ssl/apache.crt" https://api.telegram.org/bot<SECRETTOKEN>/setWebhook
``` | this is the answer for all of your problems.
follow this step after you got a secret token for your bot:
1. create file in your website <https://yourdomain.com/secret-folder/index.php>
create your php file like this :
```
<?php
$website = 'https://api.telegram.org/bot123456789:1234567890ABCDEF1234567890ABCDEF123/';
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (isset($update["message"])){
$chatID = $update["message"]["chat"]["id"];
$text = $update["message"]["text"];
if ( $text == '/start' ) {
// send welcome message
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=Welcome to my bot");
}else{
// send another message or do your logic (up to you)
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=some text here");
}
}
?>
```
1. Set Your Webhook from this bot [@set\_webhookbot](https://t.me/set_webhookbot)
2. choose command or type ' ست وب هوک '
3. reply with your secret bot token ex: ' 123456789:1234567890ABCDEF1234567890ABCDEF123 '
4. reply with your webhook address '<https://yourdomain.com/secret-folder/index.php>'
5. reply with /setwebhook
if you follow step by step its will work.
enjoy it !! |
32,166,562 | I saw a couple of days ago [this tutorial on youtube](https://www.youtube.com/watch?v=hJBYojK7DO4).
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
```
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
```
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that `$update = file_get_contents('php://input');` is the right way, to be used before `$update = file_get_contents($website."/getupdates");`. My question how can I use `php://input` to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com". | 2015/08/23 | [
"https://Stackoverflow.com/questions/32166562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5257071/"
] | After change to WebHook method, you need to put as follows, since now we are going to handle one message at time. For me works perfectly.
instead
```
$chatId = $updateArray["result"][0]["message"]["chat"]["id"];
```
to
```
$chatID = $update["message"]["chat"]["id"];
``` | Sorry for digging up this old question so enthusiastically, I had exactly the same question as you.
I think actually the answer may be easier yet less satisfying as we hoped: I don't think it's possible to get a list of previous messages to the bot while using the webhook.
Namely: what this does, is run the PHP script directly as soon as the bot receives a message. Nothing is stored in an accessible database, hence no updateArray is returned.
I came across [this example](https://core.telegram.org/bots/samples/hellobot), which shows how php://input works. I guess the solution to display a list of messages would be, let the php script store the message in a database everytime a message is 'forwarded' via the webhook.
If anyone found something else: I'm very interested. |
32,166,562 | I saw a couple of days ago [this tutorial on youtube](https://www.youtube.com/watch?v=hJBYojK7DO4).
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
```
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
```
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that `$update = file_get_contents('php://input');` is the right way, to be used before `$update = file_get_contents($website."/getupdates");`. My question how can I use `php://input` to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com". | 2015/08/23 | [
"https://Stackoverflow.com/questions/32166562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5257071/"
] | After change to WebHook method, you need to put as follows, since now we are going to handle one message at time. For me works perfectly.
instead
```
$chatId = $updateArray["result"][0]["message"]["chat"]["id"];
```
to
```
$chatID = $update["message"]["chat"]["id"];
``` | As per my understanding from your code snippet above, you need to use php://input within double quotes instead of single quotes. In php, we are having bing difference in this use case. |
32,166,562 | I saw a couple of days ago [this tutorial on youtube](https://www.youtube.com/watch?v=hJBYojK7DO4).
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
```
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
```
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that `$update = file_get_contents('php://input');` is the right way, to be used before `$update = file_get_contents($website."/getupdates");`. My question how can I use `php://input` to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com". | 2015/08/23 | [
"https://Stackoverflow.com/questions/32166562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5257071/"
] | this is the answer for all of your problems.
follow this step after you got a secret token for your bot:
1. create file in your website <https://yourdomain.com/secret-folder/index.php>
create your php file like this :
```
<?php
$website = 'https://api.telegram.org/bot123456789:1234567890ABCDEF1234567890ABCDEF123/';
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (isset($update["message"])){
$chatID = $update["message"]["chat"]["id"];
$text = $update["message"]["text"];
if ( $text == '/start' ) {
// send welcome message
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=Welcome to my bot");
}else{
// send another message or do your logic (up to you)
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=some text here");
}
}
?>
```
1. Set Your Webhook from this bot [@set\_webhookbot](https://t.me/set_webhookbot)
2. choose command or type ' ست وب هوک '
3. reply with your secret bot token ex: ' 123456789:1234567890ABCDEF1234567890ABCDEF123 '
4. reply with your webhook address '<https://yourdomain.com/secret-folder/index.php>'
5. reply with /setwebhook
if you follow step by step its will work.
enjoy it !! | Sorry for digging up this old question so enthusiastically, I had exactly the same question as you.
I think actually the answer may be easier yet less satisfying as we hoped: I don't think it's possible to get a list of previous messages to the bot while using the webhook.
Namely: what this does, is run the PHP script directly as soon as the bot receives a message. Nothing is stored in an accessible database, hence no updateArray is returned.
I came across [this example](https://core.telegram.org/bots/samples/hellobot), which shows how php://input works. I guess the solution to display a list of messages would be, let the php script store the message in a database everytime a message is 'forwarded' via the webhook.
If anyone found something else: I'm very interested. |
32,166,562 | I saw a couple of days ago [this tutorial on youtube](https://www.youtube.com/watch?v=hJBYojK7DO4).
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
```
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
```
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that `$update = file_get_contents('php://input');` is the right way, to be used before `$update = file_get_contents($website."/getupdates");`. My question how can I use `php://input` to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com". | 2015/08/23 | [
"https://Stackoverflow.com/questions/32166562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5257071/"
] | this is the answer for all of your problems.
follow this step after you got a secret token for your bot:
1. create file in your website <https://yourdomain.com/secret-folder/index.php>
create your php file like this :
```
<?php
$website = 'https://api.telegram.org/bot123456789:1234567890ABCDEF1234567890ABCDEF123/';
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (isset($update["message"])){
$chatID = $update["message"]["chat"]["id"];
$text = $update["message"]["text"];
if ( $text == '/start' ) {
// send welcome message
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=Welcome to my bot");
}else{
// send another message or do your logic (up to you)
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=some text here");
}
}
?>
```
1. Set Your Webhook from this bot [@set\_webhookbot](https://t.me/set_webhookbot)
2. choose command or type ' ست وب هوک '
3. reply with your secret bot token ex: ' 123456789:1234567890ABCDEF1234567890ABCDEF123 '
4. reply with your webhook address '<https://yourdomain.com/secret-folder/index.php>'
5. reply with /setwebhook
if you follow step by step its will work.
enjoy it !! | As per my understanding from your code snippet above, you need to use php://input within double quotes instead of single quotes. In php, we are having bing difference in this use case. |
102,430 | I have a directory with multiple img files and some of them are identical but they all have different names. I need to remove duplicates but with no external tools only with a `bash` script. I'm a beginner in Linux. I tried nested for loop to compare `md5` sums and depending on the result remove but something is wrong with the syntax and it doesn't work. any help?
what I've tried is...
```
for i in directory_path; do
sum1='find $i -type f -iname "*.jpg" -exec md5sum '{}' \;'
for j in directory_path; do
sum2='find $j -type f -iname "*.jpg" -exec md5sum '{}' \;'
if test $sum1=$sum2 ; then rm $j ; fi
done
done
```
I get: `test: too many arguments` | 2013/11/24 | [
"https://unix.stackexchange.com/questions/102430",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/53012/"
] | There are quite a few problems in your script.
* First, in order to assign the *result* of a command to a variable you need to enclose it either in backtics (``command``) or, preferably, `$(command)`. You have it in single quotes (`'command'`) which instead of assigning the result of your command to your variable, assigns the command itself as a string. Therefore, your `test` is actually:
```
$ echo "test $sum1=$sum2"
test find $i -type f -iname "*.jpg" -exec md5sum {} \;=find $j -type f -iname "*.jpg" -exec md5sum {} \;
```
* The next issue is that the command `md5sum` returns more than just the hash:
```
$ md5sum /etc/fstab
46f065563c9e88143fa6fb4d3e42a252 /etc/fstab
```
You only want to compare the first field, so you should parse the `md5sum` output by passing it through a command that only prints the first field:
```
find $i -type f -iname "*.png" -exec md5sum '{}' \; | cut -f 1 -d ' '
```
or
```
find $i -type f -iname "*.png" -exec md5sum '{}' \; | awk '{print $1}'
```
* Also, the `find` command will return many matches, not just one and each of those matches will be duplicated by the second `find`. This means that at some point you will be comparing the same file to itself, the md5sum will be identical and you will end up deleting *all* your files (I ran this on a test dir containing `a.jpg` and `b.jpg`):
```
for i in $(find . -iname "*.jpg"); do
for j in $(find . -iname "*.jpg"); do
echo "i is: $i and j is: $j"
done
done
i is: ./a.jpg and j is: ./a.jpg ## BAD, will delete a.jpg
i is: ./a.jpg and j is: ./b.jpg
i is: ./b.jpg and j is: ./a.jpg
i is: ./b.jpg and j is: ./b.jpg ## BAD will delete b.jpg
```
* You don't want to run `for i in directory_path` unless you are passing an array of directories. If all these files are in the same directory, you want to run `for i in $(find directory_path -iname "*.jpg"`) to go through all the files.
* It is [a bad idea](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29) to use `for` loops with the output of find. You should use `while` loops or [globbing](http://en.wikipedia.org/wiki/Glob_%28programming%29):
```
find . -iname "*.jpg" | while read i; do [...] ; done
```
or, if all your files re in the same directory:
```
for i in *jpg; do [...]; done
```
Depending on your shell and the options you have set, you can use globbing even for files in subdirectories but let's not get into that here.
* Finally, you should also quote your variables else directory paths with spaces will break your script.
File names can contain spaces, new lines, backslashes and other weird characters, to deal with those correctly in a `while` loop you'll need to add some more options. What you want to write is something like:
```
find dir_path -type f -iname "*.jpg" -print0 | while IFS= read -r -d '' i; do
find dir_path -type f -iname "*.jpg" -print0 | while IFS= read -r -d '' j; do
if [ "$i" != "$j" ]
then
sum1=$(md5sum "$i" | cut -f 1 -d ' ' )
sum2=$(md5sum "$j" | cut -f 1 -d ' ' )
[ "$sum1" = "$sum2" ] && rm "$j"
fi
done
done
```
An even simpler way would be:
```
find directory_path -name "*.jpg" -exec md5sum '{}' + |
perl -ane '$k{$F[0]}++; system("rm $F[1]") if $k{$F[0]}>1'
```
A better version that can deal with spaces in file names:
```
find directory_path -name "*.jpg" -exec md5sum '{}' + |
perl -ane '$k{$F[0]}++; system("rm \"@F[1 .. $#F]\"") if $k{$F[0]}>1'
```
This little Perl script will run through the results of the `find` command (i.e. the md5sum and file name). The `-a` option for `perl` splits input lines at whitespace and saves them in the `F` array, so `$F[0]` will be the md5sum and `$F[1]` the file name. The md5sum is saved in the hash `k` and the script checks if the hash has already been seen (`if $k{$F[0]}>1`) and deletes the file if it has (`system("rm $F[1]")`).
---
While that will work, it will be very slow for large image collections and you cannot choose which files to keep. There are many programs that handle this in a more elegant way including:
* [`fdupes`](http://code.google.com/p/fdupes/)
* [`fslint`](http://www.pixelbeat.org/fslint/)
* Various other options listed [here](https://askubuntu.com/a/118389/85695). | There is a nifty program called `fdupes` that simplifies the whole process and prompts the user for deleting duplicates. I think it is worth checking:
```
$ fdupes --delete DIRECTORY_WITH_DUPLICATES
[1] DIRECTORY_WITH_DUPLICATES/package-0.1-linux.tar.gz
[2] DIRECTORY_WITH_DUPLICATES/package-0.1-linux.tar.gz.1
Set 1 of 1, preserve files [1 - 2, all]: 1
[+] DIRECTORY_WITH_DUPLICATES/package-0.1-linux.tar.gz
[-] DIRECTORY_WITH_DUPLICATES/package-0.1-linux.tar.gz.1
```
Basically, it prompted me for which file to **keep**, I typed **1**, and it removed the second.
Other interesting options are:
```
-r --recurse
for every directory given follow subdirectories encountered within
-N --noprompt
when used together with --delete, preserve the first file in each set of duplicates and delete the others without prompting the user
```
From your example, you probably want to run it as:
```
fdupes --recurse --delete --noprompt DIRECTORY_WITH_DUPLICATES
```
See `man fdupes` for all options available. |
563,914 | Say I am going to write down the steps of some calculations to get the final value of $s$ from an equation like this:
$$ s = s\_0 + \frac12 gt^2. $$
Let us say $s\_0 = 20\,\mathrm{m}$, $g = 10\,\mathrm{ms^{-2}}$, and $t = 2\,\mathrm{s}$. What is the right way to write down the units in every step so that all the formula, LHS, and RHS are always consistent in terms of units?
### Alternative 1
\begin{align\*}
s &= s\_0 + \frac12gt^2 \\
&= 20\,\mathrm{m} + \frac{1}{2} \cdot 10\,\mathrm{m\,s^{-2}} \cdot (2\,\mathrm{s})^2 \\
&= 20\,\mathrm{m} + 20\,\mathrm{m} \\
&= 40\,\mathrm{m}.
\end{align\*}
### Alternative 2
\begin{align\*}
s &= s\_0 + \frac12gt^2 \\
&= 20\,\mathrm{m} + \frac{1}{2} \cdot 10\,\mathrm{m\,s^{-2}} \cdot 2^2\,\mathrm{s^2} \\
&= 20\,\mathrm{m} + 20\,\mathrm{m} \\
&= 40\,\mathrm{m}.
\end{align\*}
### Alternative 2
\begin{align\*}
s &= s\_0 + \frac12gt^2 \\
&= 20\,\mathrm{m} + \left(\frac{1}{2} \cdot 10 \cdot 2^2\right)\,\mathrm{m} \\
&= 20\,\mathrm{m} + 20\,\mathrm{m} \\
&= 40\,\mathrm{m}.
\end{align\*}
### Alternate 3
\begin{align\*}
s &= s\_0 + \frac12gt^2 \\
&= \left(20 + \frac{1}{2} \cdot 10 \cdot 2^2\right)\,\mathrm{m} \\
&= 20\,\mathrm{m} + 20\,\mathrm{m} \\
&= 40\,\mathrm{m}.
\end{align\*}
Are all alternatives correct? Is there any alternative above or another alternative that is widely used in literature? | 2020/07/05 | [
"https://physics.stackexchange.com/questions/563914",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/7378/"
] | There's no *right* way. But I use and recommend Alternative #1 in the class I teach. It keeps the value with the unit which makes it easier to go back and find mistakes.
**Addendum**
Another thing that I try to drill into them with only modest success is to *not* do "algebra-by-cross-out", but rather to write a complete new line for every step. Again, doing that improves readability and the finding of mistakes. I absorbed that habit myself after a memorial service for [Henry Primakoff](https://physicstoday.scitation.org/doi/10.1063/1.2915405) at which framed pages of his notebooks were on display ... colorful visual delights in themselves. It was said that he never skipped a step when doing calculations. If it was good enough for Primakoff it was good enough for me. I've been doing it ever since.
I'm pretty sure this disease is spread by well-meaning but misguided high school teachers. High school teachers listen up: don't do that. | I perfectly agree with garyp: There is no right or wrong way to put the units into the equations. However, in my experience people tend to make mistakes, if they rewrite the equations. That's why I recommend
1. to convert all units to the standard SI units (no prefixes like nano or kilo),
2. do the insertion and calculation of the numbers as a side mark, where we do not include the units, and
3. finally just writing the final result with the SI unit as the solution.
Hence, your calculation would read
$$
s = s\_0 + \frac{1}{2}g t ^2 = \fbox{40m}
$$
and the side mark would read
$$
\left(20 + \frac{1}{2} \cdot 10 \cdot 2^2\right)
= 20 + 20 = 40.
$$ |
100,747 | Why the probability of density is higher in the area that is closer to the nucleus? I'm a high school student. I don't know much about wave functions. | 2014/02/25 | [
"https://physics.stackexchange.com/questions/100747",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/40003/"
] | First of all you have to consider that there's an electric force (Coulomb) between nucleus and electron, so, from a classical point of view it seems reasonable that electron "wants" to stay as closer as possible to the nucleus (they respectively attract). Now it's clearly impossible that electrons could reach nucleus, from an intuitive view points you can see it if you apply the Uncertainty Principle: if the position of electron is precisely define (at the origin if we put the nucleus in that position), electron must have infinite kinetic energy and this is obviously impossible. So electron reach the equilibrium position near the nucleus. Despite that it's clear that from a merely classical discussion electron is attract by the positive charge of nucleus so, as a consequence in every theory (QM too), the probability of density is higher near nucleus than far away from it. | The short answer to your question is that in "nature;" energy, forces, and particles, operate in such a way that the energy or force needed to reach some kind of "stability" (equilibrium), is **minimized.** In the case of an electron, its "ground state" is the most stable, so the probability of "finding" it there, is very high (if not the highest). |
100,747 | Why the probability of density is higher in the area that is closer to the nucleus? I'm a high school student. I don't know much about wave functions. | 2014/02/25 | [
"https://physics.stackexchange.com/questions/100747",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/40003/"
] | First of all you have to consider that there's an electric force (Coulomb) between nucleus and electron, so, from a classical point of view it seems reasonable that electron "wants" to stay as closer as possible to the nucleus (they respectively attract). Now it's clearly impossible that electrons could reach nucleus, from an intuitive view points you can see it if you apply the Uncertainty Principle: if the position of electron is precisely define (at the origin if we put the nucleus in that position), electron must have infinite kinetic energy and this is obviously impossible. So electron reach the equilibrium position near the nucleus. Despite that it's clear that from a merely classical discussion electron is attract by the positive charge of nucleus so, as a consequence in every theory (QM too), the probability of density is higher near nucleus than far away from it. | For the 1s orbital the highest probability density exists *inside* the nucleus. Welcome to the subatomic world!
But there are many other orbitals where the density inside or near the nucleus is low. Look e.g. at <http://www.chemistry.mcmaster.ca/esam/Chapter_3/section_2.html> for details (note that a standard “*hydrogen* atom” mantra doesn’t signify much of restriction and in other atoms orbitals are not very different. |
11,521,001 | Iam using a list item in my application. Iam using the adapter:
```
adapter adapter = new ArrayAdapter<Settingsmodel>(this,
android.R.layout.simple_list_item_checked, listItems);
```
In that i want to check the tick mark of the selected list item manually. I searched a lot. Could'nt find a way to do it. Please help me if anybody knows. | 2012/07/17 | [
"https://Stackoverflow.com/questions/11521001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1498488/"
] | You can use a list and add a tag every time you clicked on checkbox in your CustomAdapter.
```
CheckBox chkbox= (CheckBox)view.findViewById(R.id.checkBox1);
chkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
isSelected.set(position, isChecked);
}
});
Where isSelected is private List<Boolean> isSelected= new ArrayList<Boolean>();
```
You can do all your work inside following while loop by analysing the isSelected list
```
while(isSelected.contains(true))
{
int pos=isSelected.indexOf(true);
isSelected.set(pos, false);
sendMail.add(listMap.get(pos).get("email"));
// if(listMap.get(pos).get("email_2")!=null){
// sendMail.add(listMap.get(pos).get("email_2"));
// }
// if(listMap.get(pos).get("email_3")!=null){
// sendMail.add(listMap.get(pos).get("email_3"));
// }
}
``` | create your own Adapter....
```
public class SettingsmodelAdapter extends ArrayAdapter<Settingsmodel>
{
.....
public final View getView(final int position, final View convertView, final ViewGroup parent)
{
final View row = super.getView(position, convertView, parent);
final CheckBox checkBox = (CheckBox) row.findViewById(android.R.id.checkbox);
checkBox.setChecked(your value);
.....
}
.....
}
``` |
4,836 | I came up with this rather amusing and bizarre stalemate where Black stalemates itself by self-smothering.
```
[FEN "8/8/8/8/8/3p4/pp6/krb1K3 b - - 0 1"]
1...d2+?? 2. Kd1
```
The peculiar feature of this stalemate is that Black is unable to move not because moving a piece would put its king into check, but moving a piece would require it to capture its own piece, which is disallowed. This is an example of a **single self-smothered stalemate**.
The question is, is it possible to have a **double self-smothered mate**, such that both sides do not have any moves at all because the moves would require capturing of the side's own pieces?
One possibility suggested by the user supercat is the following -
```
[FEN "KN1b4/RPpPp3/P1P5/4P3/8/3p1p1p/3PpPpr/4B1nk w - - 0 1"]
1. e6
```
And both sides are stalemated. However, this position cannot occur in practice, because you cannot have a Black bishop trapped on d8 with the c7 or e7 pawns still on their original squares. | 2014/02/27 | [
"https://chess.stackexchange.com/questions/4836",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/2429/"
] | I think I found a double-self-smothered-stalemate that could occur via sequence of legal moves from the normal starting position.
```
[FEN "5bnk/4ppbp/4P2p/5P1P/p1p5/P2p4/PBPP4/KNB5 w - - 0 1"]
1. c3 f6
```
Each player has seven pawns and two dark-square bishops, so one pawn from each player must have been promoted. Once White's b pawn has captured to a3 and Black's g pawn has captured to h6, White's g pawn and Black's b pawn can promote without any other pawn having to leave its file. I haven't worked out the exact "game", but I see no reason to believe it wouldn't be relatively trivial, particularly if one isn't worried about achieving the position with a minimal number of moves. | In response to an your original question about whether anything interesting has been written about stalemates, it may be worth mentioning that puzzle creator Sam Lloyd is often credited with two interesting stalemate "games" (though see game 3679 at <http://www.chesshistory.com/winter/winter08.html> for information about that attribution); in the first, White stalemates Black on the tenth move, after having captured six black pieces:
```
[FEN ""]
1.e3 a5 2.Qh5 Ra6 3.Qxa5 h5 4.Qxc7 Rah6 5.h4 f6 6.Qxd7+ Kf7 7.Qxb7 Qd3 8.Qxb8 Qh7 9.Qxc8 Kg6 10.Qe6
```
In the second, White is stalemated after Black's twelfth move, while all 32 chessmen are on the board:
```
[FEN ""]
1.d4 d6 2.Qd2 e5 3.a4 e4 4.Qf4 f5 5.h3 Be7 6.Qh2 Be6 7.Ra3 c5 8.Rg3 Qa5+ 9.Nd2 Bh4 10.f3 Bb3 11.d5 e3 12.c4 f4
```
In both of Sam Lloyd's positions, one side is stalemated while the other has many moves available. For both sides to be stalemated would probably take significantly more moves, and for both sides to be smother-stalemated would take more yet. |
4,836 | I came up with this rather amusing and bizarre stalemate where Black stalemates itself by self-smothering.
```
[FEN "8/8/8/8/8/3p4/pp6/krb1K3 b - - 0 1"]
1...d2+?? 2. Kd1
```
The peculiar feature of this stalemate is that Black is unable to move not because moving a piece would put its king into check, but moving a piece would require it to capture its own piece, which is disallowed. This is an example of a **single self-smothered stalemate**.
The question is, is it possible to have a **double self-smothered mate**, such that both sides do not have any moves at all because the moves would require capturing of the side's own pieces?
One possibility suggested by the user supercat is the following -
```
[FEN "KN1b4/RPpPp3/P1P5/4P3/8/3p1p1p/3PpPpr/4B1nk w - - 0 1"]
1. e6
```
And both sides are stalemated. However, this position cannot occur in practice, because you cannot have a Black bishop trapped on d8 with the c7 or e7 pawns still on their original squares. | 2014/02/27 | [
"https://chess.stackexchange.com/questions/4836",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/2429/"
] | I think I found a double-self-smothered-stalemate that could occur via sequence of legal moves from the normal starting position.
```
[FEN "5bnk/4ppbp/4P2p/5P1P/p1p5/P2p4/PBPP4/KNB5 w - - 0 1"]
1. c3 f6
```
Each player has seven pawns and two dark-square bishops, so one pawn from each player must have been promoted. Once White's b pawn has captured to a3 and Black's g pawn has captured to h6, White's g pawn and Black's b pawn can promote without any other pawn having to leave its file. I haven't worked out the exact "game", but I see no reason to believe it wouldn't be relatively trivial, particularly if one isn't worried about achieving the position with a minimal number of moves. | Here's a simpler mutual smothered stalemate
(9 men on a side, no promoted pieces):
```
[Title "Mutual smothered stalemate"]
[fen "5brk/4p1pb/4P1p1/6P1/1p6/1P1p4/BP1P4/KRB5 w - - 0 1"]
``` |
4,836 | I came up with this rather amusing and bizarre stalemate where Black stalemates itself by self-smothering.
```
[FEN "8/8/8/8/8/3p4/pp6/krb1K3 b - - 0 1"]
1...d2+?? 2. Kd1
```
The peculiar feature of this stalemate is that Black is unable to move not because moving a piece would put its king into check, but moving a piece would require it to capture its own piece, which is disallowed. This is an example of a **single self-smothered stalemate**.
The question is, is it possible to have a **double self-smothered mate**, such that both sides do not have any moves at all because the moves would require capturing of the side's own pieces?
One possibility suggested by the user supercat is the following -
```
[FEN "KN1b4/RPpPp3/P1P5/4P3/8/3p1p1p/3PpPpr/4B1nk w - - 0 1"]
1. e6
```
And both sides are stalemated. However, this position cannot occur in practice, because you cannot have a Black bishop trapped on d8 with the c7 or e7 pawns still on their original squares. | 2014/02/27 | [
"https://chess.stackexchange.com/questions/4836",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/2429/"
] | I think I found a double-self-smothered-stalemate that could occur via sequence of legal moves from the normal starting position.
```
[FEN "5bnk/4ppbp/4P2p/5P1P/p1p5/P2p4/PBPP4/KNB5 w - - 0 1"]
1. c3 f6
```
Each player has seven pawns and two dark-square bishops, so one pawn from each player must have been promoted. Once White's b pawn has captured to a3 and Black's g pawn has captured to h6, White's g pawn and Black's b pawn can promote without any other pawn having to leave its file. I haven't worked out the exact "game", but I see no reason to believe it wouldn't be relatively trivial, particularly if one isn't worried about achieving the position with a minimal number of moves. | Reduce number of units from Noam's record of 18 to a new record of 15.
(8+7 units, no promoted units necessarily on the board, pawn captures all achievable):
```
[Title "Minimal mutual smothered stalemate"]
[fen "5brk/4p1pb/4P1p1/6P1/6PB/6PK/6PP/8 w - - 0 1"]
```
Is this the best possible?
It's interesting that this solution is asymmetric. If you wrap both kings with pawns on opposite flanks, it requires 16 units.
EDIT: Inspired by a comment, I want to show more deeply that the position is legal. And if fact prove that, despite appearances *at least one promotion took place in the history of the game*. Assume first that no promotions happened.
White c-h pawns could have reached their files with 8 captures, which is OK since Black has 7 units left.
What about the Black pawns? All but 1 Black unit were captured by White c-h pawns. BfP ("Black f pawn") captured to g6, as this pawn couldn't have come from h7. Most efficient if BhP captured to g file, to be captured in its turn.
White pawns made 1,2,2,3 captures on files d,e,f,g respectively. So Black b,c,d pawns would have to make a total of 5 captures to get far enough (to d & e files). Together with the 2 captures onto the g file, Black made at least 7 pawn captures. This is making the most efficient assumption that BaP was the one missing Black unit not captured by a WP.
Black made 7 pawn captures, and White has 8 units remaining, so at first it looks OK. But none of these captures were on files a or b, where WaP & WbP began. One of those two WPs must have also got hit by a BP, but how? The only capture possible is of BaP.
Therefore, we have proved our original assumption wrong: at least one promotion happened in the course of the game. That might have been White or Black. E.g. WbP promotes on b1, or e.g. BbP captures only once, and promotes on c1.
---
As per @Laska"s given permission in the comments, here is a 35-move (optimal?) proof game created by @Rewan Demontay, of their position. The intention of it is that it was made to prove their retrograde analysis of the game history of their position.
```
[FEN ""]
1. Nc3 h5 2. Ne4 h4 3. Ng3 hxg3 4. fxg3 Nc6 5. Kf2 a5 6. Kf3 a4 7. Kg4 Nh6+ 8. Kh3 Ne5 9. b3 Nf3 10. exf3 Rg8 11. Bd3 Ng4 12. fxg4 d5 13. Be4 dxe4 14. Qf3 e3 15. dxe3 Kd7 16. Qxb7 Ke6 17. Ne2 Kf6 18. Bb2+ Kg6 19. Bf6 Kh7 20. Bh4 Kh8 21. Nf4 Bf5 22. Rhf1 Bh7 23. Ng6+ fxg6 24. Rad1 c6 25. Rd5 cxd5 26. c4 axb3 27. cxd5 bxa2 28. Rf4 Qd6 29. Qb5 Qe6 30. dxe6 a1=Q 31. Qc5 Qa4 32. Qd5 Qxf4 33. exf4 Ra5 34. Qg5 Rxg5 35. fxg5
```
As you can see, a **promotion** is **needed** as @Laska **rightfully claimed.**
EDIT: Thanks @Rewan. And here is a candidate *maximal* mutually smothered checkmate:
```
[Title "Maximal mutual smothered stalemate"]
[fen "4brkq/3p1brb/3Pp1p1/4P1P1/1p1p4/1P1Pp3/BRB1P3/QKRB4 w - - 0 1"]
```
Legal position with 26 pieces: 6 minor pieces captured & 4 promoted bishops. Some flexibility in the diagram: in keeping with the maximality I've chosen major pieces rather than knights in the back row. Also, kept the smothered kings out of the corners.
Note the pawn moves d2-d3 and e7-e6 unlock the two cages.
Here is a proof game for the 26 unit position.
```
[FEN ""]
1. h4 a5 2. h5 a4 3. h6 a3 4. b3 g6 5. Bb2 Bg7 6. hxg7 axb2 7. a4 h5 8. a5 h4 9. Rh3 Ra6 10. c4 f5 11. Nc3 Nf6 12. Ne4 Nd5 13. cxd5 fxe4 14. Rc3 Rf6 15. f4 c6 16. a6 h3 17. a7 h2 18. a8=B h1=B 19. g8=B b1=B 20. d6 e3 21. Bc4 Bf5 22. Bd3 Be6 23. Qc2 Qa5 24. Qb2 Qe5 25. O-O-O Bg8 26. Bb1 Bh7 27. Ba2 O-O 28. Rc2 R6f7 29. Qa1 Qh8 30. Rb2 Rg7 31. Kb1 c5 32. Rc1 b5 33. g4 b4 34. g5 Bcb7 35. Bg2 Bd5 36. Be4 Bf7 37. Bc2 Be8 38. Bd1 Bd5 39. Nf3 Bdf7 40. Be4 Nc6 41. Bec2 Ne5 42. Nd4 cxd4 43. fxe5 e6 44. d3
``` |
4,836 | I came up with this rather amusing and bizarre stalemate where Black stalemates itself by self-smothering.
```
[FEN "8/8/8/8/8/3p4/pp6/krb1K3 b - - 0 1"]
1...d2+?? 2. Kd1
```
The peculiar feature of this stalemate is that Black is unable to move not because moving a piece would put its king into check, but moving a piece would require it to capture its own piece, which is disallowed. This is an example of a **single self-smothered stalemate**.
The question is, is it possible to have a **double self-smothered mate**, such that both sides do not have any moves at all because the moves would require capturing of the side's own pieces?
One possibility suggested by the user supercat is the following -
```
[FEN "KN1b4/RPpPp3/P1P5/4P3/8/3p1p1p/3PpPpr/4B1nk w - - 0 1"]
1. e6
```
And both sides are stalemated. However, this position cannot occur in practice, because you cannot have a Black bishop trapped on d8 with the c7 or e7 pawns still on their original squares. | 2014/02/27 | [
"https://chess.stackexchange.com/questions/4836",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/2429/"
] | I think I found a double-self-smothered-stalemate that could occur via sequence of legal moves from the normal starting position.
```
[FEN "5bnk/4ppbp/4P2p/5P1P/p1p5/P2p4/PBPP4/KNB5 w - - 0 1"]
1. c3 f6
```
Each player has seven pawns and two dark-square bishops, so one pawn from each player must have been promoted. Once White's b pawn has captured to a3 and Black's g pawn has captured to h6, White's g pawn and Black's b pawn can promote without any other pawn having to leave its file. I haven't worked out the exact "game", but I see no reason to believe it wouldn't be relatively trivial, particularly if one isn't worried about achieving the position with a minimal number of moves. | Just for fun, here is an attempt at **optimizing** the number of pieces that can be involved. I was able to manage **24 pieces.**
```
[Title "me, chess.stackexchange.com 6/23/2019, mate in 20"]
[FEN "5brk/4p1pb/4p1p1/p3P1Pp/Pp1p3P/1P1P4/BP1P4/KRB5 w - - 0 1"]
``` |
4,836 | I came up with this rather amusing and bizarre stalemate where Black stalemates itself by self-smothering.
```
[FEN "8/8/8/8/8/3p4/pp6/krb1K3 b - - 0 1"]
1...d2+?? 2. Kd1
```
The peculiar feature of this stalemate is that Black is unable to move not because moving a piece would put its king into check, but moving a piece would require it to capture its own piece, which is disallowed. This is an example of a **single self-smothered stalemate**.
The question is, is it possible to have a **double self-smothered mate**, such that both sides do not have any moves at all because the moves would require capturing of the side's own pieces?
One possibility suggested by the user supercat is the following -
```
[FEN "KN1b4/RPpPp3/P1P5/4P3/8/3p1p1p/3PpPpr/4B1nk w - - 0 1"]
1. e6
```
And both sides are stalemated. However, this position cannot occur in practice, because you cannot have a Black bishop trapped on d8 with the c7 or e7 pawns still on their original squares. | 2014/02/27 | [
"https://chess.stackexchange.com/questions/4836",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/2429/"
] | Here's a simpler mutual smothered stalemate
(9 men on a side, no promoted pieces):
```
[Title "Mutual smothered stalemate"]
[fen "5brk/4p1pb/4P1p1/6P1/1p6/1P1p4/BP1P4/KRB5 w - - 0 1"]
``` | In response to an your original question about whether anything interesting has been written about stalemates, it may be worth mentioning that puzzle creator Sam Lloyd is often credited with two interesting stalemate "games" (though see game 3679 at <http://www.chesshistory.com/winter/winter08.html> for information about that attribution); in the first, White stalemates Black on the tenth move, after having captured six black pieces:
```
[FEN ""]
1.e3 a5 2.Qh5 Ra6 3.Qxa5 h5 4.Qxc7 Rah6 5.h4 f6 6.Qxd7+ Kf7 7.Qxb7 Qd3 8.Qxb8 Qh7 9.Qxc8 Kg6 10.Qe6
```
In the second, White is stalemated after Black's twelfth move, while all 32 chessmen are on the board:
```
[FEN ""]
1.d4 d6 2.Qd2 e5 3.a4 e4 4.Qf4 f5 5.h3 Be7 6.Qh2 Be6 7.Ra3 c5 8.Rg3 Qa5+ 9.Nd2 Bh4 10.f3 Bb3 11.d5 e3 12.c4 f4
```
In both of Sam Lloyd's positions, one side is stalemated while the other has many moves available. For both sides to be stalemated would probably take significantly more moves, and for both sides to be smother-stalemated would take more yet. |
4,836 | I came up with this rather amusing and bizarre stalemate where Black stalemates itself by self-smothering.
```
[FEN "8/8/8/8/8/3p4/pp6/krb1K3 b - - 0 1"]
1...d2+?? 2. Kd1
```
The peculiar feature of this stalemate is that Black is unable to move not because moving a piece would put its king into check, but moving a piece would require it to capture its own piece, which is disallowed. This is an example of a **single self-smothered stalemate**.
The question is, is it possible to have a **double self-smothered mate**, such that both sides do not have any moves at all because the moves would require capturing of the side's own pieces?
One possibility suggested by the user supercat is the following -
```
[FEN "KN1b4/RPpPp3/P1P5/4P3/8/3p1p1p/3PpPpr/4B1nk w - - 0 1"]
1. e6
```
And both sides are stalemated. However, this position cannot occur in practice, because you cannot have a Black bishop trapped on d8 with the c7 or e7 pawns still on their original squares. | 2014/02/27 | [
"https://chess.stackexchange.com/questions/4836",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/2429/"
] | Reduce number of units from Noam's record of 18 to a new record of 15.
(8+7 units, no promoted units necessarily on the board, pawn captures all achievable):
```
[Title "Minimal mutual smothered stalemate"]
[fen "5brk/4p1pb/4P1p1/6P1/6PB/6PK/6PP/8 w - - 0 1"]
```
Is this the best possible?
It's interesting that this solution is asymmetric. If you wrap both kings with pawns on opposite flanks, it requires 16 units.
EDIT: Inspired by a comment, I want to show more deeply that the position is legal. And if fact prove that, despite appearances *at least one promotion took place in the history of the game*. Assume first that no promotions happened.
White c-h pawns could have reached their files with 8 captures, which is OK since Black has 7 units left.
What about the Black pawns? All but 1 Black unit were captured by White c-h pawns. BfP ("Black f pawn") captured to g6, as this pawn couldn't have come from h7. Most efficient if BhP captured to g file, to be captured in its turn.
White pawns made 1,2,2,3 captures on files d,e,f,g respectively. So Black b,c,d pawns would have to make a total of 5 captures to get far enough (to d & e files). Together with the 2 captures onto the g file, Black made at least 7 pawn captures. This is making the most efficient assumption that BaP was the one missing Black unit not captured by a WP.
Black made 7 pawn captures, and White has 8 units remaining, so at first it looks OK. But none of these captures were on files a or b, where WaP & WbP began. One of those two WPs must have also got hit by a BP, but how? The only capture possible is of BaP.
Therefore, we have proved our original assumption wrong: at least one promotion happened in the course of the game. That might have been White or Black. E.g. WbP promotes on b1, or e.g. BbP captures only once, and promotes on c1.
---
As per @Laska"s given permission in the comments, here is a 35-move (optimal?) proof game created by @Rewan Demontay, of their position. The intention of it is that it was made to prove their retrograde analysis of the game history of their position.
```
[FEN ""]
1. Nc3 h5 2. Ne4 h4 3. Ng3 hxg3 4. fxg3 Nc6 5. Kf2 a5 6. Kf3 a4 7. Kg4 Nh6+ 8. Kh3 Ne5 9. b3 Nf3 10. exf3 Rg8 11. Bd3 Ng4 12. fxg4 d5 13. Be4 dxe4 14. Qf3 e3 15. dxe3 Kd7 16. Qxb7 Ke6 17. Ne2 Kf6 18. Bb2+ Kg6 19. Bf6 Kh7 20. Bh4 Kh8 21. Nf4 Bf5 22. Rhf1 Bh7 23. Ng6+ fxg6 24. Rad1 c6 25. Rd5 cxd5 26. c4 axb3 27. cxd5 bxa2 28. Rf4 Qd6 29. Qb5 Qe6 30. dxe6 a1=Q 31. Qc5 Qa4 32. Qd5 Qxf4 33. exf4 Ra5 34. Qg5 Rxg5 35. fxg5
```
As you can see, a **promotion** is **needed** as @Laska **rightfully claimed.**
EDIT: Thanks @Rewan. And here is a candidate *maximal* mutually smothered checkmate:
```
[Title "Maximal mutual smothered stalemate"]
[fen "4brkq/3p1brb/3Pp1p1/4P1P1/1p1p4/1P1Pp3/BRB1P3/QKRB4 w - - 0 1"]
```
Legal position with 26 pieces: 6 minor pieces captured & 4 promoted bishops. Some flexibility in the diagram: in keeping with the maximality I've chosen major pieces rather than knights in the back row. Also, kept the smothered kings out of the corners.
Note the pawn moves d2-d3 and e7-e6 unlock the two cages.
Here is a proof game for the 26 unit position.
```
[FEN ""]
1. h4 a5 2. h5 a4 3. h6 a3 4. b3 g6 5. Bb2 Bg7 6. hxg7 axb2 7. a4 h5 8. a5 h4 9. Rh3 Ra6 10. c4 f5 11. Nc3 Nf6 12. Ne4 Nd5 13. cxd5 fxe4 14. Rc3 Rf6 15. f4 c6 16. a6 h3 17. a7 h2 18. a8=B h1=B 19. g8=B b1=B 20. d6 e3 21. Bc4 Bf5 22. Bd3 Be6 23. Qc2 Qa5 24. Qb2 Qe5 25. O-O-O Bg8 26. Bb1 Bh7 27. Ba2 O-O 28. Rc2 R6f7 29. Qa1 Qh8 30. Rb2 Rg7 31. Kb1 c5 32. Rc1 b5 33. g4 b4 34. g5 Bcb7 35. Bg2 Bd5 36. Be4 Bf7 37. Bc2 Be8 38. Bd1 Bd5 39. Nf3 Bdf7 40. Be4 Nc6 41. Bec2 Ne5 42. Nd4 cxd4 43. fxe5 e6 44. d3
``` | In response to an your original question about whether anything interesting has been written about stalemates, it may be worth mentioning that puzzle creator Sam Lloyd is often credited with two interesting stalemate "games" (though see game 3679 at <http://www.chesshistory.com/winter/winter08.html> for information about that attribution); in the first, White stalemates Black on the tenth move, after having captured six black pieces:
```
[FEN ""]
1.e3 a5 2.Qh5 Ra6 3.Qxa5 h5 4.Qxc7 Rah6 5.h4 f6 6.Qxd7+ Kf7 7.Qxb7 Qd3 8.Qxb8 Qh7 9.Qxc8 Kg6 10.Qe6
```
In the second, White is stalemated after Black's twelfth move, while all 32 chessmen are on the board:
```
[FEN ""]
1.d4 d6 2.Qd2 e5 3.a4 e4 4.Qf4 f5 5.h3 Be7 6.Qh2 Be6 7.Ra3 c5 8.Rg3 Qa5+ 9.Nd2 Bh4 10.f3 Bb3 11.d5 e3 12.c4 f4
```
In both of Sam Lloyd's positions, one side is stalemated while the other has many moves available. For both sides to be stalemated would probably take significantly more moves, and for both sides to be smother-stalemated would take more yet. |
4,836 | I came up with this rather amusing and bizarre stalemate where Black stalemates itself by self-smothering.
```
[FEN "8/8/8/8/8/3p4/pp6/krb1K3 b - - 0 1"]
1...d2+?? 2. Kd1
```
The peculiar feature of this stalemate is that Black is unable to move not because moving a piece would put its king into check, but moving a piece would require it to capture its own piece, which is disallowed. This is an example of a **single self-smothered stalemate**.
The question is, is it possible to have a **double self-smothered mate**, such that both sides do not have any moves at all because the moves would require capturing of the side's own pieces?
One possibility suggested by the user supercat is the following -
```
[FEN "KN1b4/RPpPp3/P1P5/4P3/8/3p1p1p/3PpPpr/4B1nk w - - 0 1"]
1. e6
```
And both sides are stalemated. However, this position cannot occur in practice, because you cannot have a Black bishop trapped on d8 with the c7 or e7 pawns still on their original squares. | 2014/02/27 | [
"https://chess.stackexchange.com/questions/4836",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/2429/"
] | In response to an your original question about whether anything interesting has been written about stalemates, it may be worth mentioning that puzzle creator Sam Lloyd is often credited with two interesting stalemate "games" (though see game 3679 at <http://www.chesshistory.com/winter/winter08.html> for information about that attribution); in the first, White stalemates Black on the tenth move, after having captured six black pieces:
```
[FEN ""]
1.e3 a5 2.Qh5 Ra6 3.Qxa5 h5 4.Qxc7 Rah6 5.h4 f6 6.Qxd7+ Kf7 7.Qxb7 Qd3 8.Qxb8 Qh7 9.Qxc8 Kg6 10.Qe6
```
In the second, White is stalemated after Black's twelfth move, while all 32 chessmen are on the board:
```
[FEN ""]
1.d4 d6 2.Qd2 e5 3.a4 e4 4.Qf4 f5 5.h3 Be7 6.Qh2 Be6 7.Ra3 c5 8.Rg3 Qa5+ 9.Nd2 Bh4 10.f3 Bb3 11.d5 e3 12.c4 f4
```
In both of Sam Lloyd's positions, one side is stalemated while the other has many moves available. For both sides to be stalemated would probably take significantly more moves, and for both sides to be smother-stalemated would take more yet. | Just for fun, here is an attempt at **optimizing** the number of pieces that can be involved. I was able to manage **24 pieces.**
```
[Title "me, chess.stackexchange.com 6/23/2019, mate in 20"]
[FEN "5brk/4p1pb/4p1p1/p3P1Pp/Pp1p3P/1P1P4/BP1P4/KRB5 w - - 0 1"]
``` |
4,836 | I came up with this rather amusing and bizarre stalemate where Black stalemates itself by self-smothering.
```
[FEN "8/8/8/8/8/3p4/pp6/krb1K3 b - - 0 1"]
1...d2+?? 2. Kd1
```
The peculiar feature of this stalemate is that Black is unable to move not because moving a piece would put its king into check, but moving a piece would require it to capture its own piece, which is disallowed. This is an example of a **single self-smothered stalemate**.
The question is, is it possible to have a **double self-smothered mate**, such that both sides do not have any moves at all because the moves would require capturing of the side's own pieces?
One possibility suggested by the user supercat is the following -
```
[FEN "KN1b4/RPpPp3/P1P5/4P3/8/3p1p1p/3PpPpr/4B1nk w - - 0 1"]
1. e6
```
And both sides are stalemated. However, this position cannot occur in practice, because you cannot have a Black bishop trapped on d8 with the c7 or e7 pawns still on their original squares. | 2014/02/27 | [
"https://chess.stackexchange.com/questions/4836",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/2429/"
] | Here's a simpler mutual smothered stalemate
(9 men on a side, no promoted pieces):
```
[Title "Mutual smothered stalemate"]
[fen "5brk/4p1pb/4P1p1/6P1/1p6/1P1p4/BP1P4/KRB5 w - - 0 1"]
``` | Just for fun, here is an attempt at **optimizing** the number of pieces that can be involved. I was able to manage **24 pieces.**
```
[Title "me, chess.stackexchange.com 6/23/2019, mate in 20"]
[FEN "5brk/4p1pb/4p1p1/p3P1Pp/Pp1p3P/1P1P4/BP1P4/KRB5 w - - 0 1"]
``` |
4,836 | I came up with this rather amusing and bizarre stalemate where Black stalemates itself by self-smothering.
```
[FEN "8/8/8/8/8/3p4/pp6/krb1K3 b - - 0 1"]
1...d2+?? 2. Kd1
```
The peculiar feature of this stalemate is that Black is unable to move not because moving a piece would put its king into check, but moving a piece would require it to capture its own piece, which is disallowed. This is an example of a **single self-smothered stalemate**.
The question is, is it possible to have a **double self-smothered mate**, such that both sides do not have any moves at all because the moves would require capturing of the side's own pieces?
One possibility suggested by the user supercat is the following -
```
[FEN "KN1b4/RPpPp3/P1P5/4P3/8/3p1p1p/3PpPpr/4B1nk w - - 0 1"]
1. e6
```
And both sides are stalemated. However, this position cannot occur in practice, because you cannot have a Black bishop trapped on d8 with the c7 or e7 pawns still on their original squares. | 2014/02/27 | [
"https://chess.stackexchange.com/questions/4836",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/2429/"
] | Reduce number of units from Noam's record of 18 to a new record of 15.
(8+7 units, no promoted units necessarily on the board, pawn captures all achievable):
```
[Title "Minimal mutual smothered stalemate"]
[fen "5brk/4p1pb/4P1p1/6P1/6PB/6PK/6PP/8 w - - 0 1"]
```
Is this the best possible?
It's interesting that this solution is asymmetric. If you wrap both kings with pawns on opposite flanks, it requires 16 units.
EDIT: Inspired by a comment, I want to show more deeply that the position is legal. And if fact prove that, despite appearances *at least one promotion took place in the history of the game*. Assume first that no promotions happened.
White c-h pawns could have reached their files with 8 captures, which is OK since Black has 7 units left.
What about the Black pawns? All but 1 Black unit were captured by White c-h pawns. BfP ("Black f pawn") captured to g6, as this pawn couldn't have come from h7. Most efficient if BhP captured to g file, to be captured in its turn.
White pawns made 1,2,2,3 captures on files d,e,f,g respectively. So Black b,c,d pawns would have to make a total of 5 captures to get far enough (to d & e files). Together with the 2 captures onto the g file, Black made at least 7 pawn captures. This is making the most efficient assumption that BaP was the one missing Black unit not captured by a WP.
Black made 7 pawn captures, and White has 8 units remaining, so at first it looks OK. But none of these captures were on files a or b, where WaP & WbP began. One of those two WPs must have also got hit by a BP, but how? The only capture possible is of BaP.
Therefore, we have proved our original assumption wrong: at least one promotion happened in the course of the game. That might have been White or Black. E.g. WbP promotes on b1, or e.g. BbP captures only once, and promotes on c1.
---
As per @Laska"s given permission in the comments, here is a 35-move (optimal?) proof game created by @Rewan Demontay, of their position. The intention of it is that it was made to prove their retrograde analysis of the game history of their position.
```
[FEN ""]
1. Nc3 h5 2. Ne4 h4 3. Ng3 hxg3 4. fxg3 Nc6 5. Kf2 a5 6. Kf3 a4 7. Kg4 Nh6+ 8. Kh3 Ne5 9. b3 Nf3 10. exf3 Rg8 11. Bd3 Ng4 12. fxg4 d5 13. Be4 dxe4 14. Qf3 e3 15. dxe3 Kd7 16. Qxb7 Ke6 17. Ne2 Kf6 18. Bb2+ Kg6 19. Bf6 Kh7 20. Bh4 Kh8 21. Nf4 Bf5 22. Rhf1 Bh7 23. Ng6+ fxg6 24. Rad1 c6 25. Rd5 cxd5 26. c4 axb3 27. cxd5 bxa2 28. Rf4 Qd6 29. Qb5 Qe6 30. dxe6 a1=Q 31. Qc5 Qa4 32. Qd5 Qxf4 33. exf4 Ra5 34. Qg5 Rxg5 35. fxg5
```
As you can see, a **promotion** is **needed** as @Laska **rightfully claimed.**
EDIT: Thanks @Rewan. And here is a candidate *maximal* mutually smothered checkmate:
```
[Title "Maximal mutual smothered stalemate"]
[fen "4brkq/3p1brb/3Pp1p1/4P1P1/1p1p4/1P1Pp3/BRB1P3/QKRB4 w - - 0 1"]
```
Legal position with 26 pieces: 6 minor pieces captured & 4 promoted bishops. Some flexibility in the diagram: in keeping with the maximality I've chosen major pieces rather than knights in the back row. Also, kept the smothered kings out of the corners.
Note the pawn moves d2-d3 and e7-e6 unlock the two cages.
Here is a proof game for the 26 unit position.
```
[FEN ""]
1. h4 a5 2. h5 a4 3. h6 a3 4. b3 g6 5. Bb2 Bg7 6. hxg7 axb2 7. a4 h5 8. a5 h4 9. Rh3 Ra6 10. c4 f5 11. Nc3 Nf6 12. Ne4 Nd5 13. cxd5 fxe4 14. Rc3 Rf6 15. f4 c6 16. a6 h3 17. a7 h2 18. a8=B h1=B 19. g8=B b1=B 20. d6 e3 21. Bc4 Bf5 22. Bd3 Be6 23. Qc2 Qa5 24. Qb2 Qe5 25. O-O-O Bg8 26. Bb1 Bh7 27. Ba2 O-O 28. Rc2 R6f7 29. Qa1 Qh8 30. Rb2 Rg7 31. Kb1 c5 32. Rc1 b5 33. g4 b4 34. g5 Bcb7 35. Bg2 Bd5 36. Be4 Bf7 37. Bc2 Be8 38. Bd1 Bd5 39. Nf3 Bdf7 40. Be4 Nc6 41. Bec2 Ne5 42. Nd4 cxd4 43. fxe5 e6 44. d3
``` | Just for fun, here is an attempt at **optimizing** the number of pieces that can be involved. I was able to manage **24 pieces.**
```
[Title "me, chess.stackexchange.com 6/23/2019, mate in 20"]
[FEN "5brk/4p1pb/4p1p1/p3P1Pp/Pp1p3P/1P1P4/BP1P4/KRB5 w - - 0 1"]
``` |
9,282,865 | I'm hosting a website for a friend of me and I want to use a sub domain (sapp.xgclan.com) to link to his directory on my webserver.
You can also access this directory by going to www.xgclan.com/sapp/
Now I'm using the following .htaccesses file:
```
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(sapp.)xgclan.com$
RewriteRule ^(/)?$ sapp [L]
```
It works fine but when I visit sapp.xgclan.com it turns it into sapp.xgclan.com/sapp/
I don't want it to visibly add the /sapp/ part to the url in the browser.
I already tried
```
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(sapp.)xgclan.com$
RewriteRule ^(/)?$ sapp [QSA,L]
```
But that didn't work. | 2012/02/14 | [
"https://Stackoverflow.com/questions/9282865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889861/"
] | Try
```
RewriteEngine on
RewriteBase /
#if its sapp.xgckan.com
RewriteCond %{HTTP_HOST} ^sapp.xgclan.com$ [NC]
#rewrite the request to the sapp folder
RewriteRule ^ sapp%{REQUEST_URI} [L]
```
**EDIT**
>
> I just want to do this for the following sub domains: forum, sapp and servers
>
>
>
For `forum`, `sapp` and `servers` use the solution below instead
```
#if its sapp/forum/servers.xgckan.com
RewriteCond %{HTTP_HOST} ^(sapp|forum|servers).xgclan.com$ [NC]
#rewrite the request to the sap/forum/servers folder
RewriteRule ^ %1%{REQUEST_URI} [L]
``` | Not quite an answer to the concrete question, but: Why don't you point the virtual host sapp.xglcan.com directly to the sapp subdirectory? Like this:
```
<VirtualHost *:80>
DocumentRoot [path/to/www.xglan.com]/sapp
ServerName sapp.xglan.com
</VirtualHost>
``` |
56,201,386 | I am trying to update my Android project.
I initially got this error:
>
> ERROR: Gradle DSL method not found: 'classpath()'
> Possible causes:
> The project 'xxx' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).
> Upgrade plugin to version 3.4.1 and sync project
>
>
>
So I tried this in my app's `build.gradle`:
```
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
classpath 'io.fabric.tools:gradle:1.29.0'
}
}
```
But now I'm getting this error:
>
> ERROR: Could not find com.android.tools.build:gradle:3.4.1.
>
>
>
What to do? Thanks for your help. | 2019/05/18 | [
"https://Stackoverflow.com/questions/56201386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2885727/"
] | I agree with @Doug on this one - callable wraps this for you and will be easier -, but my use case required me to make HTTPS calls (`onRequest` in Functions). Also, I think you're just in the correct path - but you're **possibly** not checking it in your Cloud Functions.
In your app, you'll call:
```dart
_httpsCall() async {
// Fetch the currentUser, and then get its id token
final user = await FirebaseAuth.instance.currentUser();
final idToken = await user.getIdToken();
final token = idToken.token;
// Create authorization header
final header = { "authorization": 'Bearer $token' };
get("http://YOUR_PROJECT_BASE_URL/httpsFunction", headers: header)
.then((response) {
final status = response.statusCode;
print('STATUS CODE: $status');
})
.catchError((e) {
print(e);
});
}
```
In your function, you'll check for the token:
```js
export const httpsFunction = functions.https.onRequest((request, response) => {
const authorization = request.header("authorization")
if (authorization) {
const idToken = authorization.split('Bearer ')[1]
if (!idToken) {
response.status(400).send({ response: "Unauthenticated request!" })
return
}
return admin.auth().verifyIdToken(idToken)
.then(decodedToken => {
// You can check for your custom claims here as well
response.status(200).send({ response: "Authenticated request!" })
})
.catch(err => {
response.status(400).send({ response: "Unauthenticated request!" })
})
}
response.status(400).send({ response: "Unauthenticated request!" })
})
```
Keep in mind:
If I'm not mistaken, those tokens are valid for 1 hour, if you are going to store them somewhere, just be aware of this. I've tested locally and i**t takes around 200~500ms** - every time - to get only the id token, which in most cases are not that big of overhead - but is significant. | It's going to be easiest for you to use a [callable function](https://firebase.google.com/docs/functions/callable), since that lets you:
1. Automatically send the current user's uid in the request.
2. Know very easily on the function side if a UID was provided in the request, and refuse service if none was provided.
The flutter plugin is [here](https://pub.dev/packages/cloud_functions).
You should be able to do the equivalent work yourself, though, since callable functions are just a wrapper around normal HTTP connections. It's possible for you to get the ID token of the logged in user. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.