问:
Reset MySQL root password using ALTER USER statement after install on Mac
I recently installed MySQL and it seems I have to reset the password after install. It won't let me do anything else.

Now I already reset the password the usual way:

```<code>update user set password = password('XXX') where user = root;
</code>```

(BTW: took me ages to work out that MySQL for some bizarre reason has renamed the field 'password' to 'authentication_string'. I am quite upset about changes like that.)

Unfortunately it seems I need to change the password a different way that is unknown to me. Maybe someone here has already come across that problem?

答:
In order to chage user's password:

Firstly, login by root
$sudo mysql

Change user's password

ALTER USER 'user'@'localhost' IDENTIFIED BY 'newPassword';

Body:
I recently installed MySQL and it seems I have to reset the password after install. It won't let me do anything else.

Now I already reset the password the usual way:

update user set password = password('XXX') where user = root;

(BTW: took me ages to work out that MySQL for some bizarre reason has renamed the field 'password' to 'authentication_string'. I am quite upset about changes like that.)

Unfortunately it seems I need to change the password a different way that is unknown to me. Maybe someone here has already come across that problem?


来源: stackexchange

问:
creating export task in aws cloudwatch log
I am trying to create export task for moving the cloudwatch logs more than 30 day to move to s3 bucket. I am currently following this AWS article https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/S3ExportTasks.html. I am stuck with the creation of export task. when I ran the below command

```<code> aws logs create-export-task --profile CWLExportUser --task-name "my-log-group-$(date +%Y-%m-%d)" --log-group-name "/aws/lambda/AMICreate" --from  60  --to  155520000 --destination "diego-cw-logs" --destination-prefix "export-task-output"
</code>```

I am getting below error

```<code>An error occurred (InvalidParameterException) when calling the CreateExportTask operation: Specified time range of '60' and '155520000' is not valid. Please make sure the values are within the retention period of the log groups and from value is lesser than the to values
</code>```

I am missing something. It would be great if some one render their hands to fix the issue.

Warmly,
Muneesh

答:
Use https://currentmillis.com/ to convert time in milisecond. Below is python code and use it with eventbridge to get transfer log as per your need.

import json
import boto3
import botocore
from datetime import datetime, timedelta

def hello(event, context):

```<code># Date calculated in milisecond
time_seven_days_ago = (datetime.now() + timedelta(days=-103)).timestamp()
time_six_days_ago = (datetime.now() + timedelta(days=-102)).timestamp()
print(int(time_seven_days_ago)*1000) #printing to CloudWatch
print(int(time_six_days_ago)*1000) #printing to CloudWatch

#Boto3 objecets for CW and SNS
client = boto3.client('sns')
cli = boto3.client('logs')

try:
    response = cli.create_export_task(
    taskName='task-name',logGroupName='cloudwatch-log-group-name', fromTime=int(time_seven_days_ago)*1000, to=int(time_six_days_ago)*1000,  destination='s3-bucket-name',   destinationPrefix='its-your-wish')
    print(response)
    client.publish(
        TopicArn='topic--arn',
        #Sending Error in Email
        Message='Task completed',
        Subject='Create Task Job Status',
        MessageStructure='Create Task Job status'
        )

except BaseException as error:
    print('Error From Lambda Function', error) #Printing Error to CloudWatch
    try:
        client.publish(
        TopicArn='topic-arn',
        #Sending Error in Email
        Message=error,
        Subject='Create Task Job Failed',
        MessageStructure='Create Task Job Failed'+error
        )
    except BaseException as fail:
        print('Error while sending email', fail)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create export task for moving the cloudwatch logs more than 30 day to move to s3 bucket. I am currently following this AWS article https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/S3ExportTasks.html. I am stuck with the creation of export task. when I ran the below command

 aws logs create-export-task --profile CWLExportUser --task-name "my-log-group-$(date +%Y-%m-%d)" --log-group-name "/aws/lambda/AMICreate" --from  60  --to  155520000 --destination "diego-cw-logs" --destination-prefix "export-task-output"

I am getting below error

An error occurred (InvalidParameterException) when calling the CreateExportTask operation: Specified time range of '60' and '155520000' is not valid. Please make sure the values are within the retention period of the log groups and from value is lesser than the to values

I am missing something. It would be great if some one render their hands to fix the issue.

Warmly,
Muneesh

Body:
Use https://currentmillis.com/ to convert time in milisecond. Below is python code and use it with eventbridge to get transfer log as per your need.

import json
import boto3
import botocore
from datetime import datetime, timedelta

def hello(event, context):

# Date calculated in milisecond
time_seven_days_ago = (datetime.now() + timedelta(days=-103)).timestamp()
time_six_days_ago = (datetime.now() + timedelta(days=-102)).timestamp()
print(int(time_seven_days_ago)*1000) #printing to CloudWatch
print(int(time_six_days_ago)*1000) #printing to CloudWatch

#Boto3 objecets for CW and SNS
client = boto3.client('sns')
cli = boto3.client('logs')

try:
    response = cli.create_export_task(
    taskName='task-name',logGroupName='cloudwatch-log-group-name', fromTime=int(time_seven_days_ago)*1000, to=int(time_six_days_ago)*1000,  destination='s3-bucket-name',   destinationPrefix='its-your-wish')
    print(response)
    client.publish(
        TopicArn='topic--arn',
        #Sending Error in Email
        Message='Task completed',
        Subject='Create Task Job Status',
        MessageStructure='Create Task Job status'
        )

except BaseException as error:
    print('Error From Lambda Function', error) #Printing Error to CloudWatch
    try:
        client.publish(
        TopicArn='topic-arn',
        #Sending Error in Email
        Message=error,
        Subject='Create Task Job Failed',
        MessageStructure='Create Task Job Failed'+error
        )
    except BaseException as fail:
        print('Error while sending email', fail)


问:
Perform same task on multiple objects in the environment using for loop
I have these data:

```<code>u1 <- 'www.link1.com'
u2 <- 'www.link2.com'
u3 <- 'www.link3.com'
u4 <- 'www.link4.com'
</code>```

I want to do some work on them, how can I use for-loop to do this?!

```<code>for (i in u1 : ur4)
{
  texti <- gettxt(i)
}
</code>```

答:
As pointed out by @slowowl and @r2evans, you don't need a loop as R is vectorized. Consider storing the URLs in a vector.

You can do that as follows:

```<code>URLs <- c('www.link1.com', 'www.link2.com', 'www.link3.com', 'www.link4.com')
</code>```

And then you can use lapply over this vector as follows:

```<code>text <- lapply(URLs, gettext)
</code>```

To make a vector from individual variables you can use the following code:

```<code>vec <- c()
for (i in 1:4) {
  vec <- c(vec, get(sprintf("u%i", i)))
}
</code>```
```<code>[1] "www.link1.com" "www.link2.com" "www.link3.com" "www.link4.com"
</code>```

Body:
I have these data:

u1 <- 'www.link1.com'
u2 <- 'www.link2.com'
u3 <- 'www.link3.com'
u4 <- 'www.link4.com'

I want to do some work on them, how can I use for-loop to do this?!

for (i in u1 : ur4)
{
  texti <- gettxt(i)
}

Body:
As pointed out by @slowowl and @r2evans, you don't need a loop as R is vectorized. Consider storing the URLs in a vector.

You can do that as follows:

URLs <- c('www.link1.com', 'www.link2.com', 'www.link3.com', 'www.link4.com')

And then you can use lapply over this vector as follows:

text <- lapply(URLs, gettext)

To make a vector from individual variables you can use the following code:

vec <- c()
for (i in 1:4) {
  vec <- c(vec, get(sprintf("u%i", i)))
}

[1] "www.link1.com" "www.link2.com" "www.link3.com" "www.link4.com"


问:
In mysql, how to avoid selection if a table exists
Let's say I run the following query:

```<code>CREATE TEMPORARY TABLE IF NOT EXISTS FISH SELECT 'a';
</code>```

it will create a temporary table with 'a' in it. Now, if I run the query again, the table will not be recreated, but the select will happen again - so, the table will have 'a' twice in it. How do I prevent this from happening, i.e. if the table exists, no action should be carried out?

答:
This behavior is explicitly documented in the manual, quote:

For CREATE TABLE ... SELECT, if IF NOT EXISTS is given and the table already exists, MySQL handles the statement as follows:

The table definition given in the CREATE TABLE part is ignored. No error occurs, even if the definition does not match that of the existing table.

If there is a mismatch between the number of columns in the table and the number of columns produced by the SELECT part, the selected values are assigned to the rightmost columns. For example, if the table contains n columns and the SELECT produces m columns, where m < n, the selected values are assigned to the m rightmost columns in the table. Each of the initial n – m columns is assigned its default value, either that specified explicitly in the column definition or the implicit column data type default if the definition contains no default.

If strict SQL mode is enabled and any of these initial columns do not have an explicit default value, the statement fails with an error.

and there is no mention of any method to change this behavior so I suppose your only solution is to first check for table's existence with a separate query then CREATE...SELECT the table if it doesn't exist.

ContentLicense: CC BY-SA 3.0

Body:
Let's say I run the following query:

CREATE TEMPORARY TABLE IF NOT EXISTS FISH SELECT 'a';

it will create a temporary table with 'a' in it. Now, if I run the query again, the table will not be recreated, but the select will happen again - so, the table will have 'a' twice in it. How do I prevent this from happening, i.e. if the table exists, no action should be carried out?


问:
Show / hide Android softkeyboard on fragment replace
I have an Activity with a fragment. Let's say a list fragment with a list of things. Now I want to let the user add a thing, so I use the FragmentManager to replace the list fragment with an insert fragment which has an EditText. The EditText has the focus and the cursor is blinking. But the softkeyboard doesn't open.
Same thing other way round: if the user has entered the new thing and added it to the list, I replace the insert fragment back with a list fragment. But although there is no EditText anymore, the keyboard doesn't close.

What is the correct way to implement this? I can't believe that I have to show and hide the keyboard manually on all transitions?!

答:
for Kotlin :

put this function in somewhere like Utils class.

```<code>fun hideSoftKeyboard(view: View, context: Context) {
        val inputMethodManager =
            context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
    }

