问:
Facing issues in Pybossa during LDAP authentication

Installed "Pybossa for Python 3" in recommended virtual environment on Ubuntu 20.04.05

Configured OpenLdap envirponment and 1 user ubuntu ( Normal User) and 1 admin ( Admin ) .

Pybossa Local authentication is working fine.

Enabled Ldap authentication at Pybossa.

Created entry of ubuntu user in Postgres db .

We are not able to authenticate with Ldap authentication through Pybossa and getting below error at Postgres level...

```<code>sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedFunction) operator does not exist: character varying = bytea
LINE 3: WHERE "user".ldap = '\x7562756e7475'::bytea
                          ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

[SQL: SELECT "user".id AS user_id, "user".created AS user_created, "user".email_addr AS user_email_addr, "user".name AS user_name, "user".fullname AS user_fullnam                       e, "user".locale AS user_locale, "user".api_key AS user_api_key, "user".passwd_hash AS user_passwd_hash, "user".ldap AS user_ldap, "user".admin AS user_admin, "us                       er".pro AS user_pro, "user".privacy_mode AS user_privacy_mode, "user".restrict AS user_restrict, "user".category AS user_category, "user".flags AS user_flags, "us                       er".ckan_api AS user_ckan_api, "user".newsletter_prompted AS user_newsletter_prompted, "user".valid_email AS user_valid_email, "user".confirmation_email_sent AS u                       ser_confirmation_email_sent, "user".subscribed AS user_subscribed, "user".consent AS user_consent, "user".info AS user_info, "user".user_pref AS user_user_pref, "                       user".notified_at AS user_notified_at
FROM "user"
WHERE "user".ldap = %(ldap_1)s
 LIMIT %(param_1)s]
[parameters: {'ldap_1': <psycopg2.extensions.Binary object at 0x7fb0a40a1d50>, 'param_1': 1}]
(Background on this error at: https://sqlalche.me/e/14/f405)

</code>```

were able to successfully get ubuntu user info from ldapsearch..

(env) root@ldap:/pybossaldapsearch -h 127.0.0.1 -p 389 -D "CN=admin,dc=example,dc=com" -W -b "dc=example,dc=com" -LLL "(&(objectclass=inetOrgPerson)(cn=ubuntu))"
Enter LDAP Password:
dn: uid=ubuntu,ou=people,dc=example,dc=com
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
cn: ubuntu
sn: ubuntu
loginShell: /bin/bash
uidNumber: 2000
gidNumber: 2000
homeDirectory: /home/ubuntu
uid: ubuntu
userPassword:: e1NTSEF9a1lyaWpyeVJXem1YSGxyYlR5U1NtN3hCc01QUjRkR3U=

(env) root@ldap:/pybossa#

Were not able to login into pybosaa with LDAP

Pybossa login Error

At Postgres receive the below error...

Error at Postgres Level when try to login in Pybossa

Body:
Installed "Pybossa for Python 3" in recommended virtual environment on Ubuntu 20.04.05

Configured OpenLdap envirponment and 1 user ubuntu ( Normal User) and 1 admin ( Admin ) .

Pybossa Local authentication is working fine.

Enabled Ldap authentication at Pybossa.

Created entry of ubuntu user in Postgres db .

We are not able to authenticate with Ldap authentication through Pybossa and getting below error at Postgres level...

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedFunction) operator does not exist: character varying = bytea
LINE 3: WHERE "user".ldap = '\x7562756e7475'::bytea
                          ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

[SQL: SELECT "user".id AS user_id, "user".created AS user_created, "user".email_addr AS user_email_addr, "user".name AS user_name, "user".fullname AS user_fullnam                       e, "user".locale AS user_locale, "user".api_key AS user_api_key, "user".passwd_hash AS user_passwd_hash, "user".ldap AS user_ldap, "user".admin AS user_admin, "us                       er".pro AS user_pro, "user".privacy_mode AS user_privacy_mode, "user".restrict AS user_restrict, "user".category AS user_category, "user".flags AS user_flags, "us                       er".ckan_api AS user_ckan_api, "user".newsletter_prompted AS user_newsletter_prompted, "user".valid_email AS user_valid_email, "user".confirmation_email_sent AS u                       ser_confirmation_email_sent, "user".subscribed AS user_subscribed, "user".consent AS user_consent, "user".info AS user_info, "user".user_pref AS user_user_pref, "                       user".notified_at AS user_notified_at
FROM "user"
WHERE "user".ldap = %(ldap_1)s
 LIMIT %(param_1)s]
[parameters: {'ldap_1': <psycopg2.extensions.Binary object at 0x7fb0a40a1d50>, 'param_1': 1}]
(Background on this error at: https://sqlalche.me/e/14/f405)

were able to successfully get ubuntu user info from ldapsearch..

(env) root@ldap:/pybossaldapsearch -h 127.0.0.1 -p 389 -D "CN=admin,dc=example,dc=com" -W -b "dc=example,dc=com" -LLL "(&(objectclass=inetOrgPerson)(cn=ubuntu))"
Enter LDAP Password:
dn: uid=ubuntu,ou=people,dc=example,dc=com
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
cn: ubuntu
sn: ubuntu
loginShell: /bin/bash
uidNumber: 2000
gidNumber: 2000
homeDirectory: /home/ubuntu
uid: ubuntu
userPassword:: e1NTSEF9a1lyaWpyeVJXem1YSGxyYlR5U1NtN3hCc01QUjRkR3U=

(env) root@ldap:/pybossa#

Were not able to login into pybosaa with LDAP

Pybossa login Error

At Postgres receive the below error...

Error at Postgres Level when try to login in Pybossa


来源: stackexchange

问:
Oracle OBIEE 11g post installation scripts stuck at Setting up BI Publisher
I want to install OBIEE 11g in windows Server 2012 R2 but in step 13 of 14 during post installation scripts gets stuck and cannot move in Setting up BI publisher stage, need your kind help.

Thank you

I tried many times in other windows OSs but same stuck I got

ContentLicense: CC BY-SA 4.0


问:
Chartjs how to group labels
I have a graph with geographical points
On the Y axis I display the elevations
On the x axis I display the distance of the points from the starting point
I would like these distances to be grouped in 5 km increments

My graph

const elevations = [200,220,210,230,250,180,220...]//350 items
const distances = [0,500,1700,2300,2900,3420,3780,4250,5230,...]//350 items
const labels = ['0km', '2.81 km', '5.11 km', '7.41 km', '9.71 km', '12.01 km', '14.31 km', '16.62 km', '18.92 km', '21.21 km', '23.51 km', '25.80 km', '28.10 km', '30.39 km'];
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Elevation',
                data: elevations,
                borderWidth: 3,
                borderColor: '#F568000',
                backgroundColor: '#FF0000',
                fill: 'start'
            }]
        }
    });
```

Here is the desired end result at the bottom of the page

https://www.famenneardenne.be/se-balader/a-velo/?mb_minnumpage=1&mb_maxnumpage=2&mb_page=circuit&mb_id=49332&mb_titre=marche-en-famenne-circuit-vtt-vert&mbScrollTo=module

Thanks you

Title: Chartjs how to group labels

Body:
I have a graph with geographical points
On the Y axis I display the elevations
On the x axis I display the distance of the points from the starting point
I would like these distances to be grouped in 5 km increments

My graph

const elevations = [200,220,210,230,250,180,220...]//350 items
const distances = [0,500,1700,2300,2900,3420,3780,4250,5230,...]//350 items
const labels = ['0km', '2.81 km', '5.11 km', '7.41 km', '9.71 km', '12.01 km', '14.31 km', '16.62 km', '18.92 km', '21.21 km', '23.51 km', '25.80 km', '28.10 km', '30.39 km'];
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Elevation',
                data: elevations,
                borderWidth: 3,
                borderColor: '#F568000',
                backgroundColor: '#FF0000',
                fill: 'start'
            }]
        }
    });

Here is the desired end result at the bottom of the page

https://www.famenneardenne.be/se-balader/a-velo/?mb_minnumpage=1&mb_maxnumpage=2&mb_page=circuit&mb_id=49332&mb_titre=marche-en-famenne-circuit-vtt-vert&mbScrollTo=module

Thanks you


问:
React native realm mongodb query and offline usage
We have a use case where logged in user will has list of products which can be shown even if not internet connection and i tried to achieve this using realm device sync (Flexible) using mongodb query (Aggregation) but it able to fetch products only when internet is available so my question is that is it possible with realm device sync that we sync products from mongodb using mongodb query and load even if there is no internet connection?

Below is sample code that i tried to integrate in our app but it

```<code>const config = {
    id: this.id
};
this.app = new Realm.App(config);

const credentials = Realm.Credentials.anonymous();
await this.app.logIn(credentials);

this.connection =  await Realm.open({
    schema: [Customer],
    sync: {
        user: this.app.currentUser,
        flexible: true,
        onError: (_session, error: any) => {
            console.log('sync error');
            console.log(error.name, error.message);
        }
    }
});

const mongodb = this.app.currentUser.mongoClient('mongodb-atlas');
const collectionUsers = mongodb.db('dev_database').collection('user_roles');

const pipeline = [{
    ...
}];