</code>```

then use it in Fragments or Activities Like:

```<code>
Utils().hideSoftKeyboard(inputTextChat, requireContext())
</code>```

Body:
for Kotlin :

put this function in somewhere like Utils class.

fun hideSoftKeyboard(view: View, context: Context) {
        val inputMethodManager =
            context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
    }

then use it in Fragments or Activities Like:

Utils().hideSoftKeyboard(inputTextChat, requireContext())


问:
In Azure, is it possible to control access control (IAM) for a file shares using Powershell?
I have been trying to use Powershell to assign users access control privileges for a file share in Azure. What I have been doing is:

```<code>Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
</code>```

Login to Azure

```<code>az login
</code>```

Get User Information and isolate the User Principle Name

```<code>$UPN = (Get-AzADUser -StartsWith $UserName).UserPrincipalName
</code>```

Get the row that contains Scope

```<code>$TempScope = az storage share-rm show -g $ResourceGroup --storage-account $StorageAccount --name $FileShareName | Select-String -Pattern '/subscriptions' -CaseSensitive
</code>```

Change that row to a string

```<code>$TempScope = $TempScope | foreach {$_.ToString()}
</code>```

Remove the first 8 characters

```<code>$scope = $TempScope.Substring(9)
</code>```

Get Name of Role

```<code>$FileShareRole = Get-AzRoleDefinition $RoleName
</code>```

Assign the role to the target identity with the specified scope

```<code>New-AzRoleAssignment -SignInName $UPN -RoleDefinitionName $FileShareRole.Name -Scope $scope
</code>```

It has not been giving the user access to the file share but instead to microsoft.storage/storageaccounts/fileservices/shares.

答:
Yes, You can add Access Control to the file share. In the above-shared script, you are using the long approach to pull the resource ID of the file share. We have made some changes to the above script.

Here is the Modified script to add Access Control to the file Share:

```<code>$UserName="<UserName>"
$ResourceGroup="<RGName>"
$StorageAccount="<strgAccountName>"
$FileShareName="<FileShareName>"
$RoleName="Storage File Data SMB Share Reader"
$UPN = (Get-AzADUser -StartsWith $UserName).UserPrincipalName

$TempScope = az storage share-rm show -g $ResourceGroup --storage-account $StorageAccount --name $FileShareName --query id -o tsv
$FileShareRole = Get-AzRoleDefinition $RoleName
New-AzRoleAssignment -SignInName $UPN -RoleDefinitionName $FileShareRole.Name -Scope $scope
</code>```

Here are the three Azure built-in roles for granting share-level permissions to users:

Storage File Data SMB Share Reader  allows read access in Azure Storage file shares over SMB.

Storage File Data SMB Share Contributor  allows read, write, and delete access in Azure Storage file shares over SMB.

Storage File Data SMB Share Elevated Contributor  allows read, write, delete and modify NTFS permissions in Azure Storage file shares over SMB.

Body:
I have been trying to use Powershell to assign users access control privileges for a file share in Azure. What I have been doing is:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Login to Azure

az login

Get User Information and isolate the User Principle Name

$UPN = (Get-AzADUser -StartsWith $UserName).UserPrincipalName

Get the row that contains Scope

$TempScope = az storage share-rm show -g $ResourceGroup --storage-account $StorageAccount --name $FileShareName | Select-String -Pattern '/subscriptions' -CaseSensitive

Change that row to a string

$TempScope = $TempScope | foreach {$_.ToString()}

Remove the first 8 characters

$scope = $TempScope.Substring(9)

Get Name of Role

$FileShareRole = Get-AzRoleDefinition $RoleName

Assign the role to the target identity with the specified scope

New-AzRoleAssignment -SignInName $UPN -RoleDefinitionName $FileShareRole.Name -Scope $scope

It has not been giving the user access to the file share but instead to microsoft.storage/storageaccounts/fileservices/shares.

Body:
Yes, You can add Access Control to the file share. In the above-shared script, you are using the long approach to pull the resource ID of the file share. We have made some changes to the above script.

Here is the Modified script to add Access Control to the file Share:

$UserName="<UserName>"
$ResourceGroup="<RGName>"
$StorageAccount="<strgAccountName>"
$FileShareName="<FileShareName>"
$RoleName="Storage File Data SMB Share Reader"
$UPN = (Get-AzADUser -StartsWith $UserName).UserPrincipalName

$TempScope = az storage share-rm show -g $ResourceGroup --storage-account $StorageAccount --name $FileShareName --query id -o tsv
$FileShareRole = Get-AzRoleDefinition $RoleName
New-AzRoleAssignment -SignInName $UPN -RoleDefinitionName $FileShareRole.Name -Scope $scope

Here are the three Azure built-in roles for granting share-level permissions to users:

Storage File Data SMB Share Reader  allows read access in Azure Storage file shares over SMB.

Storage File Data SMB Share Contributor  allows read, write, and delete access in Azure Storage file shares over SMB.

Storage File Data SMB Share Elevated Contributor  allows read, write, delete and modify NTFS permissions in Azure Storage file shares over SMB.


问:
Auto incremented column with string prefix
I need an autoincremented column with prefix which exist in database. I found solutions for computed columns if both columns exist in database, but I don't want to add a new int column for other column. So I need to define an ID column like "SomeCode|00001" and should increment automatically

```<code> modelBuilder.Entity<SomeHeaderClass>()
                .Property(s => s.ID)
                .HasComputedColumnSql($"CONCAT(SomeCodeCode,'|', IDENTITY(INT, 1, 1)) PERSISTED NOT NULL");
</code>```

Is there any way to do it?

答:
IDK about other solutions but I'm not a fan of doing this kind of computed column.

We can specify 2 columns, one for prefix value and one for increment value in this case, with an unique index using the combination of those two.

Benefit:

Simplicity and performance. (small char and number have better perf compare to big char).

Easily to scale as needed (what if the prefix length can evolve ?)

Not depending on Database engine (as far as i can remember, not every RMDBS out there having such computed column feature, any even if there is, I'm sure the performance cannot compete with 2 separate column solution)

Body:
I need an autoincremented column with prefix which exist in database. I found solutions for computed columns if both columns exist in database, but I don't want to add a new int column for other column. So I need to define an ID column like "SomeCode|00001" and should increment automatically

 modelBuilder.Entity<SomeHeaderClass>()
                .Property(s => s.ID)
                .HasComputedColumnSql($"CONCAT(SomeCodeCode,'|', IDENTITY(INT, 1, 1)) PERSISTED NOT NULL");

Is there any way to do it?


问:
Symfony2: disable vendor event listeners
I have a Symfony2 application I'm working on that uses SSO and the FosUserBundle. However there is a FosUserBundle event listener which is triggered when a user logs in and therefore stops my SSO bundle from working.

Is there a way in my app/config/config.yml that I can easily disable this specific FosUserBundle listener?

PS. The listener is FOS\UserBundle\EventListener\LastLoginListener::onSecurityInteractiveLogin

答:
In my case, in Symfony 5, I needed to override some vendor service. For this purpose alias worked for me. So in services.yaml you can define:

```<code>  Ekino\NewRelicBundle\Listener\ExceptionListener:
    alias: App\Service\NewRelic\ExceptionListener
</code>```

Ekino\NewRelicBundle\Listener\ExceptionListener is the service ID which I want to override. You can find service ID by running:

```<code>php bin/console debug:container
</code>```

Body:
In my case, in Symfony 5, I needed to override some vendor service. For this purpose alias worked for me. So in services.yaml you can define:

  Ekino\NewRelicBundle\Listener\ExceptionListener:
    alias: App\Service\NewRelic\ExceptionListener

Ekino\NewRelicBundle\Listener\ExceptionListener is the service ID which I want to override. You can find service ID by running:

php bin/console debug:container


问:
Modify all values in a dictionary
Code goes below:

```<code>d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}
</code>```

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

答:
What about

```<code>d = {'a':0, 'b':0, 'c':0, 'd':0}
s = 'cbad'
for k in d.iterkeys():
    d[k] = s.index(k)