const result = await collectionUsers.aggregate(pipeline);
// Get result when user is online but do not loads after i switch to offline
</code>```

So problem is above aggregate query doesn't work if user is offline

I tried realm mongodb query and expecting it should work when user is offline as well

Body:
We have a use case where logged in user will has list of products which can be shown even if not internet connection and i tried to achieve this using realm device sync (Flexible) using mongodb query (Aggregation) but it able to fetch products only when internet is available so my question is that is it possible with realm device sync that we sync products from mongodb using mongodb query and load even if there is no internet connection?

Below is sample code that i tried to integrate in our app but it

const config = {
    id: this.id
};
this.app = new Realm.App(config);

const credentials = Realm.Credentials.anonymous();
await this.app.logIn(credentials);

this.connection =  await Realm.open({
    schema: [Customer],
    sync: {
        user: this.app.currentUser,
        flexible: true,
        onError: (_session, error: any) => {
            console.log('sync error');
            console.log(error.name, error.message);
        }
    }
});

const mongodb = this.app.currentUser.mongoClient('mongodb-atlas');
const collectionUsers = mongodb.db('dev_database').collection('user_roles');

const pipeline = [{
    ...
}];

const result = await collectionUsers.aggregate(pipeline);
// Get result when user is online but do not loads after i switch to offline

So problem is above aggregate query doesn't work if user is offline

I tried realm mongodb query and expecting it should work when user is offline as well


问:
Why does the following shorthand not work in JS?
Here's a block of code that takes an array of strings and converts them into an integer.

To be more clear, it parses the numerical characters to integers.

console.log(['1', '2', '0'].map((num) => Number.parseInt(num)))```
</div>
</div>
</p>
<p>The above works as expected. However, the following shorthand does not work.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(['1', '2', '0'].map(Number.parseInt))</code>```

You can run the code snippet and you will find that the first snippet logs the result 1, 2 and 0 as expected. However, the latter logs 1, NaN and 0.

Is there somewhere I am going wrong here in using this shorthand?

Body:
Here's a block of code that takes an array of strings and converts them into an integer.

To be more clear, it parses the numerical characters to integers.

console.log(['1', '2', '0'].map((num) => Number.parseInt(num)))

The above works as expected. However, the following shorthand does not work.

console.log(['1', '2', '0'].map(Number.parseInt))

You can run the code snippet and you will find that the first snippet logs the result 1, 2 and 0 as expected. However, the latter logs 1, NaN and 0.

Is there somewhere I am going wrong here in using this shorthand?


问:
SciPy's linegress to replicate R's linear regression "lm()"
I would like to replicate R's lm() (linear regression, possibly "Ordinary Least Squares") with SciPy. I assume that scipy.stats.linregress is suited for that.

Based on the mtcars dataset my formula is qsec ~ mpg * wt + gear.
This are 3 different types of arguments plus the dataset itself.

But SciPy's scipy.stats.linregress only offer two arguments.

This is not possible of course

```<code>linegress("qsec", "mpeg, wt", "gear", data=mtcars)
</code>```

Here is an MWE in R

```<code>data(mtcars)
m = lm(formula = qsec ~ mpg * wt + gear, data = mtcars)
summary(m)
</code>```

That is an MWE in Python using statsmodels producing the same results then the R variant.

```<code>import pydataset
# Ordinary Least Squares
from statsmodels.formula.api import ols

mtcars = pydataset.data('mtcars')
m = ols(formula='qsec ~ mpg * wt + gear', data=mtcars)
print(m.fit().summary())
</code>```

Body:
I would like to replicate R's lm() (linear regression, possibly "Ordinary Least Squares") with SciPy. I assume that scipy.stats.linregress is suited for that.

Based on the mtcars dataset my formula is qsec ~ mpg * wt + gear.
This are 3 different types of arguments plus the dataset itself.

But SciPy's scipy.stats.linregress only offer two arguments.

This is not possible of course

linegress("qsec", "mpeg, wt", "gear", data=mtcars)

Here is an MWE in R

data(mtcars)
m = lm(formula = qsec ~ mpg * wt + gear, data = mtcars)
summary(m)

That is an MWE in Python using statsmodels producing the same results then the R variant.

import pydataset
# Ordinary Least Squares
from statsmodels.formula.api import ols

mtcars = pydataset.data('mtcars')
m = ols(formula='qsec ~ mpg * wt + gear', data=mtcars)
print(m.fit().summary())


问:
How to pass a list of integers to a table-valued parameter in C#?
I'm using ASP.NET MVC Framework and SQL Server for this one.
I have created a table type which will have the list of ids coming from a variable in C#

```<code>CREATE TYPE [dbo].[RespondentTypeTable] AS TABLE
(
    Id INT NOT NULL
)
</code>```

I have created a procedure to pass the table-valued parameter with the table-type created above in readonly mode and 2 integer parameters. The stored procedure will insert the records from the other joined tables mentioned in the select statement into a local temporary table allutilitydatadto and will get the results from the temp table and drop it after fetching the records.

```<code>CREATE PROCEDURE GetSensitivityDataForDimension(@respondentIdType [dbo].[RespondentTypeTable] READONLY, @studyId INT, @dimension INT )
AS
BEGIN

CREATE TABLE #AllUtilityDataDTO
(
    AttributeLevelId INT NOT NULL,
    AttributeLevelName NVARCHAR(MAX),
    AttributeId INT NOT NULL,
    AttributeName NVARCHAR(MAX),
    RespondentId INT NOT NULL,
    UtilityValue INT
);

BEGIN
INSERT INTO #AllUtilityDataDTO
(
    AttributeLevelId,
    AttributeLevelName,
    AttributeId,
    AttributeName,
    RespondentId,
    UtilityValue
)
SELECT al.Id AS AttributeLevelId,
       al.DisplayText AS AttributeLevelName,
       a.Id AS AttributeId,
       a.DisplayText AS AttributeName,
       usd.RespondentId,
       usd.Value AS UtilityValue
FROM dbo.Attribute a
    INNER JOIN dbo.AttributeLevel al
        ON al.AttributeId = a.Id
    INNER JOIN dbo.UtilityScoreData usd
        ON usd.AttributeLevelId = al.Id
WHERE a.StudyId = @studyId
      AND usd.RespondentId IN
          (
        (SELECT Id FROM @respondentIdType)
          )
      AND
      (
          (usd.Dimension IS NOT NULL
          AND usd.Dimension = @dimension)
      )
      OR
      (
          (usd.Dimension IS NULL
          AND @dimension = 1)
      );

SELECT * FROM #AllUtilityDataDTO
END
GO

DROP TABLE #AllUtilityDataDTO
END

</code>```

The SELECT Id FROM @respondentIdType should fetch all the respondent ids that is passed to the table-valued parameter from the code.
The problem lies after this. I'm unable to convert the list of integers to a dataTable type in order to pass the values as a table-valued parameter.

Here is the code that I'm using in C# -

The respondentIds being fetched as a list of integers(List) from a respository function -

```<code>var respondentIds = _studyRepository.GetFilteredRespondentsIds(studyId, filters, minRLH);

</code>```

I'm converting the ids that are being fetched into a datatable using the below converter by passing the respondentIds variable as a parameter -

```<code>ListtoDataTableConverter dataTableConverter = new ListtoDataTableConverter();
            DataTable respondentIdTable = dataTableConverter.ToDataTable(respondentIds);
</code>```
```<code>public class ListtoDataTableConverter
        {
            public DataTable ToDataTable<T>(List<T> items)
            {
                DataTable dataTable = new DataTable(typeof(T).Name);
                //Get all the properties
                PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (PropertyInfo prop in Props)
                {
                    //Setting column names as Property names
                    dataTable.Columns.Add(prop.Name);
                }
                foreach (T item in items)
                {
                    var values = new object[Props.Length];
                    for (int i = 0; i < Props.Length; i++)
                    {
                        //inserting property values to datatable rows
                        values[i] = Props[i].GetValue(item, null);
                    }
                    dataTable.Rows.Add(values);
                }
                //put a breakpoint here and check datatable
                return dataTable;
            }
        }
</code>```

Then creating a SqlCommand to execute the stored procedure and adding parameters along with their values.

```<code>using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                // Create a DataTable with the modified rows.
                DataTable addedrespondentIds = respondentIdTable.GetChanges();

                // Configure the SqlCommand and SqlParameter.
                SqlCommand insertCommand = new SqlCommand("GetSensitivityDataForDimensionProc", connection);
                insertCommand.CommandType = CommandType.StoredProcedure;
                SqlParameter respondentParam = insertCommand.Parameters.AddWithValue("@respondentIdType", addedrespondentIds);
                respondentParam.SqlDbType = SqlDbType.Structured;
                respondentParam.TypeName = "dbo.RespondentTypeTable";
                SqlParameter studyIdParam = insertCommand.Parameters.AddWithValue("@studyId", studyId);
                respondentParam.SqlDbType = SqlDbType.Int;
                SqlParameter dimensionParam = insertCommand.Parameters.AddWithValue("@dimension", dimension);
                respondentParam.SqlDbType = SqlDbType.Int;

                // Execute the command.
                insertCommand.ExecuteNonQuery();

                connection.Close();

            }
</code>```

Here is the stored procedure and table type classes that i'm using for this -

SP class

```<code>namespace XYZData.Repositories.SqlStoredProcedures
{
    [StoredProcedure("GetSensitivityDataForDimension")]
    public class GetSensitivityDataForDimensionProc
    {
        [StoredProcedureParameter(SqlDbType.Structured)]
        public DataTable RespondentIds { get; set; }

        [StoredProcedureParameter(SqlDbType.Int)]
        public int StudyId { get; set; }

        [StoredProcedureParameter(SqlDbType.Int)]
        public int Dimension { get; set; }
    }
}

</code>```

Table type class

```<code>namespace XYZData.Repositories.SqlUserDefinedTypes
{
    [UserDefinedTableType("[dbo].[RespondentTypeTable]")]
    public class RespondentTableType
    {
        [UserDefinedTableTypeColumn(1)]
        public Int Id { get; set; }
    }
}
</code>```

I tried converting the list of integers to dataTable but it is giving System.InvalidCastException: 'Failed to convert parameter value from a DataTable to a Int32.' error while running the application. How will I pass the list of integers to the table-valued parameter?

Body:
I'm using ASP.NET MVC Framework and SQL Server for this one.
I have created a table type which will have the list of ids coming from a variable in C#

CREATE TYPE [dbo].[RespondentTypeTable] AS TABLE
(
    Id INT NOT NULL
)

I have created a procedure to pass the table-valued parameter with the table-type created above in readonly mode and 2 integer parameters. The stored procedure will insert the records from the other joined tables mentioned in the select statement into a local temporary table allutilitydatadto and will get the results from the temp table and drop it after fetching the records.

CREATE PROCEDURE GetSensitivityDataForDimension(@respondentIdType [dbo].[RespondentTypeTable] READONLY, @studyId INT, @dimension INT )
AS
BEGIN

CREATE TABLE #AllUtilityDataDTO
(
    AttributeLevelId INT NOT NULL,
    AttributeLevelName NVARCHAR(MAX),
    AttributeId INT NOT NULL,
    AttributeName NVARCHAR(MAX),
    RespondentId INT NOT NULL,
    UtilityValue INT
);

BEGIN
INSERT INTO #AllUtilityDataDTO
(
    AttributeLevelId,
    AttributeLevelName,
    AttributeId,
    AttributeName,
    RespondentId,
    UtilityValue
)
SELECT al.Id AS AttributeLevelId,
       al.DisplayText AS AttributeLevelName,
       a.Id AS AttributeId,
       a.DisplayText AS AttributeName,
       usd.RespondentId,
       usd.Value AS UtilityValue
FROM dbo.Attribute a
    INNER JOIN dbo.AttributeLevel al
        ON al.AttributeId = a.Id
    INNER JOIN dbo.UtilityScoreData usd
        ON usd.AttributeLevelId = al.Id
WHERE a.StudyId = @studyId
      AND usd.RespondentId IN
          (
        (SELECT Id FROM @respondentIdType)
          )
      AND
      (
          (usd.Dimension IS NOT NULL
          AND usd.Dimension = @dimension)
      )
      OR
      (
          (usd.Dimension IS NULL
          AND @dimension = 1)
      );

SELECT * FROM #AllUtilityDataDTO
END
GO

DROP TABLE #AllUtilityDataDTO
END

The SELECT Id FROM @respondentIdType should fetch all the respondent ids that is passed to the table-valued parameter from the code.
The problem lies after this. I'm unable to convert the list of integers to a dataTable type in order to pass the values as a table-valued parameter.

Here is the code that I'm using in C# -

The respondentIds being fetched as a list of integers(List) from a respository function -

var respondentIds = _studyRepository.GetFilteredRespondentsIds(studyId, filters, minRLH);

I'm converting the ids that are being fetched into a datatable using the below converter by passing the respondentIds variable as a parameter -

ListtoDataTableConverter dataTableConverter = new ListtoDataTableConverter();
            DataTable respondentIdTable = dataTableConverter.ToDataTable(respondentIds);

public class ListtoDataTableConverter
        {
            public DataTable ToDataTable<T>(List<T> items)
            {
                DataTable dataTable = new DataTable(typeof(T).Name);
                //Get all the properties
                PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (PropertyInfo prop in Props)
                {
                    //Setting column names as Property names
                    dataTable.Columns.Add(prop.Name);
                }
                foreach (T item in items)
                {
                    var values = new object[Props.Length];
                    for (int i = 0; i < Props.Length; i++)
                    {
                        //inserting property values to datatable rows
                        values[i] = Props[i].GetValue(item, null);
                    }
                    dataTable.Rows.Add(values);
                }
                //put a breakpoint here and check datatable
                return dataTable;
            }
        }

Then creating a SqlCommand to execute the stored procedure and adding parameters along with their values.

using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                // Create a DataTable with the modified rows.
                DataTable addedrespondentIds = respondentIdTable.GetChanges();

                // Configure the SqlCommand and SqlParameter.
                SqlCommand insertCommand = new SqlCommand("GetSensitivityDataForDimensionProc", connection);
                insertCommand.CommandType = CommandType.StoredProcedure;
                SqlParameter respondentParam = insertCommand.Parameters.AddWithValue("@respondentIdType", addedrespondentIds);
                respondentParam.SqlDbType = SqlDbType.Structured;
                respondentParam.TypeName = "dbo.RespondentTypeTable";
                SqlParameter studyIdParam = insertCommand.Parameters.AddWithValue("@studyId", studyId);
                respondentParam.SqlDbType = SqlDbType.Int;
                SqlParameter dimensionParam = insertCommand.Parameters.AddWithValue("@dimension", dimension);
                respondentParam.SqlDbType = SqlDbType.Int;

                // Execute the command.
                insertCommand.ExecuteNonQuery();

                connection.Close();

            }

Here is the stored procedure and table type classes that i'm using for this -

SP class

namespace XYZData.Repositories.SqlStoredProcedures
{
    [StoredProcedure("GetSensitivityDataForDimension")]
    public class GetSensitivityDataForDimensionProc
    {
        [StoredProcedureParameter(SqlDbType.Structured)]
        public DataTable RespondentIds { get; set; }

        [StoredProcedureParameter(SqlDbType.Int)]
        public int StudyId { get; set; }

        [StoredProcedureParameter(SqlDbType.Int)]
        public int Dimension { get; set; }
    }
}

Table type class

namespace XYZData.Repositories.SqlUserDefinedTypes
{
    [UserDefinedTableType("[dbo].[RespondentTypeTable]")]
    public class RespondentTableType
    {
        [UserDefinedTableTypeColumn(1)]
        public Int Id { get; set; }
    }
}

I tried converting the list of integers to dataTable but it is giving System.InvalidCastException: 'Failed to convert parameter value from a DataTable to a Int32.' error while running the application. How will I pass the list of integers to the table-valued parameter?


问:
Druid {"error":"Basic authenticator with name [MyBasicMetadataAuthenticator] does not exist."}
I have done a basic setup of druid cluster on my local machine with basic auth properties like below

```<code># Druid basic security
druid.auth.authenticatorChain=["MyBasicMetadataAuthenticator"]
druid.auth.authenticator.MyBasicMetadataAuthenticator.type=basic

# Default password for 'admin' user, should be changed for production.
druid.auth.authenticator.MyBasicMetadataAuthenticator.initialAdminPassword=password1

# Default password for internal 'druid_system' user, should be changed for production.
druid.auth.authenticator.MyBasicMetadataAuthenticator.initialInternalClientPassword=password2

# Uses the metadata store for storing users, you can use authentication API to create new users and grant permissions
druid.auth.authenticator.MyBasicMetadataAuthenticator.credentialsValidator.type=metadata

# If true and the request credential doesn't exists in this credentials store, the request will proceed to next Authenticator in the chain.
druid.auth.authenticator.MyBasicMetadataAuthenticator.skipOnFailure=false

druid.auth.authenticator.MyBasicMetadataAuthenticator.authorizerName=MyBasicMetadataAuthorizer

# Escalator
druid.escalator.type=basic
druid.escalator.internalClientUsername=druid_system
druid.escalator.internalClientPassword=password2
druid.escalator.authorizerName=MyBasicMetadataAuthorizer

druid.auth.authorizers=["MyBasicMetadataAuthorizer"]

druid.auth.authorizer.MyBasicMetadataAuthorizer.type=basic
</code>```

and if see my services, all are running like below

```<code>> CONTAINER ID   IMAGE                   COMMAND                  CREATED          STATUS                   PORTS                                                      NAMES
8c16553331b6   apache/druid:24.0.0     "/druid.sh broker"       43 minutes ago   Up 18 seconds            0.0.0.0:8082->8082/tcp                                     broker
c1a1fc119ee1   apache/druid:24.0.0     "/druid.sh router"       43 minutes ago   Up 18 seconds            0.0.0.0:8888->8888/tcp                                     router
5a20e7da110c   apache/druid:24.0.0     "/druid.sh middleMan…"   43 minutes ago   Up 18 seconds            0.0.0.0:8091->8091/tcp, 0.0.0.0:8100-8105->8100-8105/tcp   middlemanager
ef6e49b0815b   apache/druid:24.0.0     "/druid.sh historical"   43 minutes ago   Up 18 seconds            0.0.0.0:8083->8083/tcp                                     historical
f2b4008edd8e   apache/druid:24.0.0     "/druid.sh coordinat…"   43 minutes ago   Up 20 seconds            0.0.0.0:8081->8081/tcp                                     coordinator
8eff9a6add0e   postgres:latest         "docker-entrypoint.s…"   17 hours ago     Up 21 seconds            0.0.0.0:5433->5432/tcp                                     postgres
eecb2afe81e7   zookeeper:3.5           "/docker-entrypoint.…"   17 hours ago     Up 21 seconds            2888/tcp, 3888/tcp, 0.0.0.0:2181->2181/tcp, 8080/tcp       zookeeper
</code>```

and if i am hitting any of api of druid

```<code>$ curl -H "Content-type: application/json" -u admin:password1  -d "{\"password\":\"password123\"}" -X POST http://66.94.107.105:8081/druid-ext/basic-security/authentication/db/MyBasicMetadataAuthenticator/users/admin/credentials;
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   114    0    88  100    26    125     37 --:--:-- --:--:-- --:--:--   162{"error":"Basic authenticator with name [MyBasicMetadataAuthenticator] does not exist."}
</code>```

Body:
I have done a basic setup of druid cluster on my local machine with basic auth properties like below

# Druid basic security
druid.auth.authenticatorChain=["MyBasicMetadataAuthenticator"]
druid.auth.authenticator.MyBasicMetadataAuthenticator.type=basic

# Default password for 'admin' user, should be changed for production.
druid.auth.authenticator.MyBasicMetadataAuthenticator.initialAdminPassword=password1

# Default password for internal 'druid_system' user, should be changed for production.
druid.auth.authenticator.MyBasicMetadataAuthenticator.initialInternalClientPassword=password2

# Uses the metadata store for storing users, you can use authentication API to create new users and grant permissions
druid.auth.authenticator.MyBasicMetadataAuthenticator.credentialsValidator.type=metadata

# If true and the request credential doesn't exists in this credentials store, the request will proceed to next Authenticator in the chain.
druid.auth.authenticator.MyBasicMetadataAuthenticator.skipOnFailure=false

druid.auth.authenticator.MyBasicMetadataAuthenticator.authorizerName=MyBasicMetadataAuthorizer

# Escalator
druid.escalator.type=basic
druid.escalator.internalClientUsername=druid_system
druid.escalator.internalClientPassword=password2
druid.escalator.authorizerName=MyBasicMetadataAuthorizer

druid.auth.authorizers=["MyBasicMetadataAuthorizer"]

druid.auth.authorizer.MyBasicMetadataAuthorizer.type=basic

and if see my services, all are running like below

> CONTAINER ID   IMAGE                   COMMAND                  CREATED          STATUS                   PORTS                                                      NAMES
8c16553331b6   apache/druid:24.0.0     "/druid.sh broker"       43 minutes ago   Up 18 seconds            0.0.0.0:8082->8082/tcp                                     broker
c1a1fc119ee1   apache/druid:24.0.0     "/druid.sh router"       43 minutes ago   Up 18 seconds            0.0.0.0:8888->8888/tcp                                     router
5a20e7da110c   apache/druid:24.0.0     "/druid.sh middleMan…"   43 minutes ago   Up 18 seconds            0.0.0.0:8091->8091/tcp, 0.0.0.0:8100-8105->8100-8105/tcp   middlemanager
ef6e49b0815b   apache/druid:24.0.0     "/druid.sh historical"   43 minutes ago   Up 18 seconds            0.0.0.0:8083->8083/tcp                                     historical
f2b4008edd8e   apache/druid:24.0.0     "/druid.sh coordinat…"   43 minutes ago   Up 20 seconds            0.0.0.0:8081->8081/tcp                                     coordinator
8eff9a6add0e   postgres:latest         "docker-entrypoint.s…"   17 hours ago     Up 21 seconds            0.0.0.0:5433->5432/tcp                                     postgres
eecb2afe81e7   zookeeper:3.5           "/docker-entrypoint.…"   17 hours ago     Up 21 seconds            2888/tcp, 3888/tcp, 0.0.0.0:2181->2181/tcp, 8080/tcp       zookeeper

and if i am hitting any of api of druid

$ curl -H "Content-type: application/json" -u admin:password1  -d "{\"password\":\"password123\"}" -X POST http://66.94.107.105:8081/druid-ext/basic-security/authentication/db/MyBasicMetadataAuthenticator/users/admin/credentials;
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   114    0    88  100    26    125     37 --:--:-- --:--:-- --:--:--   162{"error":"Basic authenticator with name [MyBasicMetadataAuthenticator] does not exist."}


问:
How to Implement React Server Side Rendering in AWS ? I'm using AWS Amplify to host React App
I need to enable React Server Side Rendering in AWS Amplify . I have seen a documentation that uses cloudfront and S3 bucket . Anybody know how to make it possible using Amplify ?

I cannot find any documentation or any other support regarding this


问:
How I do to make the Notebook use all space below 'Flota'?
The notebook does not expand and it looks so small.

I have tried with grid geometry and pack(fill='both', expand='yes'), that didn't worked. I know my code is in spanish but i think it is understandable for english speakers.

I also tried to create a frame below 'Flota' tittle and make the notebook pack there but it dosen't work.

The foto i have attached is how it looks now with the code I'm sharing.

```<code>import tkinter as tk
from tkinter import ttk