</code>```

? It's no functional programming anymore but should be more performant and more pythonic, perhaps :-).

EDIT: A function variant using python dict-comprehensions (needs Python 2.7+ or 3+):

```<code>d.update({k : s.index(k) for k in d.iterkeys()})
</code>```

or even

```<code>{k : s.index(k) for k in d.iterkeys()}
</code>```

if a new dict is okay!

Title: Modify all values in a dictionary

Body:
Code goes below:

d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

Body:
What about

d = {'a':0, 'b':0, 'c':0, 'd':0}
s = 'cbad'
for k in d.iterkeys():
    d[k] = s.index(k)

? It's no functional programming anymore but should be more performant and more pythonic, perhaps :-).

EDIT: A function variant using python dict-comprehensions (needs Python 2.7+ or 3+):

d.update({k : s.index(k) for k in d.iterkeys()})

or even

{k : s.index(k) for k in d.iterkeys()}

if a new dict is okay!


问:
I have this problem while building the project in Unreal Engine. Can anyone help me with that
An error occurred while trying to generate project files.

Some Platforms were skipped due to invalid SDK setup: Mac, IOS, Android, Lumin.
See the log file for detailed information (/Users/sidd/Library/Application Support/Epic/UnrealBuildTool/Log_GPF.txt)

Discovering modules, targets and source code for project...
WARNING: Failed to query Xcode version
Triggered an exception while looking for SDK directory in Xcode.app
System.IO.DirectoryNotFoundException: Could not find a part of the path '/Library/Developer/CommandLineTools/Platforms/MacOSX.platform/Developer/SDKs'.
at System.IO.Enumeration.FileSystemEnumerator1.CreateDirectoryHandle(String path, Boolean ignoreNotFound) at System.IO.Enumeration.FileSystemEnumerator1.Init()
at System.IO.Enumeration.FileSystemEnumerator1..ctor(String directory, Boolean isNormalized, EnumerationOptions options) at System.IO.Enumeration.FileSystemEnumerable1..ctor(String directory, FindTransform transform, EnumerationOptions options, Boolean isNormalized)
at System.IO.Enumeration.FileSystemEnumerableFactory.UserDirectories(String directory, String expression, EnumerationOptions options)
at System.IO.Directory.InternalEnumeratePaths(String path, String searchPattern, SearchTarget searchTarget, EnumerationOptions options)
at System.IO.Directory.GetDirectories(String path)
at UnrealBuildTool.AppleToolChainSettings.SelectSDK(String BaseSDKDir, String OSPrefix, String& PlatformSDKVersion, Boolean bVerbose) in /Users/build/Build/++UE5/Sync/Engine/Source/Programs/UnrealBuildTool/ToolChain/AppleToolChain.cs:line 87
ERROR: Invalid SDK MacOSX.sdk, not found in /Library/Developer/CommandLineTools/Platforms/MacOSX.platform/Developer/SDKs

答:
I was having the same problem, this post saved my life.

You will need to select a valid 'Command Line Tools' in Xcode Preferences, under Locations tab.


问:
how to upload file with a new name in php
am trying to upload a file with a new name. here's my code. when i use the new name i get this error::move_uploaded_file(2-text/plain09-02-22.txt): failed to open stream: No such file or directory. but when i use the actual name it upload.</p>
```<code> $path = 'temp/';
         if (isset($_FILES['$_FILES']) && !empty($_FILES['$_FILES'])) {
             $file = $_FILES['$_FILES'];
             $file_name = $_FILES['$_FILES']['name'];
             $file_tmp = $_FILES['$_FILES']['tmp_name'];
             $file_type = $_FILES['$_FILES']['type'];
           }
           $file_ext = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));
          $new_filename = "$userid-".$file_type .date('d-m-y').".".$file_ext;
          $path = $path.$new_filename;
          if (move_uploaded_file($file_tmp,$path))
          {
           echo "upload success";
             http_response_code(200);
          }
          else {
             echo "upload failed";
             http_response_code(400);
          }
</code>```

答:
Change it to</p>
```<code>$file_type = explode("/", $file_type);
$new_filename = "$userid-".$file_type[0].date('d-m-y').".".$file_ext;
</code>```

Body:
am trying to upload a file with a new name. here's my code. when i use the new name i get this error::move_uploaded_file(2-text/plain09-02-22.txt): failed to open stream: No such file or directory. but when i use the actual name it upload.

 $path = 'temp/';
         if (isset($_FILES['$_FILES']) && !empty($_FILES['$_FILES'])) {
             $file = $_FILES['$_FILES'];
             $file_name = $_FILES['$_FILES']['name'];
             $file_tmp = $_FILES['$_FILES']['tmp_name'];
             $file_type = $_FILES['$_FILES']['type'];
           }
           $file_ext = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));
          $new_filename = "$userid-".$file_type .date('d-m-y').".".$file_ext;
          $path = $path.$new_filename;
          if (move_uploaded_file($file_tmp,$path))
          {
           echo "upload success";
             http_response_code(200);
          }
          else {
             echo "upload failed";
             http_response_code(400);
          }

Body:
Change it to

$file_type = explode("/", $file_type);
$new_filename = "$userid-".$file_type[0].date('d-m-y').".".$file_ext;


问:
SwiftUI Timeout Alert Warning Then Timed Out
I setup a timer to show two alerts. The first alert shows the user a warning that says "Hey, you've been inactive for a while, are you still here" and if they tap yes, then it resets the timer. If they don't tap the alert button, after x amount of time it shows the second alert notifying them their session has expired. They tap OK and it takes them out of the nav view and back to the main page.

This all works perfectly, however XCode is throwing an error of:

```<code>[Presentation] Attempt to present <SwiftUI.PlatformAlertController: 0x7fc2fa031800> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x7fc2e9f05530> (from <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_24NavigationColumnModifier__: 0x7fc309f28e80>) which is already presenting <SwiftUI.PlatformAlertController: 0x7fc2ea842000>.
</code>```

From what I understand, this is saying, there's already an alert being shown and even though I'm going to dismiss it and show your other alert, I'm going to complain about it, which tells me I'm doing something wrong. I would like to ensure I'm doing it correctly so I do not receive this error in XCode's console.

After creating the timer I am using onReceive to watch it:

```<code>.onReceive(timer) { time in
            if userTimeout == true {
                timer.upstream.connect().cancel()
            } else {
            caWarning()
            caTimeout()
            }
        }
</code>```

The two functions are really simplistic:

```<code>func caWarning() {
    if Date.now >= userActivity.addingTimeInterval(5*1) {
        userActivityAlert = true
    }
}

func caTimeout() {
    if Date.now >= userActivity.addingTimeInterval(10*1) {
        userActivityAlert = false
        userTimeout = true
    }
}
</code>```

Finally, my if statement for the alerts is:

```<code>if userActivityAlert == true {
            VStack {
                EmptyView()
            }
            .alert("Foo", isPresented: $userActivityAlert, actions: {
                Button("I'm Here") {
                    userActivity = Date.now
                }
            }, message: { Text("Are you still there?") }
        ) // End show alert
        } else if UserTimeout == true {
            VStack {
                EmptyView()
            }
            .alert("Foo", isPresented: $userTimeout, actions: {
                Button("OK") {
                    self.caRegExpired.navToHome = true
                }
            }, message: {
                    Text("Your session has expired.\nTap OK, to start over.")
            }) // End Alert
        } // End If
</code>```

I have tried everything I can think of. From @Environment (\.dismiss) var dismiss and then calling dismiss() (dismisses the underlying view and not the alert), to pouring through Apple's docs and old UIKit stuff (no help).

I'm fine with either doing it this way (i.e. two separate alerts) OR being able to modify the first alert into the second alert after a certain period of time (perhaps even showing a countdown until the user's session has expired).

Honestly, I'm wondering if it's just log noise because the first alert disappears and the second one displays exactly as it should. Literally this all works fine, but it's important that errors are addressed and I want to know if I'm doing something wrong.

This is for the latest SwiftUI 5+ and XCode for iOS 15+

答:
@loremipsum's link has the answer: just wait a little between deactivating the first alert and showing the second:</p>
```<code>struct ContentView: View {

    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    @State private var userActivityAlert = false
    @State private var userTimeout = false
    @State private var userActivity = Date.now

    var body: some View {

        VStack {
            Text("Hello, World!")
                .alert("Foo", isPresented: $userActivityAlert, actions: {
                    Button("I'm Here") {
                        userActivity = Date.now
                    }
                }, message: { Text("Are you still there?") }
                ) // End show alert

            Text("Hello, World!")
                .alert("Foo", isPresented: $userTimeout, actions: {
                    Button("OK") {
                        //                        self.caRegExpired.navToHome = true
                    }
                }, message: {
                    Text("Your session has expired.\nTap OK, to start over.")
                }) // End Alert

        }
        .onReceive(timer) { time in
            if userTimeout == true {
                timer.upstream.connect().cancel()
            } else {
                caWarning()
                caTimeout()
            }
        }
    }

    func caWarning() {
        if Date.now >= userActivity.addingTimeInterval(5*1) {
            userActivityAlert = true
        }
    }

    func caTimeout() {
        if Date.now >= userActivity.addingTimeInterval(10*1) {
            userActivityAlert = false

            //This delay leaves a little gap between alerts
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                userTimeout = true
            }
        }
    }
}
</code>```

Body:
I setup a timer to show two alerts. The first alert shows the user a warning that says "Hey, you've been inactive for a while, are you still here" and if they tap yes, then it resets the timer. If they don't tap the alert button, after x amount of time it shows the second alert notifying them their session has expired. They tap OK and it takes them out of the nav view and back to the main page.

This all works perfectly, however XCode is throwing an error of:

[Presentation] Attempt to present <SwiftUI.PlatformAlertController: 0x7fc2fa031800> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x7fc2e9f05530> (from <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_24NavigationColumnModifier__: 0x7fc309f28e80>) which is already presenting <SwiftUI.PlatformAlertController: 0x7fc2ea842000>.

From what I understand, this is saying, there's already an alert being shown and even though I'm going to dismiss it and show your other alert, I'm going to complain about it, which tells me I'm doing something wrong. I would like to ensure I'm doing it correctly so I do not receive this error in XCode's console.

After creating the timer I am using onReceive to watch it:

.onReceive(timer) { time in
            if userTimeout == true {
                timer.upstream.connect().cancel()
            } else {
            caWarning()
            caTimeout()
            }
        }

The two functions are really simplistic:

func caWarning() {
    if Date.now >= userActivity.addingTimeInterval(5*1) {
        userActivityAlert = true
    }
}

func caTimeout() {
    if Date.now >= userActivity.addingTimeInterval(10*1) {
        userActivityAlert = false
        userTimeout = true
    }
}

Finally, my if statement for the alerts is:

if userActivityAlert == true {
            VStack {
                EmptyView()
            }
            .alert("Foo", isPresented: $userActivityAlert, actions: {
                Button("I'm Here") {
                    userActivity = Date.now
                }
            }, message: { Text("Are you still there?") }
        ) // End show alert
        } else if UserTimeout == true {
            VStack {
                EmptyView()
            }
            .alert("Foo", isPresented: $userTimeout, actions: {
                Button("OK") {
                    self.caRegExpired.navToHome = true
                }
            }, message: {
                    Text("Your session has expired.\nTap OK, to start over.")
            }) // End Alert
        } // End If

I have tried everything I can think of. From @Environment (\.dismiss) var dismiss and then calling dismiss() (dismisses the underlying view and not the alert), to pouring through Apple's docs and old UIKit stuff (no help).

I'm fine with either doing it this way (i.e. two separate alerts) OR being able to modify the first alert into the second alert after a certain period of time (perhaps even showing a countdown until the user's session has expired).

Honestly, I'm wondering if it's just log noise because the first alert disappears and the second one displays exactly as it should. Literally this all works fine, but it's important that errors are addressed and I want to know if I'm doing something wrong.

This is for the latest SwiftUI 5+ and XCode for iOS 15+

Body:
@loremipsum's link has the answer: just wait a little between deactivating the first alert and showing the second:

struct ContentView: View {

    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    @State private var userActivityAlert = false
    @State private var userTimeout = false
    @State private var userActivity = Date.now

    var body: some View {

        VStack {
            Text("Hello, World!")
                .alert("Foo", isPresented: $userActivityAlert, actions: {
                    Button("I'm Here") {
                        userActivity = Date.now
                    }
                }, message: { Text("Are you still there?") }
                ) // End show alert

            Text("Hello, World!")
                .alert("Foo", isPresented: $userTimeout, actions: {
                    Button("OK") {
                        //                        self.caRegExpired.navToHome = true
                    }
                }, message: {
                    Text("Your session has expired.\nTap OK, to start over.")
                }) // End Alert

        }
        .onReceive(timer) { time in
            if userTimeout == true {
                timer.upstream.connect().cancel()
            } else {
                caWarning()
                caTimeout()
            }
        }
    }

    func caWarning() {
        if Date.now >= userActivity.addingTimeInterval(5*1) {
            userActivityAlert = true
        }
    }

    func caTimeout() {
        if Date.now >= userActivity.addingTimeInterval(10*1) {
            userActivityAlert = false

            //This delay leaves a little gap between alerts
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                userTimeout = true
            }
        }
    }
}


问:
How to properly type a React ErrorBoundary class component in Typescript?
Here is my current attempt on how to properly type a React ErrorBoundary class component in Typescript:

```<code>import React from "react";
import ErrorPage from "./ErrorPage";
import type { Store } from "redux";   // I'M PASSING THE REDUX STORE AS A CUSTOM PROP