# screen and root settings
# crear ventana
root = tk.Tk()

# info de la pantalla
width= root.winfo_screenwidth()
height= root.winfo_screenheight()

# tamaño de la ventana
"""root.geometry("%dx%d" % (width, height))"""
root.title("Gestor de Flotas - Tallers Citoler")
root.geometry("1600x900")

# ventana en mitad de pantalla
pwidth = round(width/2-1600/2)
pheight = round(height/2-900/2)
root.geometry(str(1600)+"x"+str(900)+"+"+str(pwidth)+"+"+str(pheight))

# no cambiar tamaño ventana
root.resizable(False, False)

# titulo de ventana
root.title("Tallers Citoler - Gestor de flotas")

# color de fondo de la ventana, de momento no pongo ninguno
root.config(bg='blue')
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)

###############################################################
# TOP SIDE
# etiqueta titulo (tittle label)
frame_titulo = tk.Frame(root, bd=1, relief=tk.FLAT,bg='black')
frame_titulo.grid(sticky='N', columnspan=2)

etiqueta_titulo = tk.Label(frame_titulo, text='Tallers Citoler - Sistema de Gestion de Flotas', fg='black', font=('Dosis', 48), bg= 'darksalmon', padx=147, pady=1)
etiqueta_titulo.grid(row=0,column=0, columnspan=2, sticky='N')

###############################################################
# LEFT SIDE
# left frame
panel_izquierdo = tk.Frame(root, bd=1, relief=tk.FLAT, bg='black')
panel_izquierdo.grid(row=1, column=0)

fondo_izquierdo = tk.Label(panel_izquierdo, padx=270, pady=401, bg='white')
fondo_izquierdo.grid()

# 'flota' label
frame_cartel_flota = tk.Frame(panel_izquierdo, bd=1, relief=tk.FLAT, bg='black')
frame_cartel_flota.grid(row=0, column=0, sticky='N')

cartel_flota = tk.Label(frame_cartel_flota, text='Flota', font=('Dosis', 34), bg= '#EED5B7', padx=220)
cartel_flota.grid(row=0,column=0, sticky='N')

# panel botones y flota (grey panel below 'Flota' tittle)
frame_botones_flota = tk.Frame(panel_izquierdo, bd=1, relief=tk.FLAT, bg='black')
frame_botones_flota.grid(row=0, column=0, sticky='S')

"""cartel_botones_flota = tk.Label(frame_botones_flota, bg= 'lightgrey', padx=270, pady=371)
cartel_botones_flota.grid(row=0,column=0)"""

# Notebook
# Crear pestañas flota
notebook_flota = ttk.Notebook(frame_botones_flota)
notebook_flota.grid(column=0, row=1, sticky='N')

p1 = ttk.Frame(notebook_flota)
p2 = ttk.Frame(notebook_flota)
p3 = ttk.Frame(notebook_flota)

# agregar pestañas
notebook_flota.add(p1, text='Carretillas')
notebook_flota.add(p2, text='Elevadores')
notebook_flota.add(p3, text='Vehiculos')

###############################################################
# RIGHT SIDE
# right frame
panel_derecho = tk.Frame(root, bd=1, relief=tk.FLAT, bg='black')
panel_derecho.grid(row=1, column=1)

fondo_derecho = tk.Label(panel_derecho, padx=525, pady=401, bg='red')
fondo_derecho.grid()

# 'recordatorios' label
frame_cartel_recordatorios = tk.Frame(panel_derecho, bd=1, relief=tk.FLAT, bg='black')
frame_cartel_recordatorios.grid(row=0, column=0, sticky='N')

cartel_recordatorios = tk.Label(frame_cartel_recordatorios, text='Recordatorios', font=('Dosis', 34), bg= 'khaki', padx=384)
cartel_recordatorios.grid(row=0,column=0, sticky='N')

#panel info recordatorios (big yellow label)
frame_info_recordatorios = tk.Frame(panel_derecho, bd=1, relief=tk.FLAT, bg='black')
frame_info_recordatorios.grid(row=0, column=0, sticky='S')

cartel_info_recordatorios = tk.Label(frame_info_recordatorios, bg= 'yellow', padx=525, pady=371)
cartel_info_recordatorios.grid(row=0,column=0)

###############################################################
# ejecucion de la ventana
root.mainloop()
</code>```

Body:
The notebook does not expand and it looks so small.

I have tried with grid geometry and pack(fill='both', expand='yes'), that didn't worked. I know my code is in spanish but i think it is understandable for english speakers.

I also tried to create a frame below 'Flota' tittle and make the notebook pack there but it dosen't work.

The foto i have attached is how it looks now with the code I'm sharing.

import tkinter as tk
from tkinter import ttk

# screen and root settings
# crear ventana
root = tk.Tk()

# info de la pantalla
width= root.winfo_screenwidth()
height= root.winfo_screenheight()

# tamaño de la ventana
"""root.geometry("%dx%d" % (width, height))"""
root.title("Gestor de Flotas - Tallers Citoler")
root.geometry("1600x900")

# ventana en mitad de pantalla
pwidth = round(width/2-1600/2)
pheight = round(height/2-900/2)
root.geometry(str(1600)+"x"+str(900)+"+"+str(pwidth)+"+"+str(pheight))

# no cambiar tamaño ventana
root.resizable(False, False)

# titulo de ventana
root.title("Tallers Citoler - Gestor de flotas")

# color de fondo de la ventana, de momento no pongo ninguno
root.config(bg='blue')
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)

###############################################################
# TOP SIDE
# etiqueta titulo (tittle label)
frame_titulo = tk.Frame(root, bd=1, relief=tk.FLAT,bg='black')
frame_titulo.grid(sticky='N', columnspan=2)

etiqueta_titulo = tk.Label(frame_titulo, text='Tallers Citoler - Sistema de Gestion de Flotas', fg='black', font=('Dosis', 48), bg= 'darksalmon', padx=147, pady=1)
etiqueta_titulo.grid(row=0,column=0, columnspan=2, sticky='N')

###############################################################
# LEFT SIDE
# left frame
panel_izquierdo = tk.Frame(root, bd=1, relief=tk.FLAT, bg='black')
panel_izquierdo.grid(row=1, column=0)

fondo_izquierdo = tk.Label(panel_izquierdo, padx=270, pady=401, bg='white')
fondo_izquierdo.grid()

# 'flota' label
frame_cartel_flota = tk.Frame(panel_izquierdo, bd=1, relief=tk.FLAT, bg='black')
frame_cartel_flota.grid(row=0, column=0, sticky='N')

cartel_flota = tk.Label(frame_cartel_flota, text='Flota', font=('Dosis', 34), bg= '#EED5B7', padx=220)
cartel_flota.grid(row=0,column=0, sticky='N')

# panel botones y flota (grey panel below 'Flota' tittle)
frame_botones_flota = tk.Frame(panel_izquierdo, bd=1, relief=tk.FLAT, bg='black')
frame_botones_flota.grid(row=0, column=0, sticky='S')

"""cartel_botones_flota = tk.Label(frame_botones_flota, bg= 'lightgrey', padx=270, pady=371)
cartel_botones_flota.grid(row=0,column=0)"""

# Notebook
# Crear pestañas flota
notebook_flota = ttk.Notebook(frame_botones_flota)
notebook_flota.grid(column=0, row=1, sticky='N')

p1 = ttk.Frame(notebook_flota)
p2 = ttk.Frame(notebook_flota)
p3 = ttk.Frame(notebook_flota)

# agregar pestañas
notebook_flota.add(p1, text='Carretillas')
notebook_flota.add(p2, text='Elevadores')
notebook_flota.add(p3, text='Vehiculos')

###############################################################
# RIGHT SIDE
# right frame
panel_derecho = tk.Frame(root, bd=1, relief=tk.FLAT, bg='black')
panel_derecho.grid(row=1, column=1)

fondo_derecho = tk.Label(panel_derecho, padx=525, pady=401, bg='red')
fondo_derecho.grid()

# 'recordatorios' label
frame_cartel_recordatorios = tk.Frame(panel_derecho, bd=1, relief=tk.FLAT, bg='black')
frame_cartel_recordatorios.grid(row=0, column=0, sticky='N')

cartel_recordatorios = tk.Label(frame_cartel_recordatorios, text='Recordatorios', font=('Dosis', 34), bg= 'khaki', padx=384)
cartel_recordatorios.grid(row=0,column=0, sticky='N')

#panel info recordatorios (big yellow label)
frame_info_recordatorios = tk.Frame(panel_derecho, bd=1, relief=tk.FLAT, bg='black')
frame_info_recordatorios.grid(row=0, column=0, sticky='S')

cartel_info_recordatorios = tk.Label(frame_info_recordatorios, bg= 'yellow', padx=525, pady=371)
cartel_info_recordatorios.grid(row=0,column=0)

###############################################################
# ejecucion de la ventana
root.mainloop()


问:
Boto3 presigned_url works only without "X-Amz-Algorithm" params
I am trying to generate presigned url using boto3 in django. When I am trying to upload the file using the URL through Postman or CURL, it fails with "SignatureDoesNotMatch". But when I try the same link removing the "X-Amz-Algorithm" parameter from the generated URL, it works fine. Below are the details of my s3 bucket Policy, CORS and the code. Please note I masked few confidential fields with "###<name>###"

Bucket policy

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": [
                "###<arn>###",
                "###<arn>###/*"
            ]
        }
    ]
}
</code>```

Bucket policy

```<code>[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "POST",
            "PUT"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 2592000
    }
]
</code>```

Python Code

```<code>s3_client = boto3.client(settings.S3_RESOURCE,region_name=settings.AWS_REGION, # eu-west-1
                         config=botocore.client.Config(signature_version=settings.AWS_S3_SIGNATURE_VERSION, # s3v4
                                                       s3={'addressing_style': settings.AWS_S3_ADDRESSING_STYLE} # virtual
                        )

preasigned_url = s3_client.generate_presigned_url(ClientMethod='put_object',
                                                    ExpiresIn=settings.AWS_PRESIGNED_EXPIRY,
                                                    Params={'Bucket': settings.AWS_OPEN_UPLOAD_BUCKET,
                                                            'Key': file_upload_folder + audiofile_name,
                                                            'ACL': settings.AWS_DEFAULT_ACL, # private
                                                            'ContentType': 'audio/mpeg'
                                                            }
                                                    )

</code>```

Generated URL

https://s3.eu-west-1.amazonaws.com/###\<bucket/key>###?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=###<credential>###eu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221220T114721Z&X-Amz-Expires=604799&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-acl&X-Amz-Signature=###Signature###

When I try to upload with the above URL using Postman or CURL, I am receiving the below error.

```<code>    <Code>SignatureDoesNotMatch</Code>
    <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>
</code>```

But it works fine if I remove the "X-Amz-Algorithm" key/value from the URL.

https://s3.eu-west-1.amazonaws.com/###\<bucket/key>###?X-Amz-Credential=###<credential>###eu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221220T114721Z&X-Amz-Expires=604799&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-acl&X-Amz-Signature=###Signature###

Is there anything I'm missing while generating the pre_signed_url or while upload ?

Body:
I am trying to generate presigned url using boto3 in django. When I am trying to upload the file using the URL through Postman or CURL, it fails with "SignatureDoesNotMatch". But when I try the same link removing the "X-Amz-Algorithm" parameter from the generated URL, it works fine. Below are the details of my s3 bucket Policy, CORS and the code. Please note I masked few confidential fields with "###<name>###"

Bucket policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": [
                "###<arn>###",
                "###<arn>###/*"
            ]
        }
    ]
}

Bucket policy

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "POST",
            "PUT"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 2592000
    }
]

Python Code