interface Props {
  store: Store         // THIS IS A CUSTOM PROP THAT I'M PASSING
}

interface State {      // IS THIS THE CORRECT TYPE FOR THE state ?
  hasError: boolean
}

class ErrorBoundary extends React.Component<Props,State> {

  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error): State {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo: React.ErrorInfo): void {
    // You can also log the error to an error reporting service
    // logErrorToMyService(error, errorInfo);
    console.log("error: " + error);
    console.log("errorInfo: " + JSON.stringify(errorInfo));
    console.log("componentStack: " + errorInfo.componentStack);
  }

  render(): React.ReactNode {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return(
        <ErrorPage
          message={"Something went wrong..."}
        />
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
</code>```

This question is about the types for this ErrorBoundary class component. I'm breaking it into parts to make it easier.

PART A: Types for props and state

Is what I'm doing right?

```<code>interface Props {
  store: Store         // THIS IS A CUSTOM PROP THAT I'M PASSING
}

interface State {      // IS THIS THE CORRECT TYPE FOR THE state ?
  hasError: boolean
}

class ErrorBoundary extends React.Component<Props,State> {}
</code>```

PART B: getDerivedStateFromError(error)

What type should I choose for the error parameter? The return type should be the State type, right?

```<code>static getDerivedStateFromError(error): State {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }
</code>```

PART C: componentDidCatch(error, errorInfo: React.React.ErrorInfo)

What type should I choose for the error parameter? For the errorInfo, React does have a ErrorInfo type that seems to be correct. Is it? The return type should be void, correct?

```<code>componentDidCatch(error, errorInfo: React.ErrorInfo): void {
    console.log("error: " + error);
    console.log("errorInfo: " + JSON.stringify(errorInfo));
    console.log("componentStack: " + errorInfo.componentStack);
}
</code>```

PART D: the render() method

Should the return type be ReactNode ?

```<code>render(): React.ReactNode {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return(
        <ErrorPage
          message={"Something went wrong..."}
        />
      );
    }

    return this.props.children;
  }
</code>```

答:
You can use the following code as an Error Boundary:

```<code>import React, { Component, ErrorInfo, ReactNode } from "react";

interface Props {
  children: ReactNode;
}

interface State {
  hasError: boolean;
}

class ErrorBoundary extends Component<Props, State> {
  public state: State = {
    hasError: false
  };

  public static getDerivedStateFromError(_: Error): State {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("Uncaught error:", error, errorInfo);
  }

  public render() {
    if (this.state.hasError) {
      return <h1>Sorry.. there was an error</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
</code>```

Body:
Here is my current attempt on how to properly type a React ErrorBoundary class component in Typescript:

import React from "react";
import ErrorPage from "./ErrorPage";
import type { Store } from "redux";   // I'M PASSING THE REDUX STORE AS A CUSTOM PROP

interface Props {
  store: Store         // THIS IS A CUSTOM PROP THAT I'M PASSING
}

interface State {      // IS THIS THE CORRECT TYPE FOR THE state ?
  hasError: boolean
}

class ErrorBoundary extends React.Component<Props,State> {

  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error): State {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo: React.ErrorInfo): void {
    // You can also log the error to an error reporting service
    // logErrorToMyService(error, errorInfo);
    console.log("error: " + error);
    console.log("errorInfo: " + JSON.stringify(errorInfo));
    console.log("componentStack: " + errorInfo.componentStack);
  }

  render(): React.ReactNode {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return(
        <ErrorPage
          message={"Something went wrong..."}
        />
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

This question is about the types for this ErrorBoundary class component. I'm breaking it into parts to make it easier.

PART A: Types for props and state

Is what I'm doing right?

interface Props {
  store: Store         // THIS IS A CUSTOM PROP THAT I'M PASSING
}

interface State {      // IS THIS THE CORRECT TYPE FOR THE state ?
  hasError: boolean
}

class ErrorBoundary extends React.Component<Props,State> {}

PART B: getDerivedStateFromError(error)

What type should I choose for the error parameter? The return type should be the State type, right?

static getDerivedStateFromError(error): State {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

PART C: componentDidCatch(error, errorInfo: React.React.ErrorInfo)

What type should I choose for the error parameter? For the errorInfo, React does have a ErrorInfo type that seems to be correct. Is it? The return type should be void, correct?

componentDidCatch(error, errorInfo: React.ErrorInfo): void {
    console.log("error: " + error);
    console.log("errorInfo: " + JSON.stringify(errorInfo));
    console.log("componentStack: " + errorInfo.componentStack);
}

PART D: the render() method

Should the return type be ReactNode ?

render(): React.ReactNode {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return(
        <ErrorPage
          message={"Something went wrong..."}
        />
      );
    }

    return this.props.children;
  }

Body:
You can use the following code as an Error Boundary:

import React, { Component, ErrorInfo, ReactNode } from "react";

interface Props {
  children: ReactNode;
}

interface State {
  hasError: boolean;
}

class ErrorBoundary extends Component<Props, State> {
  public state: State = {
    hasError: false
  };

  public static getDerivedStateFromError(_: Error): State {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("Uncaught error:", error, errorInfo);
  }

  public render() {
    if (this.state.hasError) {
      return <h1>Sorry.. there was an error</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;


问:
Firestore query is not being executed
I am facing a weird issue, and i have tried to debug, enter logs etc but still reached no where with this. I am trying to retrive data from firestore. This data is easily recovered using the same code in other activities. But in this one, its like the code doesnt exist. It doesnt enter any of the .addOnSuccess or .addOnFailure loops. Just moves over them - any thoughts?</p>
```<code> try {
    //Retrieving availability data from Firestore for the service Provider
    val mFirestore = FirebaseFirestore.getInstance()
        .collection("Users")
        .document(serviceProvider!!.getUID()!!)
        .collection("bookingOptions")
        .document(serviceProvider!!.getUID()!!)

        Log.e("BookingOption try started", serviceProvider!!.getUID()!!)
        mFirestore.get().addOnCompleteListener {
            Log.e("BookingOption query executed", serviceProvider!!.getUID()!!)
            if (it.isSuccessful) {
                val document = it.result
                bookingConditions = document.toObject(Bakala::class.java)
                Log.i("BookingOption retrieved", it.toString())
                //Device timezone if it is the client then the client device timezone
                selectedCalendar = Calendar.getInstance(TimeZone.getDefault())
                //saving the the provider timezone id
                providerTimeZoneID = bookingConditions!!.gettimeZoneId().toString()
                Log.e("TimeZone Data obtained", providerTimeZoneID)
                //get current time in company timezone id
                //convert to user timezone
                val minDate =
                    Calendar.getInstance(TimeZone.getTimeZone(bookingConditions!!.gettimeZoneId()))
                FORMAT.timeZone = TimeZone.getDefault()
                val date = FORMAT.format(minDate.time)
                try {
                    minDate.time = FORMAT.parse(date)
                } catch (e: ParseException) {
                    e.printStackTrace()
                }
            }
        }.addOnFailureListener {

       Log.e("BookingOption retrieval failure", it.toString())
                Toast.makeText(this, "Sorry could not load company info", Toast.LENGTH_SHORT).show()
//            finish()
            }.addOnCanceledListener {
                Log.e("BookingOption retrieval failure", "Query cancelled")
            }
        } catch(e: Exception) {
            e.printStackTrace()
            Log.e("BookingOptions failure",e.message.toString())
        }
</code>```

答: Figured it out, asynchronous execution of later functions that uses data from the above code ran quicker and caused a crash. Included that function in the successlistener for the query and it worked...</p>

Title: Firestore query is not being executed

Body:
I am facing a weird issue, and i have tried to debug, enter logs etc but still reached no where with this. I am trying to retrive data from firestore. This data is easily recovered using the same code in other activities. But in this one, its like the code doesnt exist. It doesnt enter any of the .addOnSuccess or .addOnFailure loops. Just moves over them - any thoughts?

 try {
    //Retrieving availability data from Firestore for the service Provider
    val mFirestore = FirebaseFirestore.getInstance()
        .collection("Users")
        .document(serviceProvider!!.getUID()!!)
        .collection("bookingOptions")
        .document(serviceProvider!!.getUID()!!)

        Log.e("BookingOption try started", serviceProvider!!.getUID()!!)
        mFirestore.get().addOnCompleteListener {
            Log.e("BookingOption query executed", serviceProvider!!.getUID()!!)
            if (it.isSuccessful) {
                val document = it.result
                bookingConditions = document.toObject(Bakala::class.java)
                Log.i("BookingOption retrieved", it.toString())
                //Device timezone if it is the client then the client device timezone
                selectedCalendar = Calendar.getInstance(TimeZone.getDefault())
                //saving the the provider timezone id
                providerTimeZoneID = bookingConditions!!.gettimeZoneId().toString()
                Log.e("TimeZone Data obtained", providerTimeZoneID)
                //get current time in company timezone id
                //convert to user timezone
                val minDate =
                    Calendar.getInstance(TimeZone.getTimeZone(bookingConditions!!.gettimeZoneId()))
                FORMAT.timeZone = TimeZone.getDefault()
                val date = FORMAT.format(minDate.time)
                try {
                    minDate.time = FORMAT.parse(date)
                } catch (e: ParseException) {
                    e.printStackTrace()
                }
            }
        }.addOnFailureListener {

       Log.e("BookingOption retrieval failure", it.toString())
                Toast.makeText(this, "Sorry could not load company info", Toast.LENGTH_SHORT).show()
//            finish()
            }.addOnCanceledListener {
                Log.e("BookingOption retrieval failure", "Query cancelled")
            }
        } catch(e: Exception) {
            e.printStackTrace()
            Log.e("BookingOptions failure",e.message.toString())
        }


问:
Solving equation to find center point of circle from 3 points

I'm looking for a high precision solution to find the center point of a circle from 3 data points on a canvas (x,y). I found this example in the attached screenshot above, now I'm using the Math.NET package to solve the equation and I'm comparing the results against this online tool: https://planetcalc.com/8116/.

However, when I calculate the radius its completely off and often a negative number???

```<code>using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Double;
using System;

namespace ConsoleAppTestBed
{
  class Program
  {
    static void Main(string[] args)
    {
        var dataPoints = new double[,]
        {

            { 5, 80 },
            { 20, 100 },
            { 40, 140 }
        };

        var fitter = new CircleFitter();
        var result = fitter.Fit(dataPoints);

        var x = -result[0];
        var y = -result[1];
        var c = result[2];

        Console.WriteLine("Center Point:");
        Console.WriteLine(x);
        Console.WriteLine(y);
        Console.WriteLine(c);

        //// (x^2 + y^2 - c^2)
        var radius = Math.Pow(x, 2) + Math.Pow(y, 2) - Math.Pow(c, 2);
        //// sqrt((x^2 + y^2 - c^2))
        radius =  Math.Sqrt(radius);
        Console.WriteLine("Radius:");
        Console.WriteLine(radius);
        Console.ReadLine();
    }

    public class CircleFitter
    {
        public double[] Fit(double[,] v)
        {
            var xy1 = new double[] { v[0,0], v[0,1] };
            var xy2= new double[] { v[1, 0], v[1, 1] };
            var xy3 = new double[] { v[2, 0], v[2, 1] };

            // Create Left Side Matrix of Equation
            var a = CreateLeftSide_(xy1);
            var b = CreateLeftSide_(xy2);
            var c = CreateLeftSide_(xy3);
            var matrixA = DenseMatrix.OfArray(new[,]
            {
                { a[0], a[1], a[2] },
                { b[0], b[1], b[2] },
                { c[0], c[1], c[2] }
            });

            // Create Right Side Vector of Equation
            var d = CreateRightSide_(xy1);
            var e = CreateRightSide_(xy2);
            var f = CreateRightSide_(xy3);
            double[] vector = { d, e, f };
            var vectorB =  Vector<double>.Build.Dense(vector);

            // Solve Equation
            var r = matrixA.Solve(vectorB);
            var result = r.ToArray();

            return result;
        }

        //2x, 2y, 1
        public double[] CreateLeftSide_(double[] d)
        {
            return new double[] { (2 * d[0]), (2 * d[1]) , 1};

        }

        // -(x^2 + y^2)
        public double CreateRightSide_(double[] d)
        {
            return -(Math.Pow(d[0], 2) + Math.Pow(d[1], 2));

        }
    }
  }

}
</code>```

Any ideas?

Thanks in advance.

答:
I have just converted William Li's answer to Swift 5 for
those who like to cmd+C and cmd+V like me :)

```<code> func calculateCircle(){

    let x1:Float = 0
    let y1:Float = 0

    let x2:Float = 0.5
    let y2:Float = 0.5

    let x3:Float = 1
    let y3:Float = 0

    let x12 = x1 - x2
    let x13 = x1 - x3

    let y12 = y1 - y2
    let y13 = y1 - y3

    let y31 = y3 - y1
    let y21 = y2 - y1

    let x31 = x3 - x1
    let x21 = x2 - x1

    let sx13 = pow(x1, 2) - pow(x3, 2)

    let sy13 = pow(y1, 2) - pow(y3, 2)

    let sx21 = pow(x2, 2) - pow(x1, 2)

    let sy21 = pow(y2, 2) - pow(y1, 2)

    let f = ((sx13) * (x12)
                    + (sy13) * (x12)
                    + (sx21) * (x13)
                    + (sy21) * (x13))
                    / (2 * ((y31) * (x12) - (y21) * (x13)))

    let g = ((sx13) * (y12)
                    + (sy13) * (y12)
                    + (sx21) * (y13)
                    + (sy21) * (y13))
                    / (2 * ((x31) * (y12) - (x21) * (y13)))

    let c = -pow(x1, 2) - pow(y1, 2) - 2 * g * x1 - 2 * f * y1

    let h = -g
    let k = -f
    let r = sqrt(h * h + k * k - c)

    print("center x  = \(h)")
    print("center y = \(k)")
    print("r = \(r)")

}
</code>```

Body:
I'm looking for a high precision solution to find the center point of a circle from 3 data points on a canvas (x,y). I found this example in the attached screenshot above, now I'm using the Math.NET package to solve the equation and I'm comparing the results against this online tool: https://planetcalc.com/8116/.

However, when I calculate the radius its completely off and often a negative number???

using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Double;
using System;

namespace ConsoleAppTestBed
{
  class Program
  {
    static void Main(string[] args)
    {
        var dataPoints = new double[,]
        {

            { 5, 80 },
            { 20, 100 },
            { 40, 140 }
        };

        var fitter = new CircleFitter();
        var result = fitter.Fit(dataPoints);

        var x = -result[0];
        var y = -result[1];
        var c = result[2];

        Console.WriteLine("Center Point:");
        Console.WriteLine(x);
        Console.WriteLine(y);
        Console.WriteLine(c);

        //// (x^2 + y^2 - c^2)
        var radius = Math.Pow(x, 2) + Math.Pow(y, 2) - Math.Pow(c, 2);
        //// sqrt((x^2 + y^2 - c^2))
        radius =  Math.Sqrt(radius);
        Console.WriteLine("Radius:");
        Console.WriteLine(radius);
        Console.ReadLine();
    }

    public class CircleFitter
    {
        public double[] Fit(double[,] v)
        {
            var xy1 = new double[] { v[0,0], v[0,1] };
            var xy2= new double[] { v[1, 0], v[1, 1] };
            var xy3 = new double[] { v[2, 0], v[2, 1] };

            // Create Left Side Matrix of Equation
            var a = CreateLeftSide_(xy1);
            var b = CreateLeftSide_(xy2);
            var c = CreateLeftSide_(xy3);
            var matrixA = DenseMatrix.OfArray(new[,]
            {
                { a[0], a[1], a[2] },
                { b[0], b[1], b[2] },
                { c[0], c[1], c[2] }
            });

            // Create Right Side Vector of Equation
            var d = CreateRightSide_(xy1);
            var e = CreateRightSide_(xy2);
            var f = CreateRightSide_(xy3);
            double[] vector = { d, e, f };
            var vectorB =  Vector<double>.Build.Dense(vector);

            // Solve Equation
            var r = matrixA.Solve(vectorB);
            var result = r.ToArray();

            return result;
        }

        //2x, 2y, 1
        public double[] CreateLeftSide_(double[] d)
        {
            return new double[] { (2 * d[0]), (2 * d[1]) , 1};

        }

        // -(x^2 + y^2)
        public double CreateRightSide_(double[] d)
        {
            return -(Math.Pow(d[0], 2) + Math.Pow(d[1], 2));

        }
    }
  }

}

Any ideas?

Thanks in advance.

Body:
I have just converted William Li's answer to Swift 5 for
those who like to cmd+C and cmd+V like me :)

 func calculateCircle(){

    let x1:Float = 0
    let y1:Float = 0

    let x2:Float = 0.5
    let y2:Float = 0.5

    let x3:Float = 1
    let y3:Float = 0

    let x12 = x1 - x2
    let x13 = x1 - x3

    let y12 = y1 - y2
    let y13 = y1 - y3

    let y31 = y3 - y1
    let y21 = y2 - y1

    let x31 = x3 - x1
    let x21 = x2 - x1

    let sx13 = pow(x1, 2) - pow(x3, 2)

    let sy13 = pow(y1, 2) - pow(y3, 2)

    let sx21 = pow(x2, 2) - pow(x1, 2)

    let sy21 = pow(y2, 2) - pow(y1, 2)

    let f = ((sx13) * (x12)
                    + (sy13) * (x12)
                    + (sx21) * (x13)
                    + (sy21) * (x13))
                    / (2 * ((y31) * (x12) - (y21) * (x13)))

    let g = ((sx13) * (y12)
                    + (sy13) * (y12)
                    + (sx21) * (y13)
                    + (sy21) * (y13))
                    / (2 * ((x31) * (y12) - (x21) * (y13)))

    let c = -pow(x1, 2) - pow(y1, 2) - 2 * g * x1 - 2 * f * y1

    let h = -g
    let k = -f
    let r = sqrt(h * h + k * k - c)

    print("center x  = \(h)")
    print("center y = \(k)")
    print("r = \(r)")

}


问:
How do i align a background color for a text to an image?
im quite new to coding... and im making a portfolio that contains all the projects ive currently done... and i want to align the text background color to the image to sort of have a flushed in effect or somehting

```<code>    .project-tile{
        padding: 10px;
        width: 30%;
        border-radius: 10px;
        text-align: center;
        display: inline-block;
    }
    .project-tile img{
        max-height: 300px;
        max-width: 300px;
        box-shadow: 0 0 10px gray;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        background-color: rgba(128, 128, 128, 0.575);
    }
    .project-tile a{
        text-decoration: underline;
        color: rgb(255, 255, 255);
        font-size: 23px;
        background-color: rgba(128, 128, 128, 0.575);
        display: grid;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        height: 40px;
        align-items: center;
    }
</code>```

html

```<code>    <section id="projects">
        <h2>Here are few of my projects ive been working on</h2>
        <div class="project-tile">
            <a href="https://codepen.io/Leuqas/full/gOXLGoE">Tribute Page</a>
            <img src="https://cdn.discordapp.com/attachments/940847175867457547/940848284073885726/unknown.png" alt="picture">
        </div>
        <div class="project-tile">
            <a href="https://codepen.io/Leuqas/full/PoOWXWp">HTML Documentation Page</a>
            <img src="https://cdn.discordapp.com/attachments/940847175867457547/940847191801618442/unknown.png" alt="picture">
        </div>
        <div class="project-tile">
            <a href="https://codepen.io/Leuqas/full/xxPRMPX">Product Landing Page</a>
            <img src="https://cdn.discordapp.com/attachments/940847175867457547/940849497288880178/unknown.png" alt="picture">
        </div>
    </section>
</code>```

this are my current codes and what it looks like(picture)

答:
You can wrap all the divs in one div (I set its id to "wrapper") and set its display to flex. (didn't change anything else in your code)

#wrapper {
    display: flex; //<<----- The newly added
}

.project-tile{
    padding: 10px;
    width: 30%;
    border-radius: 10px;
    text-align: center;
    display: inline-block;
}
.project-tile img{
    max-height: 300px;
    max-width: 300px;
    box-shadow: 0 0 10px gray;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    background-color: rgba(128, 128, 128, 0.575);
}
.project-tile a{
    text-decoration: underline;
    color: rgb(255, 255, 255);
    font-size: 23px;
    background-color: rgba(128, 128, 128, 0.575);
    display: grid;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    height: 40px;
    align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="projects">
        <h2>Here are few of my projects ive been working on</h2>
        <div id="wrapper"> <!----The newly added------->
            <div class="project-tile">
                Tribute Page
                <img src="https://cdn.discordapp.com/attachments/940847175867457547/940848284073885726/unknown.png" alt="picture">
            </div>
            <div class="project-tile">
                HTML Documentation Page
                <img src="https://cdn.discordapp.com/attachments/940847175867457547/940847191801618442/unknown.png" alt="picture">
            </div>
            <div class="project-tile">
                Product Landing Page
                <img src="https://cdn.discordapp.com/attachments/940847175867457547/940849497288880178/unknown.png" alt="picture">
            </div>
        </div>
    </section></code>```

Body:
im quite new to coding... and im making a portfolio that contains all the projects ive currently done... and i want to align the text background color to the image to sort of have a flushed in effect or somehting

    .project-tile{
        padding: 10px;
        width: 30%;
        border-radius: 10px;
        text-align: center;
        display: inline-block;
    }
    .project-tile img{
        max-height: 300px;
        max-width: 300px;
        box-shadow: 0 0 10px gray;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        background-color: rgba(128, 128, 128, 0.575);
    }
    .project-tile a{
        text-decoration: underline;
        color: rgb(255, 255, 255);
        font-size: 23px;
        background-color: rgba(128, 128, 128, 0.575);
        display: grid;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        height: 40px;
        align-items: center;
    }

html

Here are few of my projects ive been working on

            Tribute Page

            HTML Documentation Page

            Product Landing Page

this are my current codes and what it looks like(picture)

Body:
You can wrap all the divs in one div (I set its id to "wrapper") and set its display to flex. (didn't change anything else in your code)

#wrapper {
    display: flex; //<<----- The newly added
}

.project-tile{
    padding: 10px;
    width: 30%;
    border-radius: 10px;
    text-align: center;
    display: inline-block;
}
.project-tile img{
    max-height: 300px;
    max-width: 300px;
    box-shadow: 0 0 10px gray;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    background-color: rgba(128, 128, 128, 0.575);
}
.project-tile a{
    text-decoration: underline;
    color: rgb(255, 255, 255);
    font-size: 23px;
    background-color: rgba(128, 128, 128, 0.575);
    display: grid;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    height: 40px;
    align-items: center;
}

<section id="projects">
        <h2>Here are few of my projects ive been working on</h2>
        <div id="wrapper"> <!----The newly added------->
            <div class="project-tile">
                <a href="https://codepen.io/Leuqas/full/gOXLGoE">Tribute Page</a>
                <img src="https://cdn.discordapp.com/attachments/940847175867457547/940848284073885726/unknown.png" alt="picture">
            </div>
            <div class="project-tile">
                <a href="https://codepen.io/Leuqas/full/PoOWXWp">HTML Documentation Page</a>
                <img src="https://cdn.discordapp.com/attachments/940847175867457547/940847191801618442/unknown.png" alt="picture">
            </div>
            <div class="project-tile">
                <a href="https://codepen.io/Leuqas/full/xxPRMPX">Product Landing Page</a>
                <img src="https://cdn.discordapp.com/attachments/940847175867457547/940849497288880178/unknown.png" alt="picture">
            </div>
        </div>
    </section>


问:
Why isn't ANTLR 4 recognising Unicode characters as valid tokens?
I have been struggling to get ANTLR 4 to recognise Unicode characters in the input.

I reduced my grammar to a simpler test I found on this answer to a related question, but all I've done is change the characters it's supposed to recognise, and it didn't work.

Grammar:

```<code>grammar Unicode;

stat: E_CODE* EOF;

E_CODE: '↊' | '↋';
</code>```

Test class:

class UnicodeTest {
    @Test
    fun `parse unicode`() {
        val lexer = UnicodeLexer(CharStreams.fromString("↊↋"))
        val parser = UnicodeParser(CommonTokenStream(lexer))
        val result = parser.stat().text
        println("Result = <$result>")
        assertThat(result).isEqualTo("↊↋<EOF>")
    }
}
```
<p>What I get when I run this is:</p>
<pre class="lang-none prettyprint-override"><code>> Task :test FAILED
line 1:0 token recognition error at: '↊'
line 1:1 token recognition error at: '↋'
Result = <<EOF>>

expected:<"[↊↋]<EOF>"> but was:<"[]<EOF>">
Expected :"[↊↋]<EOF>"
Actual   :"[]<EOF>"
</code>```

From stderr, it looks like it is correctly pulling the characters from my string as Unicode (it did start as a String so it had better!), but then not recognising the characters as a valid token.

I'm not sure how to debug this sort of thing, because the lexer rules get compiled into a giant blob that I can't figure out how to read. What I can verify is that tokens inside the lexer only contains one element, the EOF.

Ruled out so far:

The grammar file itself is UTF-8.

The Java compiler encoding is definitely set to UTF-8.

tasks.withType<JavaCompile> {
    // Why is this not yet the default? :(
    options.encoding = "UTF-8"
}
```
</li>
<li>The Kotlin compiler encoding is supposedly always UTF-8 with no option to change that. Mentioned only because I have no idea <em>which</em> compiler is used to compile the Java classes.</li>
<li>When I run tests, those also run as UTF-8.
<pre class="lang-kotlin prettyprint-override"><code>tasks.withType<Test> {
    useJUnitPlatform()
    defaultCharacterEncoding = "UTF-8"
}
</code>```

I get the same issue when running the code in my main program, where I can see on the command-line that -Dfile.encoding=UTF-8 is on the command-line.

Workaround?

If I change the grammar file to use Unicode escapes explicitly, then it works! So OK, there's something about how ANTLR is reading the file, where it isn't defaulting to UTF-8 as many people are saying it does. I plan to use a lot of Unicode though and would prefer not to have to escape everything. So I guess I just have to find some appropriate Gradle config to force the encoding when its compiler runs. :/

答:
How source files are compiled are (AFAIK) not important.

Using your example grammar as-is, I ran the following tests:

InputStream inputStream = new ByteArrayInputStream("↊↋".getBytes());
UnicodeLexer lexer = new UnicodeLexer(CharStreams.fromStream(inputStream, StandardCharsets.UTF_8));
UnicodeParser parser = new UnicodeParser(new CommonTokenStream(lexer));
System.out.println(parser.stat().getText());
```
<p>and:</p>
<pre class="lang-java prettyprint-override"><code>UnicodeLexer lexer = new UnicodeLexer(CharStreams.fromFileName("input.txt", StandardCharsets.UTF_8));
UnicodeParser parser = new UnicodeParser(new CommonTokenStream(lexer));
System.out.println(parser.stat().getText());
</code>```

(where the file input.txt contains ↊↋)

and both resulted in the following being printed to my console:

```<code>↊↋<EOF>
</code>```

I.e. did you try adding the encoding to the CharStream?

Body:
I have been struggling to get ANTLR 4 to recognise Unicode characters in the input.

I reduced my grammar to a simpler test I found on this answer to a related question, but all I've done is change the characters it's supposed to recognise, and it didn't work.

Grammar:

grammar Unicode;

stat: E_CODE* EOF;

E_CODE: '↊' | '↋';

Test class:

class UnicodeTest {
    @Test
    fun `parse unicode`() {
        val lexer = UnicodeLexer(CharStreams.fromString("↊↋"))
        val parser = UnicodeParser(CommonTokenStream(lexer))
        val result = parser.stat().text
        println("Result = <$result>")
        assertThat(result).isEqualTo("↊↋<EOF>")
    }
}

What I get when I run this is:

> Task :test FAILED
line 1:0 token recognition error at: '↊'
line 1:1 token recognition error at: '↋'
Result = <<EOF>>

expected:<"[↊↋]<EOF>"> but was:<"[]<EOF>">
Expected :"[↊↋]<EOF>"
Actual   :"[]<EOF>"

From stderr, it looks like it is correctly pulling the characters from my string as Unicode (it did start as a String so it had better!), but then not recognising the characters as a valid token.

I'm not sure how to debug this sort of thing, because the lexer rules get compiled into a giant blob that I can't figure out how to read. What I can verify is that tokens inside the lexer only contains one element, the EOF.

Ruled out so far:

The grammar file itself is UTF-8.

The Java compiler encoding is definitely set to UTF-8.

tasks.withType<JavaCompile> {
    // Why is this not yet the default? :(
    options.encoding = "UTF-8"
}

The Kotlin compiler encoding is supposedly always UTF-8 with no option to change that. Mentioned only because I have no idea which compiler is used to compile the Java classes.

When I run tests, those also run as UTF-8.

tasks.withType<Test> {
    useJUnitPlatform()
    defaultCharacterEncoding = "UTF-8"
}

I get the same issue when running the code in my main program, where I can see on the command-line that -Dfile.encoding=UTF-8 is on the command-line.

Workaround?

If I change the grammar file to use Unicode escapes explicitly, then it works! So OK, there's something about how ANTLR is reading the file, where it isn't defaulting to UTF-8 as many people are saying it does. I plan to use a lot of Unicode though and would prefer not to have to escape everything. So I guess I just have to find some appropriate Gradle config to force the encoding when its compiler runs. :/

Body:
How source files are compiled are (AFAIK) not important.

Using your example grammar as-is, I ran the following tests:

InputStream inputStream = new ByteArrayInputStream("↊↋".getBytes());
UnicodeLexer lexer = new UnicodeLexer(CharStreams.fromStream(inputStream, StandardCharsets.UTF_8));
UnicodeParser parser = new UnicodeParser(new CommonTokenStream(lexer));
System.out.println(parser.stat().getText());

and:

UnicodeLexer lexer = new UnicodeLexer(CharStreams.fromFileName("input.txt", StandardCharsets.UTF_8));
UnicodeParser parser = new UnicodeParser(new CommonTokenStream(lexer));
System.out.println(parser.stat().getText());

(where the file input.txt contains ↊↋)

and both resulted in the following being printed to my console:

↊↋<EOF>

I.e. did you try adding the encoding to the CharStream?


问:
Fill a 6x6 grid with 6 colors without same colors touching each other
I'm trying to create a board game with p5.js (Javascript)

To set up the game board which is a 6 by 6 grid, I have to fill the grid with 6 colors in a way that no horizontal or vertical touching cells have the same color. And all 6 colors have to be used in 6 cells.

But now I'm struggling a bit creating an algorithm that places the colors randomly but keeping the rules.

I tried to start at the top left corner, filling with a random color.
Then I start to fill the cell to the left and the bottom with a different color.

The problem is, that when the script wants to fill the last few cells, there are no colors left to use (either already 6 cells filled or a remaining color is a neighbor)

Example:
Still two cells need to be red, but only one place is left for red (under white):

```<code>//fill placedColors Array with zeros
placedColors = [];
for(let i=0; i<6; i++) {
    placedColors[i] = 0;
}

//fill allIndexes Array with indizies to keep control of visited cells
let allIndexes = [];
for(let i=0; i<36; i++) {
    allIndexes.push(i);
}

//build board
//when I set the limit to 36 the script runs forever because no solution is found
for(let i=0; i<33; i++) {
    fillCells(i);
}

function fillCells(index) {
    //get top and left color
    let topColor = false;
    //index is in the second row
    if(index >= 6) {
        topColor = cells[index-6].color;
    }

    let leftColor = false;
    //index is not in the first column
    if(index % 6 > 0 && index > 0) {
        leftColor = cells[index-1].color;
    }

    if(allIndexes.indexOf(index) > -1) {
        cells.push(new Cell(index, pickColor(topColor, leftColor)));
    }

    //mark index as visited
    var allIndexesIndex = allIndexes.indexOf(index);
    if (allIndexesIndex !== -1) {
        allIndexes.splice(allIndexesIndex, 1);
    }
}

function pickColor(invalidColor1,invalidColor2) {
    let colorFound = false;
    do {
        randColor = floor(random(6));

        if(placedColors[randColor] < 6 && randColor!=invalidColor1 && randColor!=invalidColor2) {
            placedColors[randColor]++;
            colorFound = true;
        }
    } while(!colorFound);

    return randColor;
}

</code>```

答:
Thanks for your suggestions! I tried to find an own solution parallel to the posted one. Now with this code, it works fine:</p>
```<code>function buildBoard() {
    cells = [];

    for(let i=0; i<gameSize; i++) {
        placedColors[i] = 0;
    }

    for(var i=0; i<gameSize*gameSize; i++) {
        cells.push(new Cell(i, pickColor()));
    }

    do {
        invalidFields = [];
        findInvalidFields();

        if(invalidFields.length > 0) {
            let cell1index = Math.floor(Math.random() * invalidFields.length);
            cell1 = invalidFields[cell1index];
            //check, if cell in different color available
            let otherColorAvailable = false;
            for(cell of invalidFields) {
                if(cell.color != cell1.color) {
                    otherColorAvailable = true;
                    break;
                }
            }

            if(otherColorAvailable) {
                //pick invalid cell
                do {
                    let cell2index = Math.floor(Math.random() * invalidFields.length);
                    cell2 = invalidFields[cell2index];
                } while (cell2.color == cell1.color)
            } else {
                //pick random cell
                do {
                    let cell2index = Math.floor(Math.random() * cells.length);
                    cell2 = cells[cell2index];
                } while (cell2.color == cell1.color)
            }

            //switch colors of cells
            let tempColor = cell1.color;
            cell1.color = cell2.color;
            cell2.color = tempColor;
        }
    } while (!checkStartField());
}

function findInvalidFields() {
    for(let index=0; index<cells.length; index++) {
        let thisColor = cells[index].color;

        //right
        if(index%gameSize < gameSize-1 && cells[index+1].color == thisColor) {
            if(invalidFields.indexOf(cells[index+1])) {
                invalidFields.push(cells[index+1]);
            }
        }

        //bottom
        if(index < gameSize*gameSize-gameSize && cells[index+gameSize].color == thisColor) {
            if(invalidFields.indexOf(cells[index+gameSize])) {
                invalidFields.push(cells[index+gameSize]);
            }
        }
    }
}

function checkStartField() {
    for(let index=0; index<cells.length; index++) {
        let thisColor = cells[index].color;

        //top
        if(index >= gameSize && cells[index-gameSize].color == thisColor) {
            //console.log(index+'top');
            return false;
        }

        //right
        if(index%gameSize < gameSize-1 && cells[index+1].color == thisColor) {
            //console.log(index+'right');
            return false;
        }

        //bottom
        if(index < gameSize*gameSize-gameSize && cells[index+gameSize].color == thisColor) {
            //console.log(index+'bottom');
            return false;
        }

        //left
        if(index%gameSize > 0 && cells[index-1].color == thisColor) {
            //console.log(index+'left');
            return false;
        }
    }

    return true;
}
</code>```

Body:
I'm trying to create a board game with p5.js (Javascript)

To set up the game board which is a 6 by 6 grid, I have to fill the grid with 6 colors in a way that no horizontal or vertical touching cells have the same color. And all 6 colors have to be used in 6 cells.

But now I'm struggling a bit creating an algorithm that places the colors randomly but keeping the rules.

I tried to start at the top left corner, filling with a random color.
Then I start to fill the cell to the left and the bottom with a different color.

The problem is, that when the script wants to fill the last few cells, there are no colors left to use (either already 6 cells filled or a remaining color is a neighbor)

Example:
Still two cells need to be red, but only one place is left for red (under white):

//fill placedColors Array with zeros
placedColors = [];
for(let i=0; i<6; i++) {
    placedColors[i] = 0;
}

//fill allIndexes Array with indizies to keep control of visited cells
let allIndexes = [];
for(let i=0; i<36; i++) {
    allIndexes.push(i);
}

//build board
//when I set the limit to 36 the script runs forever because no solution is found
for(let i=0; i<33; i++) {
    fillCells(i);
}

function fillCells(index) {
    //get top and left color
    let topColor = false;
    //index is in the second row
    if(index >= 6) {
        topColor = cells[index-6].color;
    }

    let leftColor = false;
    //index is not in the first column
    if(index % 6 > 0 && index > 0) {
        leftColor = cells[index-1].color;
    }

    if(allIndexes.indexOf(index) > -1) {
        cells.push(new Cell(index, pickColor(topColor, leftColor)));
    }

    //mark index as visited
    var allIndexesIndex = allIndexes.indexOf(index);
    if (allIndexesIndex !== -1) {
        allIndexes.splice(allIndexesIndex, 1);
    }
}

function pickColor(invalidColor1,invalidColor2) {
    let colorFound = false;
    do {
        randColor = floor(random(6));

        if(placedColors[randColor] < 6 && randColor!=invalidColor1 && randColor!=invalidColor2) {
            placedColors[randColor]++;
            colorFound = true;
        }
    } while(!colorFound);

    return randColor;
}

Body:
Thanks for your suggestions! I tried to find an own solution parallel to the posted one. Now with this code, it works fine:

function buildBoard() {
    cells = [];

    for(let i=0; i<gameSize; i++) {
        placedColors[i] = 0;
    }

    for(var i=0; i<gameSize*gameSize; i++) {
        cells.push(new Cell(i, pickColor()));
    }

    do {
        invalidFields = [];
        findInvalidFields();

        if(invalidFields.length > 0) {
            let cell1index = Math.floor(Math.random() * invalidFields.length);
            cell1 = invalidFields[cell1index];
            //check, if cell in different color available
            let otherColorAvailable = false;
            for(cell of invalidFields) {
                if(cell.color != cell1.color) {
                    otherColorAvailable = true;
                    break;
                }
            }

            if(otherColorAvailable) {
                //pick invalid cell
                do {
                    let cell2index = Math.floor(Math.random() * invalidFields.length);
                    cell2 = invalidFields[cell2index];
                } while (cell2.color == cell1.color)
            } else {
                //pick random cell
                do {
                    let cell2index = Math.floor(Math.random() * cells.length);
                    cell2 = cells[cell2index];
                } while (cell2.color == cell1.color)
            }

            //switch colors of cells
            let tempColor = cell1.color;
            cell1.color = cell2.color;
            cell2.color = tempColor;
        }
    } while (!checkStartField());
}

function findInvalidFields() {
    for(let index=0; index<cells.length; index++) {
        let thisColor = cells[index].color;

        //right
        if(index%gameSize < gameSize-1 && cells[index+1].color == thisColor) {
            if(invalidFields.indexOf(cells[index+1])) {
                invalidFields.push(cells[index+1]);
            }
        }

        //bottom
        if(index < gameSize*gameSize-gameSize && cells[index+gameSize].color == thisColor) {
            if(invalidFields.indexOf(cells[index+gameSize])) {
                invalidFields.push(cells[index+gameSize]);
            }
        }
    }
}

function checkStartField() {
    for(let index=0; index<cells.length; index++) {
        let thisColor = cells[index].color;

        //top
        if(index >= gameSize && cells[index-gameSize].color == thisColor) {
            //console.log(index+'top');
            return false;
        }

        //right
        if(index%gameSize < gameSize-1 && cells[index+1].color == thisColor) {
            //console.log(index+'right');
            return false;
        }

        //bottom
        if(index < gameSize*gameSize-gameSize && cells[index+gameSize].color == thisColor) {
            //console.log(index+'bottom');
            return false;
        }

        //left
        if(index%gameSize > 0 && cells[index-1].color == thisColor) {
            //console.log(index+'left');
            return false;
        }
    }

    return true;
}


问:
How to display a mysql database without refreshing the page with data from GET data without clicking button
My Problem is trying to display value from the database without refreshing the page.

Ok, My Code consist of value retrieve from page 1 to page 2 using GET methods, let's say the value is captured from the data-name "location" which consist of the value of 3.

The value of "location" on page 2 is then used to grab the information of the user on which location is stored and display the data that needs to display on a table on page 2 without clicking any button, basically on page load, it will display the data.

Then to make the data automatically update without refresh, I tried using a method that needs me to use Ajax that uses a GET to page 3 which supposedly have all the PHP to select database MySQL scripts.

In the PHP to select database MySQL scripts, my codes require to use the "location" data from page 2 that retrieve from page 1.

Since I need to POST using an ajax script, I added a PHP script into my Ajax script with a return value from page 3 data as well.

But it does not show the value that needs to be shown. Your help or guidance is highly appreciated.  Thank You in advance.

Here are my codes for Page 2 (display page)

```<code>$locationID = @$_GET['location'];

    $sqlCheckVisitors = "SELECT * FROM visitor_list WHERE visitor_EventChooseID = '$locationID'";
    $resultCheckVisitors = $conn->query($sqlCheckVisitors);
    $calCheckResult_visitor = mysqli_num_rows($resultCheckVisitors);
        if($calCheckResult_visitor > 0)
            {
                $value_originalVisit =  $calCheckResult_visitor;
            }
        else
            {
                $value_originalVisit = 0;
            }
</code>```

```<code><div class="row">
    <div class="form-group col">
        <label class="form-control form-control-lg text-8 text-center">Live Balance : <br>
            <div id="live_totalbalance"></div>
                /
            <div id="live_totalpreset"></div>
        </label>
    </div>
</div>
</code>```

```<code><script type="text/javascript">
    $(document).ready(function(){
        // Display Total Live Balance
        $.ajax({
            url: "livedata_totalbalance.php?locationID=<?php echo $locationID ;?>",
            type: "GET",
            dataType: "html",
            cache: "false",
            success: function(data)
            {
                $('#live_totalbalance').html(data);
            }
        });
    });
</script>
</code>```

Here are my codes for Page 3 (livedata_totalbalance.php)

```<code><?php
    include "database.php";

    $locationID = @$_GET['locationID'];

    $sqlEventList = "SELECT * FROM event_list WHERE event_id ='$locationID'";
    $resultEventList = $conn->query($sqlEventList);
    $dataEventList = mysqli_fetch_array($resultEventList);

    $event_data = $dataEventList['event_data'];

    echo $event_data;
?>
</code>```

答:
If you want to change the data in a certain period of time Or change it for example after user landed on you page without refreshing the page, you could put your ajax in a JS timer like this:

```<code>setTimeout(() => {
     $.ajax({
            url: "livedata_totalbalance.php?locationID=<?php echo $locationID ;?>",
            type: "GET",
            dataType: "html",
            cache: "false",
            success: function(data)
            {
                $('#live_totalbalance').html(data);
            }
        });
}, 2000);
</code>```

this will get new data after 2 Seconds (2000 ms).
or even if you want to change data in every 2 seconds, you can put this code in a for or while loop.

Hope it works :)

Body:
My Problem is trying to display value from the database without refreshing the page.

Ok, My Code consist of value retrieve from page 1 to page 2 using GET methods, let's say the value is captured from the data-name "location" which consist of the value of 3.

The value of "location" on page 2 is then used to grab the information of the user on which location is stored and display the data that needs to display on a table on page 2 without clicking any button, basically on page load, it will display the data.

Then to make the data automatically update without refresh, I tried using a method that needs me to use Ajax that uses a GET to page 3 which supposedly have all the PHP to select database MySQL scripts.

In the PHP to select database MySQL scripts, my codes require to use the "location" data from page 2 that retrieve from page 1.

Since I need to POST using an ajax script, I added a PHP script into my Ajax script with a return value from page 3 data as well.

But it does not show the value that needs to be shown. Your help or guidance is highly appreciated.  Thank You in advance.

Here are my codes for Page 2 (display page)

$locationID = @$_GET['location'];

    $sqlCheckVisitors = "SELECT * FROM visitor_list WHERE visitor_EventChooseID = '$locationID'";
    $resultCheckVisitors = $conn->query($sqlCheckVisitors);
    $calCheckResult_visitor = mysqli_num_rows($resultCheckVisitors);
        if($calCheckResult_visitor > 0)
            {
                $value_originalVisit =  $calCheckResult_visitor;
            }
        else
            {
                $value_originalVisit = 0;
            }

        Live Balance :

                /

Here are my codes for Page 3 (livedata_totalbalance.php)

<?php
    include "database.php";

    $locationID = @$_GET['locationID'];

    $sqlEventList = "SELECT * FROM event_list WHERE event_id ='$locationID'";
    $resultEventList = $conn->query($sqlEventList);
    $dataEventList = mysqli_fetch_array($resultEventList);

    $event_data = $dataEventList['event_data'];

    echo $event_data;
?>

Body:
If you want to change the data in a certain period of time Or change it for example after user landed on you page without refreshing the page, you could put your ajax in a JS timer like this:

setTimeout(() => {
     $.ajax({
            url: "livedata_totalbalance.php?locationID=<?php echo $locationID ;?>",
            type: "GET",
            dataType: "html",
            cache: "false",
            success: function(data)
            {
                $('#live_totalbalance').html(data);
            }
        });
}, 2000);

this will get new data after 2 Seconds (2000 ms).
or even if you want to change data in every 2 seconds, you can put this code in a for or while loop.

Hope it works :)


问:
Always up to date content using AJAX
At the moment I am using ajax requests every 10 minutes to update certain content and other time intervals for others.

I do this using jQuery by:

On mouse move, the active page is checked

If the active page has not be updated within the given time interval, the page is updated

I'm doing this because although i want the content to stay up to date, I don't want it to be sending requests in the background (when the user is not using the application). Doing this also means that if the user has not used it for more than the time period, when they start to use it again it will automatically update.

I'm wondering just how efficient this is as whenever the mouse moves the checks are called (and has slowed down performance a bit - especially when trying to click links) - is the a more efficient way to do this?

Thanks!

答:
Another possible solution would be to use the window blur and focus events to determine if the window is active:

```<code>var checkForContentUpdates = true;

$(window).focus(function() {
    checkForContentUpdates = true;
});

$(window).blur(function() {
    checkForContentUpdates = false;
});
</code>```

Your AJAX routine would then key off of the checkForContentUpdates bool.

I'm sure that there are scenarios where this isn't fool-proof, so you'd likely have to combine this method with other logic.

Title: Always up to date content using AJAX

Body:
Another possible solution would be to use the window blur and focus events to determine if the window is active:

var checkForContentUpdates = true;

$(window).focus(function() {
    checkForContentUpdates = true;
});

$(window).blur(function() {
    checkForContentUpdates = false;
});

Your AJAX routine would then key off of the checkForContentUpdates bool.

I'm sure that there are scenarios where this isn't fool-proof, so you'd likely have to combine this method with other logic.