s3_client = boto3.client(settings.S3_RESOURCE,region_name=settings.AWS_REGION, # eu-west-1
                         config=botocore.client.Config(signature_version=settings.AWS_S3_SIGNATURE_VERSION, # s3v4
                                                       s3={'addressing_style': settings.AWS_S3_ADDRESSING_STYLE} # virtual
                        )

preasigned_url = s3_client.generate_presigned_url(ClientMethod='put_object',
                                                    ExpiresIn=settings.AWS_PRESIGNED_EXPIRY,
                                                    Params={'Bucket': settings.AWS_OPEN_UPLOAD_BUCKET,
                                                            'Key': file_upload_folder + audiofile_name,
                                                            'ACL': settings.AWS_DEFAULT_ACL, # private
                                                            'ContentType': 'audio/mpeg'
                                                            }
                                                    )

Generated URL

https://s3.eu-west-1.amazonaws.com/###\<bucket/key>###?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=###<credential>###eu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221220T114721Z&X-Amz-Expires=604799&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-acl&X-Amz-Signature=###Signature###

When I try to upload with the above URL using Postman or CURL, I am receiving the below error.

    SignatureDoesNotMatch
    <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>

But it works fine if I remove the "X-Amz-Algorithm" key/value from the URL.

https://s3.eu-west-1.amazonaws.com/###\<bucket/key>###?X-Amz-Credential=###<credential>###eu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221220T114721Z&X-Amz-Expires=604799&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-acl&X-Amz-Signature=###Signature###

Is there anything I'm missing while generating the pre_signed_url or while upload ?


问:
Terminal cursor in VSCode obscures the command I type so I can't fully see it
When I start to type a command in VSCode terminal, the cursor sort of multiplies and partly obscures the command, so I can't fully read it, as on this picture (it reads "git status"). Besides, if I try out different styles in the settings, the cursor won't change  - it remains the same.

VSCode 1.74.1/Mac OS High Sierra 10.13
enter image description here

Changing fonts doesn't help. I tried to reinstall the app, but it's all the same.


问:
How to get the content of ckeditor5 when user presses Enter in the editor?
Now I am saving the content of the editor upon blur

```<code>                       onBlur={(event, editor) => {
                            const data: any = editor.getData();
                            void onCKEditorEntityBlur("Editing", data);
                        }}
</code>```

Users prefer I use Enter instead.
It tried

```<code>                     onKeyDownCapture={(event, editor) => {
                            const data: any = editor.getData();
                            void onNoteKeyDownCapture("Editing", data);
                        }}
</code>```

But pressings Enter, does not go to the onNoteKeyDownCapture function
What is the best way to capture the Enter event?
Thank you

Body:
Now I am saving the content of the editor upon blur

                       onBlur={(event, editor) => {
                            const data: any = editor.getData();
                            void onCKEditorEntityBlur("Editing", data);
                        }}

Users prefer I use Enter instead.
It tried

                     onKeyDownCapture={(event, editor) => {
                            const data: any = editor.getData();
                            void onNoteKeyDownCapture("Editing", data);
                        }}

But pressings Enter, does not go to the onNoteKeyDownCapture function
What is the best way to capture the Enter event?
Thank you


问:
Why does logic of iff(null, , ) depend on type of the operands?
```<code>print iff(1.0 > real(null), 1.0, -1.0), iff(1.0 > real(null), true, false)
--------------------------------------------------------------------------
-1    |   <null>
</code>```

Though I did not find it documented, since the logic of where treats null as false, it is logical that iff() goes to ifFalse expression. However, I find it strange that with boolean if-expressions it evaluates to null.

Body:
print iff(1.0 > real(null), 1.0, -1.0), iff(1.0 > real(null), true, false)
--------------------------------------------------------------------------
-1    |   <null>

Though I did not find it documented, since the logic of where treats null as false, it is logical that iff() goes to ifFalse expression. However, I find it strange that with boolean if-expressions it evaluates to null.


问:
Scriban - $ prefixed vars are not being parsed
I have been trying to include some system vars prefixed with $ like $SYSTEM_VAR but these vars not being parsed, only if i remove the $ sign. I have also tried with @ symbol with similar results.

Thanks,


问:
unknown ping error in Unity when calling a punRpc
we have this error which comes up exactly every 5 seconds and I couldn't find anywhere infos about it or how to fix it.
screenshot of the error

```<code>RPC method 'RPC_ReceivePing' found on object with PhotonView 1001 but has wrong parameters. Implement as 'RPC_ReceivePing(Int32)'. PhotonMessageInfo is optional as final parameter.Return type must be void or IEnumerator (if you enable RunRpcCoroutines).
UnityEngine.Debug:LogErrorFormat (UnityEngine.Object,string,object[])
Photon.Pun.PhotonNetwork:ExecuteRpc (ExitGames.Client.Photon.Hashtable,Photon.Realtime.Player) (at Assets/Plugins/PhotonUnityNetworking/Code/PhotonNetworkPart.cs:646)
Photon.Pun.PhotonNetwork:RPC (Photon.Pun.PhotonView,string,Photon.Pun.RpcTarget,Photon.Realtime.Player,bool,object[]) (at Assets/Plugins/PhotonUnityNetworking/Code/PhotonNetworkPart.cs:1266)
Photon.Pun.PhotonNetwork:RPC (Photon.Pun.PhotonView,string,Photon.Pun.RpcTarget,bool,object[]) (at Assets/Plugins/PhotonUnityNetworking/Code/PhotonNetwork.cs:2940)
Photon.Pun.PhotonView:RPC (string,Photon.Pun.RpcTarget,object[]) (at Assets/Plugins/PhotonUnityNetworking/Code/PhotonView.cs:609)
FirstGearGames.PhotonNetworking.Utilities.MasterClientMonitor:CheckSendPing () (at Assets/01_Batvision/05_Scripts/GameLogic/MasterClientMonitor.cs:299)
FirstGearGames.PhotonNetworking.Utilities.MasterClientMonitor:Update () (at Assets/01_Batvision/05_Scripts/GameLogic/MasterClientMonitor.cs:127)
</code>```

it's telling me that some RPC parameter is wrong but I checked every single one in the project and can't seem to find what they mean.
screenshot of all rpc

here's an example of one of the RPC
example of my rpc

```<code>void Update()
{
   if (HasCrossedTheRing == true)
    {

         photonView.RPC("ConfirmRing", RpcTarget.All);
         PhotonNetwork.SendAllOutgoingCommands();

    }
}

[PunRPC]
public void ConfirmRing()
{
    if (HasCrossedTheRing == true)
    {
        mainRingTimerObj.StopTimer();
        NextInsectObjCin.LookAtRoots();
        rootsAdd.addColorRoot();
        HasCrossedTheRing = false;

    }
}
</code>```

would anyone have an idea what the error means or how I can find on which RPC the problem comes from?

thanks for your time,

HD

I tried deleting all unused RPC in the project and check that it wasn't a spelling error and the so called bool "RunRpcCoroutines" is already set to false

the MasterClientMonitor.cs

```<code>using UnityEngine;
using System.Collections.Generic;
using Photon.Pun;
using Photon.Realtime;
using System.Linq;

namespace FirstGearGames.PhotonNetworking.Utilities
{

    public class MasterClientMonitor : MonoBehaviourPunCallbacks
    {
        #region Types.
        /// <summary>
        /// Holds a players ping.
        /// </summary>
        private class PlayerPing
        {
            public PlayerPing(Player player, int ping)
            {
                Player = player;
                _pings.Add(ping);
            }
            /// <summary>
            /// Last time a ping was set for this player.
            /// </summary>
            public float LastUpdatedTime { get; private set; } = -1f;
            /// <summary>
            /// Player this instance is for.
            /// </summary>
            public readonly Player Player;
            /// <summary>
            /// Pings for this player.
            /// </summary>
            private List<int> _pings = new List<int>();
            /// <summary>
            /// Maximum number of ping history to allow.
            /// </summary>
            private const int MAXIMUM_RECORDED_PINGS = 6;

            /// <summary>
            /// Returns the average ping for this player. Returns -1f if recorded ping quantity is not at maximum recorded pings.
            /// </summary>
            /// <returns></returns>
            public int ReturnAveragePing()
            {
                //Not enough pings to consider an average yet.
                if (_pings.Count < MAXIMUM_RECORDED_PINGS)
                {
                    return -1;
                }
                //Has enough pings to return average.
                else
                {
                    int sum = _pings.Sum();
                    return Mathf.CeilToInt(sum / _pings.Count);
                }
            }

            /// <summary>
            /// Adds a ping for this player. Replaces oldest ping if at maximum recorded pings.
            /// </summary>
            /// <param name="value"></param>
            public void AddPing(int value)
            {
                //If at max pings remove the first entry.
                if (_pings.Count >= MAXIMUM_RECORDED_PINGS)
                    _pings.RemoveAt(0);

                _pings.Add(value);
                LastUpdatedTime = Time.unscaledTime;
            }
        }
        #endregion

        #region Private.
        /// <summary>
        /// List of player pings.
        /// </summary>
        private List<PlayerPing> _playerPings = new List<PlayerPing>();
        /// <summary>
        /// Next time to check for a high ping on master client.
        /// </summary>
        private float _nextCheckChangeMaster = 0f;
        /// <summary>
        /// Number of times in a row the current master client has had a significantly higher ping.
        /// </summary>
        private int _consequtiveHighPingCount = 0;
        /// <summary>
        /// True if received a master client change request. This is only set on master client.
        /// </summary>
        private bool _pendingMasterChange = false;
        /// <summary>
        /// Time a takeover request was sent. -1f if no takeover request is active.
        /// </summary>
        private float _takeoverRequestTime = -1f;
        /// <summary>
        /// Next time to send ping for this client.
        /// </summary>
        private float _nextSendPingTime = 0f;
        #endregion

        #region Const.
        /// <summary>
        /// How many times in a row the current masters ping must be significantly higher than others to forfeit master client.
        /// </summary>
        private const int HIGH_PING_TURNOVER_REQUIREMENT = 3;
        /// <summary>
        /// Mimimum current master client pings must be higher than lowest pinging player to be considered significantly higher.
        /// </summary>
        private const int MINIMUM_PING_DIFFERENCE = 50;
        /// <summary>
        /// How often to check for lowest pings. Masterclient must have a high ping after HIGH_PING_TURNOVER_REQUIREMENT times.
        /// </summary>
        private const float PING_CHECK_INTERVAL = 5f;
        /// <summary>
        /// Time master client has to grant a takeover request before it's taken forcefully. It's preferred that the master grants the request to prevent multiple takeovers in a short duration, but when master client is laggy or broken this may not be possible.
        /// </summary>
        private const float TAKEOVER_REQUEST_TIMEOUT = 3f;
        /// <summary>
        /// How frequently to send this clients ping.
        /// </summary>
        private const float SEND_PING_INTERVAL = 5f;
        #endregion

        private void Update()
        {
            CheckSendPing();
            CheckChangeMaster();
            CheckTakeoverTimeout();
        }

        public override void OnPlayerLeftRoom(Player otherPlayer)
        {
            //See if player is in player pings. If so remove them.
            int index = _playerPings.FindIndex(x => x.Player == otherPlayer);
            if (index != -1)
                _playerPings.RemoveAt(index);
        }

        public override void OnMasterClientSwitched(Player newMasterClient)
        {
            base.OnMasterClientSwitched(newMasterClient);
            //Unset pending master change.
            _pendingMasterChange = false;
            //Reset takeover data.
            _takeoverRequestTime = -1f;
            _consequtiveHighPingCount = 0;
        }

        /// <summary>
        /// Checks if a takeover needs to be forced. Usually occurs when the master client doesn't respond in time.
        /// </summary>
        private void CheckTakeoverTimeout()
        {
            //No takeover in progress.
            if (_takeoverRequestTime == -1f)
                return;

            //Master client request timed out. Takeover forcefully.
            if ((Time.unscaledTime - _takeoverRequestTime) > TAKEOVER_REQUEST_TIMEOUT)
            {
                _takeoverRequestTime = -1f;
                SetNewMaster(PhotonNetwork.LocalPlayer);
            }
        }

        /// <summary>
        /// Sets a new master client.
        /// </summary>
        /// <param name="newMaster"></param>
        private void SetNewMaster(Player newMaster, bool resetHighPingCount = true)
        {
            if (resetHighPingCount)
                _consequtiveHighPingCount = 0;
            //Set new master and use takeover.
            PhotonNetwork.SetMasterClient(newMaster);
        }

        /// <summary>
        /// Checks to change master if the current master is significantly more laggy than other players.
        /// </summary>
        /// <returns></returns>
        private void CheckChangeMaster()
        {
            //Network conditions not met.
            if (!PhotonNetwork.IsConnected || !PhotonNetwork.InRoom || PhotonNetwork.IsMasterClient)
                return;
            //Takeover already in progress.
            if (_takeoverRequestTime != -1f)
                return;
            //Too recent since last check.
            if (Time.time < _nextCheckChangeMaster)
                return;

            //Next time to check pings.
            _nextCheckChangeMaster = Time.time + PING_CHECK_INTERVAL;

            /* Players should already be removed when leaving the room.
             * This is just an extra precautionary. */
            RemoveNullPlayers();

            //Get list of all players.
            Player[] players = PhotonNetwork.PlayerList;
            //If only one player.
            if (players.Length <= 1)
                return;

            int lowestAverageIndex = -1;
            int lowestAveragePing = -1;
            int masterPing = -1;
            int masterIndex = -1;

            foreach (Player player in players)
            {
                int pingsIndex = _playerPings.FindIndex(x => x.Player == player);
                //Not found in players pings.
                if (pingsIndex == -1)
                    continue;

                //If player being checked is this client.
                if (player == PhotonNetwork.LocalPlayer)
                {
                    //If this client hasn't sent a ping in awhile don't even try to takeover.
                    if ((Time.unscaledTime - _playerPings[pingsIndex].LastUpdatedTime) >= (SEND_PING_INTERVAL * 2))
                        return;
                }

                //Get average.
                int averagePing = _playerPings[pingsIndex].ReturnAveragePing();
                //If average isn't -1 then enough pings have been sent to calculate an average.
                if (averagePing != -1)
                {
                    /* If average ping is lowest than the current lowest or
                     * the lowest average index is -1 (which means unset) then
                     * set as new lowest average. */
                    if (averagePing < lowestAveragePing || lowestAverageIndex == -1)
                    {
                        lowestAveragePing = averagePing;
                        lowestAverageIndex = pingsIndex;
                    }
                    //If player being checked is master client.
                    if (_playerPings[pingsIndex].Player.IsMasterClient)
                    {
                        masterIndex = pingsIndex;

                        /* If master client hasn't send a ping within a reasonable time then
                         * set the master clients ping unrealistically high to force a high
                         * consequtive ping count. */
                        if ((Time.unscaledTime - _playerPings[masterIndex].LastUpdatedTime) >= (SEND_PING_INTERVAL * 2))
                            masterPing = 999999999;
                        //Otherwise set to average ping.
                        else
                            masterPing = averagePing;
                    }
                }
            }

            //If the lowest ping index couldn't be found.
            if (lowestAverageIndex == -1)
                return;
            //Master index couldn't be found.
            if (masterIndex == -1)
                return;
            /* If the lowest ping index isn't this client then
             * don't proceed further, let the lowest pinging player
             * try the take over when the time comes. */
            if (_playerPings[lowestAverageIndex].Player != PhotonNetwork.LocalPlayer)
                return;

            /* If here this client is the lowest pinging player. */

            float masterPingDifference = (masterPing - lowestAveragePing);
            //If master ping is difference is high enough to change master client.
            if (masterPingDifference > MINIMUM_PING_DIFFERENCE)
                _consequtiveHighPingCount++;
            //master ping not too much higher.
            else
                _consequtiveHighPingCount = 0;

            //If high ping 3 times in a row then request setting a new master.
            if (_consequtiveHighPingCount >= 3)
            {
                _takeoverRequestTime = Time.unscaledTime;
                base.photonView.RPC("RPC_RequestMasterClient", RpcTarget.MasterClient, _playerPings[lowestAverageIndex].Player);
            }
        }

        /// <summary>
        /// Sends ping to all players including self.
        /// </summary>
        private void CheckSendPing()
        {
            if (Time.unscaledTime < _nextSendPingTime)
                return;

            _nextSendPingTime = Time.unscaledTime + SEND_PING_INTERVAL;

            base.photonView.RPC("RPC_ReceivePing", RpcTarget.All, PhotonNetwork.GetPing());
        }

        /// <summary>
        /// Receives a ping for the specified player.
        /// </summary>
        /// <param name="player"></param>
        /// <param name="ping"></param>
        [PunRPC]
        private void RPC_ReceivePing(Player player, int ping)
        {
            int index = _playerPings.FindIndex(x => x.Player == player);
            if (index == -1)
                _playerPings.Add(new PlayerPing(player, ping));
            else
                _playerPings[index].AddPing(ping);
        }

        /// <summary>
        /// Removes null players from player pings list.
        /// </summary>
        private void RemoveNullPlayers()
        {
            for (int i = 0; i < _playerPings.Count; i++)
            {
                //If null player remove from list and decrease i.
                if (_playerPings[i].Player == null)
                {
                    _playerPings.RemoveAt(i);
                    i--;
                }
            }
        }

        /// <summary>
        /// Request releasing the master client to the requestor.
        /// </summary>
        /// <param name="requestor">Player requesting the change.</param>
        /// Master client required.
        [PunRPC]
        private void RPC_RequestMasterClient(Player requestor)
        {
            //A change is already pending.
            if (_pendingMasterChange)
                return;
            //If not master.
            if (!PhotonNetwork.IsMasterClient)
                return;

            _pendingMasterChange = true;
            //RPC to allow change.
            base.photonView.RPC("RPC_MasterClientGranted", requestor);
        }

        /// <summary>
        /// Received on a player which may takeover as master client.
        /// </summary>
        [PunRPC]
        private void RPC_MasterClientGranted()
        {
            //Set new master as self.
            SetNewMaster(PhotonNetwork.LocalPlayer);
        }

        /// <summary>
        /// Called when the game gains or loses focus.
        /// </summary>
        /// <param name="pause"></param>
        private void OnApplicationPause(bool pause)
        {
            if (pause)
                LocallyHandOffMasterClient();
        }
        /// <summary>
        /// Called when the game gains or loses focus.
        /// </summary>
        private void OnApplicationFocus(bool focus)
        {
            if (!focus)
                LocallyHandOffMasterClient();
        }

        /// <summary>
        /// Hands off master client to the lowest pinging player at this time.
        /// </summary>
        private void LocallyHandOffMasterClient()
        {
            //Conditions where this does not apply.
            if (!PhotonNetwork.IsConnected || !PhotonNetwork.InRoom || !PhotonNetwork.IsMasterClient)
                return;
            //Only player.
            if (PhotonNetwork.PlayerList.Length <= 1)
                return;

            //Other index which isn't this client.
            int otherIndex = -1;

            int lowestIndex = -1;
            int lowestPing = -1;
            for (int i = 0; i < _playerPings.Count; i++)
            {
                //Skip self.
                if (_playerPings[i].Player == PhotonNetwork.LocalPlayer)
                    continue;

                otherIndex = i;

                int average = _playerPings[i].ReturnAveragePing();
                //If new lowest or lowest isnt yet set.
                if (average < lowestPing || lowestIndex == -1)
                {
                    lowestIndex = i;
                    lowestPing = average;
                }
            }

            //If the lowest ping was found.
            if (lowestIndex != -1)
            {
                SetNewMaster(_playerPings[lowestIndex].Player);
            }
            //Lowest ping not found. Maybe not enough data is collected.
            else
            {
                /* Can only proceed if an index of another player was found.
                 * If so send to the last player checked which wasnt self. */
                if (otherIndex != -1)
                    SetNewMaster(_playerPings[otherIndex].Player);
            }
        }
    }

}
</code>```

Body:
we have this error which comes up exactly every 5 seconds and I couldn't find anywhere infos about it or how to fix it.
screenshot of the error

RPC method 'RPC_ReceivePing' found on object with PhotonView 1001 but has wrong parameters. Implement as 'RPC_ReceivePing(Int32)'. PhotonMessageInfo is optional as final parameter.Return type must be void or IEnumerator (if you enable RunRpcCoroutines).
UnityEngine.Debug:LogErrorFormat (UnityEngine.Object,string,object[])
Photon.Pun.PhotonNetwork:ExecuteRpc (ExitGames.Client.Photon.Hashtable,Photon.Realtime.Player) (at Assets/Plugins/PhotonUnityNetworking/Code/PhotonNetworkPart.cs:646)
Photon.Pun.PhotonNetwork:RPC (Photon.Pun.PhotonView,string,Photon.Pun.RpcTarget,Photon.Realtime.Player,bool,object[]) (at Assets/Plugins/PhotonUnityNetworking/Code/PhotonNetworkPart.cs:1266)
Photon.Pun.PhotonNetwork:RPC (Photon.Pun.PhotonView,string,Photon.Pun.RpcTarget,bool,object[]) (at Assets/Plugins/PhotonUnityNetworking/Code/PhotonNetwork.cs:2940)
Photon.Pun.PhotonView:RPC (string,Photon.Pun.RpcTarget,object[]) (at Assets/Plugins/PhotonUnityNetworking/Code/PhotonView.cs:609)
FirstGearGames.PhotonNetworking.Utilities.MasterClientMonitor:CheckSendPing () (at Assets/01_Batvision/05_Scripts/GameLogic/MasterClientMonitor.cs:299)
FirstGearGames.PhotonNetworking.Utilities.MasterClientMonitor:Update () (at Assets/01_Batvision/05_Scripts/GameLogic/MasterClientMonitor.cs:127)

it's telling me that some RPC parameter is wrong but I checked every single one in the project and can't seem to find what they mean.
screenshot of all rpc

here's an example of one of the RPC
example of my rpc

void Update()
{
   if (HasCrossedTheRing == true)
    {

         photonView.RPC("ConfirmRing", RpcTarget.All);
         PhotonNetwork.SendAllOutgoingCommands();

    }
}

[PunRPC]
public void ConfirmRing()
{
    if (HasCrossedTheRing == true)
    {
        mainRingTimerObj.StopTimer();
        NextInsectObjCin.LookAtRoots();
        rootsAdd.addColorRoot();
        HasCrossedTheRing = false;

    }
}

would anyone have an idea what the error means or how I can find on which RPC the problem comes from?

thanks for your time,

HD

I tried deleting all unused RPC in the project and check that it wasn't a spelling error and the so called bool "RunRpcCoroutines" is already set to false

the MasterClientMonitor.cs

using UnityEngine;
using System.Collections.Generic;
using Photon.Pun;
using Photon.Realtime;
using System.Linq;

namespace FirstGearGames.PhotonNetworking.Utilities
{

    public class MasterClientMonitor : MonoBehaviourPunCallbacks
    {
        #region Types.
        ///
        /// Holds a players ping.
        ///
        private class PlayerPing
        {
            public PlayerPing(Player player, int ping)
            {
                Player = player;
                _pings.Add(ping);
            }
            ///
            /// Last time a ping was set for this player.
            ///
            public float LastUpdatedTime { get; private set; } = -1f;
            ///
            /// Player this instance is for.
            ///
            public readonly Player Player;
            ///
            /// Pings for this player.
            ///
            private List<int> _pings = new List<int>();
            ///
            /// Maximum number of ping history to allow.
            ///
            private const int MAXIMUM_RECORDED_PINGS = 6;

            ///
            /// Returns the average ping for this player. Returns -1f if recorded ping quantity is not at maximum recorded pings.
            ///
            /// <returns></returns>
            public int ReturnAveragePing()
            {
                //Not enough pings to consider an average yet.
                if (_pings.Count < MAXIMUM_RECORDED_PINGS)
                {
                    return -1;
                }
                //Has enough pings to return average.
                else
                {
                    int sum = _pings.Sum();
                    return Mathf.CeilToInt(sum / _pings.Count);
                }
            }

            ///
            /// Adds a ping for this player. Replaces oldest ping if at maximum recorded pings.
            ///
            /// <param name="value"></param>
            public void AddPing(int value)
            {
                //If at max pings remove the first entry.
                if (_pings.Count >= MAXIMUM_RECORDED_PINGS)
                    _pings.RemoveAt(0);

                _pings.Add(value);
                LastUpdatedTime = Time.unscaledTime;
            }
        }
        #endregion

        #region Private.
        ///
        /// List of player pings.
        ///
        private List<PlayerPing> _playerPings = new List<PlayerPing>();
        ///
        /// Next time to check for a high ping on master client.
        ///
        private float _nextCheckChangeMaster = 0f;
        ///
        /// Number of times in a row the current master client has had a significantly higher ping.
        ///
        private int _consequtiveHighPingCount = 0;
        ///
        /// True if received a master client change request. This is only set on master client.
        ///
        private bool _pendingMasterChange = false;
        ///
        /// Time a takeover request was sent. -1f if no takeover request is active.
        ///
        private float _takeoverRequestTime = -1f;
        ///
        /// Next time to send ping for this client.
        ///
        private float _nextSendPingTime = 0f;
        #endregion

        #region Const.
        ///
        /// How many times in a row the current masters ping must be significantly higher than others to forfeit master client.
        ///
        private const int HIGH_PING_TURNOVER_REQUIREMENT = 3;
        ///
        /// Mimimum current master client pings must be higher than lowest pinging player to be considered significantly higher.
        ///
        private const int MINIMUM_PING_DIFFERENCE = 50;
        ///
        /// How often to check for lowest pings. Masterclient must have a high ping after HIGH_PING_TURNOVER_REQUIREMENT times.
        ///
        private const float PING_CHECK_INTERVAL = 5f;
        ///
        /// Time master client has to grant a takeover request before it's taken forcefully. It's preferred that the master grants the request to prevent multiple takeovers in a short duration, but when master client is laggy or broken this may not be possible.
        ///
        private const float TAKEOVER_REQUEST_TIMEOUT = 3f;
        ///
        /// How frequently to send this clients ping.
        ///
        private const float SEND_PING_INTERVAL = 5f;
        #endregion

        private void Update()
        {
            CheckSendPing();
            CheckChangeMaster();
            CheckTakeoverTimeout();
        }

        public override void OnPlayerLeftRoom(Player otherPlayer)
        {
            //See if player is in player pings. If so remove them.
            int index = _playerPings.FindIndex(x => x.Player == otherPlayer);
            if (index != -1)
                _playerPings.RemoveAt(index);
        }

        public override void OnMasterClientSwitched(Player newMasterClient)
        {
            base.OnMasterClientSwitched(newMasterClient);
            //Unset pending master change.
            _pendingMasterChange = false;
            //Reset takeover data.
            _takeoverRequestTime = -1f;
            _consequtiveHighPingCount = 0;
        }

        ///
        /// Checks if a takeover needs to be forced. Usually occurs when the master client doesn't respond in time.
        ///
        private void CheckTakeoverTimeout()
        {
            //No takeover in progress.
            if (_takeoverRequestTime == -1f)
                return;

            //Master client request timed out. Takeover forcefully.
            if ((Time.unscaledTime - _takeoverRequestTime) > TAKEOVER_REQUEST_TIMEOUT)
            {
                _takeoverRequestTime = -1f;
                SetNewMaster(PhotonNetwork.LocalPlayer);
            }
        }

        ///
        /// Sets a new master client.
        ///
        /// <param name="newMaster"></param>
        private void SetNewMaster(Player newMaster, bool resetHighPingCount = true)
        {
            if (resetHighPingCount)
                _consequtiveHighPingCount = 0;
            //Set new master and use takeover.
            PhotonNetwork.SetMasterClient(newMaster);
        }

        ///
        /// Checks to change master if the current master is significantly more laggy than other players.
        ///
        /// <returns></returns>
        private void CheckChangeMaster()
        {
            //Network conditions not met.
            if (!PhotonNetwork.IsConnected || !PhotonNetwork.InRoom || PhotonNetwork.IsMasterClient)
                return;
            //Takeover already in progress.
            if (_takeoverRequestTime != -1f)
                return;
            //Too recent since last check.
            if (Time.time < _nextCheckChangeMaster)
                return;

            //Next time to check pings.
            _nextCheckChangeMaster = Time.time + PING_CHECK_INTERVAL;

            /* Players should already be removed when leaving the room.
             * This is just an extra precautionary. */
            RemoveNullPlayers();

            //Get list of all players.
            Player[] players = PhotonNetwork.PlayerList;
            //If only one player.
            if (players.Length <= 1)
                return;

            int lowestAverageIndex = -1;
            int lowestAveragePing = -1;
            int masterPing = -1;
            int masterIndex = -1;

            foreach (Player player in players)
            {
                int pingsIndex = _playerPings.FindIndex(x => x.Player == player);
                //Not found in players pings.
                if (pingsIndex == -1)
                    continue;

                //If player being checked is this client.
                if (player == PhotonNetwork.LocalPlayer)
                {
                    //If this client hasn't sent a ping in awhile don't even try to takeover.
                    if ((Time.unscaledTime - _playerPings[pingsIndex].LastUpdatedTime) >= (SEND_PING_INTERVAL * 2))
                        return;
                }

                //Get average.
                int averagePing = _playerPings[pingsIndex].ReturnAveragePing();
                //If average isn't -1 then enough pings have been sent to calculate an average.
                if (averagePing != -1)
                {
                    /* If average ping is lowest than the current lowest or
                     * the lowest average index is -1 (which means unset) then
                     * set as new lowest average. */
                    if (averagePing < lowestAveragePing || lowestAverageIndex == -1)
                    {
                        lowestAveragePing = averagePing;
                        lowestAverageIndex = pingsIndex;
                    }
                    //If player being checked is master client.
                    if (_playerPings[pingsIndex].Player.IsMasterClient)
                    {
                        masterIndex = pingsIndex;

                        /* If master client hasn't send a ping within a reasonable time then
                         * set the master clients ping unrealistically high to force a high
                         * consequtive ping count. */
                        if ((Time.unscaledTime - _playerPings[masterIndex].LastUpdatedTime) >= (SEND_PING_INTERVAL * 2))
                            masterPing = 999999999;
                        //Otherwise set to average ping.
                        else
                            masterPing = averagePing;
                    }
                }
            }

            //If the lowest ping index couldn't be found.
            if (lowestAverageIndex == -1)
                return;
            //Master index couldn't be found.
            if (masterIndex == -1)
                return;
            /* If the lowest ping index isn't this client then
             * don't proceed further, let the lowest pinging player
             * try the take over when the time comes. */
            if (_playerPings[lowestAverageIndex].Player != PhotonNetwork.LocalPlayer)
                return;

            /* If here this client is the lowest pinging player. */

            float masterPingDifference = (masterPing - lowestAveragePing);
            //If master ping is difference is high enough to change master client.
            if (masterPingDifference > MINIMUM_PING_DIFFERENCE)
                _consequtiveHighPingCount++;
            //master ping not too much higher.
            else
                _consequtiveHighPingCount = 0;

            //If high ping 3 times in a row then request setting a new master.
            if (_consequtiveHighPingCount >= 3)
            {
                _takeoverRequestTime = Time.unscaledTime;
                base.photonView.RPC("RPC_RequestMasterClient", RpcTarget.MasterClient, _playerPings[lowestAverageIndex].Player);
            }
        }

        ///
        /// Sends ping to all players including self.
        ///
        private void CheckSendPing()
        {
            if (Time.unscaledTime < _nextSendPingTime)
                return;

            _nextSendPingTime = Time.unscaledTime + SEND_PING_INTERVAL;

            base.photonView.RPC("RPC_ReceivePing", RpcTarget.All, PhotonNetwork.GetPing());
        }

        ///
        /// Receives a ping for the specified player.
        ///
        /// <param name="player"></param>
        /// <param name="ping"></param>
        [PunRPC]
        private void RPC_ReceivePing(Player player, int ping)
        {
            int index = _playerPings.FindIndex(x => x.Player == player);
            if (index == -1)
                _playerPings.Add(new PlayerPing(player, ping));
            else
                _playerPings[index].AddPing(ping);
        }

        ///
        /// Removes null players from player pings list.
        ///
        private void RemoveNullPlayers()
        {
            for (int i = 0; i < _playerPings.Count; i++)
            {
                //If null player remove from list and decrease i.
                if (_playerPings[i].Player == null)
                {
                    _playerPings.RemoveAt(i);
                    i--;
                }
            }
        }

        ///
        /// Request releasing the master client to the requestor.
        ///
        /// <param name="requestor">Player requesting the change.</param>
        /// Master client required.
        [PunRPC]
        private void RPC_RequestMasterClient(Player requestor)
        {
            //A change is already pending.
            if (_pendingMasterChange)
                return;
            //If not master.
            if (!PhotonNetwork.IsMasterClient)
                return;

            _pendingMasterChange = true;
            //RPC to allow change.
            base.photonView.RPC("RPC_MasterClientGranted", requestor);
        }

        ///
        /// Received on a player which may takeover as master client.
        ///
        [PunRPC]
        private void RPC_MasterClientGranted()
        {
            //Set new master as self.
            SetNewMaster(PhotonNetwork.LocalPlayer);
        }

        ///
        /// Called when the game gains or loses focus.
        ///
        /// <param name="pause"></param>
        private void OnApplicationPause(bool pause)
        {
            if (pause)
                LocallyHandOffMasterClient();
        }
        ///
        /// Called when the game gains or loses focus.
        ///
        private void OnApplicationFocus(bool focus)
        {
            if (!focus)
                LocallyHandOffMasterClient();
        }

        ///
        /// Hands off master client to the lowest pinging player at this time.
        ///
        private void LocallyHandOffMasterClient()
        {
            //Conditions where this does not apply.
            if (!PhotonNetwork.IsConnected || !PhotonNetwork.InRoom || !PhotonNetwork.IsMasterClient)
                return;
            //Only player.
            if (PhotonNetwork.PlayerList.Length <= 1)
                return;

            //Other index which isn't this client.
            int otherIndex = -1;

            int lowestIndex = -1;
            int lowestPing = -1;
            for (int i = 0; i < _playerPings.Count; i++)
            {
                //Skip self.
                if (_playerPings[i].Player == PhotonNetwork.LocalPlayer)
                    continue;

                otherIndex = i;

                int average = _playerPings[i].ReturnAveragePing();
                //If new lowest or lowest isnt yet set.
                if (average < lowestPing || lowestIndex == -1)
                {
                    lowestIndex = i;
                    lowestPing = average;
                }
            }

            //If the lowest ping was found.
            if (lowestIndex != -1)
            {
                SetNewMaster(_playerPings[lowestIndex].Player);
            }
            //Lowest ping not found. Maybe not enough data is collected.
            else
            {
                /* Can only proceed if an index of another player was found.
                 * If so send to the last player checked which wasnt self. */
                if (otherIndex != -1)
                    SetNewMaster(_playerPings[otherIndex].Player);
            }
        }
    }

}


问:
Using TVPosterView inside UICollectionViewCell creates odd sizing issue
I'm trying to create a tvOS project using UICollectionView displays camera streams.

In the UICollectionViewCell I'm using TVPosterView to display the stream/image and a title.

The problem that I'm facing currently that when the app starts all thumbnails/UICollectionViewCell seems to have proper size; First item focused with larger size than others. When I roll-out to other item/s, the earlier focused item became much smaller than the size it has when started.

Let me try to explain the situation if I'm not clear with my words.

When the app starts - Camera A focused and larger size than others:

When roll-out Camera A, it become much smaller than Camera D or Camera E; Also, the currently focused Camera B do not has a larger size anymore (if I compared with Camera A size from previous screen):

In the UICollectionView controller I have following delegate method:

```<code>extension ListingViewController: UICollectionViewDelegateFlowLayout
{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        let thumbWidth = CGFloat(320)
        let thumbHeight = CGFloat(thumbWidth * 0.7)
        return CGSize(width: thumbWidth, height: thumbHeight)
    }
}
</code>```

In the UICollectionViewCell I basically has following codes:

```<code>internal func setupUI()
{
        posterView = TVPosterView()
        posterView.tag = 1100
        posterView.clipsToBounds = false

        addSubview(posterView)
        posterView.alignToSuperView()
}
</code>```

alignToSuperView() basically an extension to UIView with following codes:

```<code>public func alignToSuperView()
{
        self.translatesAutoresizingMaskIntoConstraints = false
        guard let margins = self.superview?.layoutMarginsGuide else {
            return
        }
        self.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
        self.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
        self.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
        self.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
        self.superview?.layoutIfNeeded()
}
</code>```

Body:
I'm trying to create a tvOS project using UICollectionView displays camera streams.

In the UICollectionViewCell I'm using TVPosterView to display the stream/image and a title.

The problem that I'm facing currently that when the app starts all thumbnails/UICollectionViewCell seems to have proper size; First item focused with larger size than others. When I roll-out to other item/s, the earlier focused item became much smaller than the size it has when started.

Let me try to explain the situation if I'm not clear with my words.

When the app starts - Camera A focused and larger size than others:

When roll-out Camera A, it become much smaller than Camera D or Camera E; Also, the currently focused Camera B do not has a larger size anymore (if I compared with Camera A size from previous screen):

In the UICollectionView controller I have following delegate method:

extension ListingViewController: UICollectionViewDelegateFlowLayout
{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        let thumbWidth = CGFloat(320)
        let thumbHeight = CGFloat(thumbWidth * 0.7)
        return CGSize(width: thumbWidth, height: thumbHeight)
    }
}

In the UICollectionViewCell I basically has following codes:

internal func setupUI()
{
        posterView = TVPosterView()
        posterView.tag = 1100
        posterView.clipsToBounds = false

        addSubview(posterView)
        posterView.alignToSuperView()
}

alignToSuperView() basically an extension to UIView with following codes:

public func alignToSuperView()
{
        self.translatesAutoresizingMaskIntoConstraints = false
        guard let margins = self.superview?.layoutMarginsGuide else {
            return
        }
        self.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
        self.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
        self.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
        self.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
        self.superview?.layoutIfNeeded()
}


问:
mapping string array with if statement
I want to map from string to string but i m getting error
error build:

```<code>Cannot convert return expression of type '()' to return type 'String'
</code>```

Code ->

```<code>var months : [String] = ["sonbahar", "kis", "ilkbahar", "yaz"]

var aylar : [String]

aylar = months.map{ _ in return

if months == "sonbahar" {
    print("eylul ekim kasim")
}
if months == "kis" {
    print("aralik ocak subat")
}
if months == "ilkbahar" {
    print("mart nisan mayis")
}
if months == "yaz" {
    print("haziran temmuz agustos")
}
}
</code>```

I tried mapping from string array to string array, I want to see as I showed but taking error.

Title: mapping string array with if statement

Body:
I want to map from string to string but i m getting error
error build:

Cannot convert return expression of type '()' to return type 'String'

Code ->

var months : [String] = ["sonbahar", "kis", "ilkbahar", "yaz"]

var aylar : [String]

aylar = months.map{ _ in return

if months == "sonbahar" {
    print("eylul ekim kasim")
}
if months == "kis" {
    print("aralik ocak subat")
}
if months == "ilkbahar" {
    print("mart nisan mayis")
}
if months == "yaz" {
    print("haziran temmuz agustos")
}
}

I tried mapping from string array to string array, I want to see as I showed but taking error.


问:
Jinja2 read file
I am using Jinja2 templates to create configs. I am trying to reverse the process, to read the contents of a file and store the variables.

For example,

If I have a file containing the following:

```<code>!
interface gi0/0
 **random stuff**
 description first desc
 **random stuff**
!
interface gi0/1
 description second desc
 **random stuff**
!
</code>```

Can I create a template as below and use it to read the files and store the variables?

```<code>interface {{INTERFACE}}
 description {{DESCRIPTION}}
</code>```

So I would end up with something like this:

```<code>(interface:"gi0/0",description:"first desc"),
(interface:"gi0/1",description:"second desc")
</code>```

Title: Jinja2 read file

Body:
I am using Jinja2 templates to create configs. I am trying to reverse the process, to read the contents of a file and store the variables.

For example,

If I have a file containing the following:

!
interface gi0/0
 **random stuff**
 description first desc
 **random stuff**
!
interface gi0/1
 description second desc
 **random stuff**
!

Can I create a template as below and use it to read the files and store the variables?

interface {{INTERFACE}}
 description {{DESCRIPTION}}

So I would end up with something like this:

(interface:"gi0/0",description:"first desc"),
(interface:"gi0/1",description:"second desc")


问:
Catch initiator request in Django signal handler
I am working on a Python/Django project. I use Django signals in order to do an operation after creation of new instances of a model.

The question is: Is there any trick to access the request that has triggered this signal? e.g. to use its user field and do some operations based on it.