问:
flutter app architecture and state management with provider, correct usage?
I'm working on understanding the flow of data through a flutter application and state management methods. I made this flow chart to try and create a visual of what I hope to do to help guide me. All the firebase reads and writes are going through UserModel (small application, only data that is variable is UserModel which is like a profile + stats etc.), this way I can save locally or push to firebase when the user has an online connection.

widgets in green are displayed, in total this app is only two pages, main page and onboarding. Mainpage is comprised of a navigation bar with two screen widgets and a modal on one of those screens.

My question is, is the structure that I have above an efficient and logical use of these tools? Suggestions on improving it if necessary?

Also, the pathing arrow between firebase and user model should be two way


来源: stackexchange

问:
Helping with a layout xml issue
I want to put the checkmark inside the Name text as in the image, but I couldn't, no matter what I do, it stays outside and when the Name gets longer, the checkmark disappears. What I want to do is to have the Checkmark next to the Name text and give a match_parent

My code

```<code><TextView
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="16dp"
    android:fontFamily="sans-serif-black"
    android:text="Hiddy"
    android:textColor="?attr/textcolor"
    android:textSize="20sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/circleImageView"
    tools:ignore="HardcodedText" />

<ImageView
    android:id="@+id/verified"
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:layout_marginStart="8dp"
    android:src="@drawable/ic_verify"
    android:visibility="gone"
    app:layout_constraintBottom_toBottomOf="@+id/name"
    app:layout_constraintStart_toEndOf="@+id/name"
    app:layout_constraintTop_toTopOf="@+id/name"
    android:contentDescription="TODO"
    tools:ignore="ContentDescription,HardcodedText" />

<TextView
    android:id="@+id/username"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="3dp"
    android:layout_marginEnd="16dp"
    android:fontFamily="sans-serif-black"
    android:text="hiddy"
    android:textColor="?attr/texttwocolor"
    android:textSize="18sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/name"
    tools:ignore="HardcodedText" />
</code>```

Screenshot

ContentLicense: CC BY-SA 4.0

Title: Helping with a layout xml issue

Body:
I want to put the checkmark inside the Name text as in the image, but I couldn't, no matter what I do, it stays outside and when the Name gets longer, the checkmark disappears. What I want to do is to have the Checkmark next to the Name text and give a match_parent

My code

<TextView
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="16dp"
    android:fontFamily="sans-serif-black"
    android:text="Hiddy"
    android:textColor="?attr/textcolor"
    android:textSize="20sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/circleImageView"
    tools:ignore="HardcodedText" />

<ImageView
    android:id="@+id/verified"
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:layout_marginStart="8dp"
    android:src="@drawable/ic_verify"
    android:visibility="gone"
    app:layout_constraintBottom_toBottomOf="@+id/name"
    app:layout_constraintStart_toEndOf="@+id/name"
    app:layout_constraintTop_toTopOf="@+id/name"
    android:contentDescription="TODO"
    tools:ignore="ContentDescription,HardcodedText" />

<TextView
    android:id="@+id/username"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="3dp"
    android:layout_marginEnd="16dp"
    android:fontFamily="sans-serif-black"
    android:text="hiddy"
    android:textColor="?attr/texttwocolor"
    android:textSize="18sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/name"
    tools:ignore="HardcodedText" />

Screenshot


问:
AWS EMR CLI add-step with multiple files
I have an EMR environment that runs fine when I submit single python (pyspark) files from a local shell script (myProgram.py was already copied up to S3...):

```<code>aws emr add-steps \
  --cluster-id $CID \
  --steps Type=Spark,\
Name="chessAnalytics",\
ActionOnFailure=CONTINUE,\
Args=[s3://$SRC_BUCKET/myProgram.py,\
--gameset1,\'$GAMESET1_URI\',\
--gameset2,\'$GAMESET2_URI\',\
--output_uri,s3://$OUT_BUCKET/V4_t]
</code>```

I wish to factor some utils out of myProgram.py into a peer file utils.py.  All the docs on this keep coming back to the --py-files option for spark-submit and using a zip file.   I am not using spark-submit; I am using aws emr add-steps.  Rather blindly, I tried adding --py-files to the add-steps launch:

```<code>aws emr add-steps \
  --cluster-id $CID \
  --steps Type=Spark,\
Name="chessAnalytics",\
ActionOnFailure=CONTINUE,\
Args=[--py-files,s3://$SRC_BUCKET/myZipFile.zip,\
--gameset1,\'$GAMESET1_URI\',\
--gameset2,\'$GAMESET2_URI\',\
--output_uri,s3://$OUT_BUCKET/V4_t]
</code>```

But this fails with error Error: Unrecognized option: --gameset1

What is an appropriate way to bundle multiple python files for pyspark exec on AWS EMR using the local CLI (aws emr add-step)?`

Body:
I have an EMR environment that runs fine when I submit single python (pyspark) files from a local shell script (myProgram.py was already copied up to S3...):

aws emr add-steps \
  --cluster-id $CID \
  --steps Type=Spark,\
Name="chessAnalytics",\
ActionOnFailure=CONTINUE,\
Args=[s3://$SRC_BUCKET/myProgram.py,\
--gameset1,\'$GAMESET1_URI\',\
--gameset2,\'$GAMESET2_URI\',\
--output_uri,s3://$OUT_BUCKET/V4_t]

I wish to factor some utils out of myProgram.py into a peer file utils.py.  All the docs on this keep coming back to the --py-files option for spark-submit and using a zip file.   I am not using spark-submit; I am using aws emr add-steps.  Rather blindly, I tried adding --py-files to the add-steps launch:

aws emr add-steps \
  --cluster-id $CID \
  --steps Type=Spark,\
Name="chessAnalytics",\
ActionOnFailure=CONTINUE,\
Args=[--py-files,s3://$SRC_BUCKET/myZipFile.zip,\
--gameset1,\'$GAMESET1_URI\',\
--gameset2,\'$GAMESET2_URI\',\
--output_uri,s3://$OUT_BUCKET/V4_t]

But this fails with error Error: Unrecognized option: --gameset1

What is an appropriate way to bundle multiple python files for pyspark exec on AWS EMR using the local CLI (aws emr add-step)?`


问:
Installed packages goes to the wrong folder in pycharm
I typed pip install Django into the pycharm terminal and it installed the Django files to python311\lib\site-packages, an excluded directory, instead of python311\site-packages.


问:
How to instrumentation test multi module fragments in a single activity Android app that requires activity application
I implemented a single activity multi module app. The fragment in the module uses the activity?.application as BaseApplication to get the dao for the fragment view model. Now, writing the espresso test, calling

```<code>launchFragmentInContainer<AddTripFragment>(themeResId = R.style.Theme)
</code>```

it's calling a

```<code>java.lang.ClassCastException: android.app.Application cannot be cast to com.example.core.ui.BaseApplication
</code>```

Is there a way to provide some type of application for the test case?

```<code>class ModuleFragment : Fragment() {

    private val viewModel: ModuleViewModel by activityViewModels {
        ModuleViewModelFactory(((activity?.application as BaseApplication).database).dao())
    }
}
</code>```
```<code>@RunWith(AndroidJUnit4::class)
class ModuleFragmentTest {
    private lateinit var scenario: FragmentScenario<ModuleFragment>

    @Before
    fun setup() {
        scenario = launchFragmentInContainer(themeResId = R.style)
    }
}

</code>```

I've tried to declare the app's module main activity test rule. However, that doesn't take me too far and is also leading to circular dependency.

```<code>    val activityRule = ActivityTestRule(MainActivity::class.java)

</code>```

Body:
I implemented a single activity multi module app. The fragment in the module uses the activity?.application as BaseApplication to get the dao for the fragment view model. Now, writing the espresso test, calling

launchFragmentInContainer<AddTripFragment>(themeResId = R.style.Theme)

it's calling a

java.lang.ClassCastException: android.app.Application cannot be cast to com.example.core.ui.BaseApplication

Is there a way to provide some type of application for the test case?

class ModuleFragment : Fragment() {

    private val viewModel: ModuleViewModel by activityViewModels {
        ModuleViewModelFactory(((activity?.application as BaseApplication).database).dao())
    }
}

@RunWith(AndroidJUnit4::class)
class ModuleFragmentTest {
    private lateinit var scenario: FragmentScenario<ModuleFragment>

    @Before
    fun setup() {
        scenario = launchFragmentInContainer(themeResId = R.style)
    }
}

I've tried to declare the app's module main activity test rule. However, that doesn't take me too far and is also leading to circular dependency.

    val activityRule = ActivityTestRule(MainActivity::class.java)


问:
How to copy CSV to TABLE if CSV contains too many columns to pre-create table? (Postgress)
I want to copy a U.S. Census CSV to a table, however, the CSV header contains well over 200+ columns. How can I tell Postgress SQL to create a table from the CSV using the header as column names?</p>


问:
Should Retrofit and okHttp dependencies be omitted from testing source sets in favour of mockwebserver?
I am reviewing the dependencies in my build.gradle.kts file and noticed for Retrofit and okHttp i have a bunch of dependencies in implementation, testImplementation and androidTestImplementation. Are network dependencies like Retrofit and okHttp really needed for testImplementation and androidTestImplementation. should I only be using mockwebserver in these testing source sets?

```<code>//current
    implementation(Retrofit.okHttp)
    implementation(Retrofit.loggingInterceptor)
    implementation(Retrofit.retrofit)
    implementation(Retrofit.converterGson)
    implementation(Retrofit.converterMoshi)

    testImplementation(UnitTesting.mockwebserver)
    testImplementation(UnitTesting.okHttp)
    testImplementation(UnitTesting.loggingInterceptor)
    testImplementation(UnitTesting.retrofit)
    testImplementation(UnitTesting.converterGson)
    testImplementation(UnitTesting.converterMoshi)

    androidTestImplementation(Testing.mockwebserver)
    androidTestImplementation(Testing.okHttp)
    androidTestImplementation(Testing.loggingInterceptor)
    androidTestImplementation(Testing.retrofit)
    androidTestImplementation(Testing.converterGson)
    androidTestImplementation(Testing.converterMoshi)

//proposed
    implementation(Retrofit.okHttp)
    implementation(Retrofit.loggingInterceptor)
    implementation(Retrofit.retrofit)
    implementation(Retrofit.converterGson)
    implementation(Retrofit.converterMoshi)

    testImplementation(UnitTesting.mockwebserver)

    androidTestImplementation(Testing.mockwebserver)

</code>```

Body:
I am reviewing the dependencies in my build.gradle.kts file and noticed for Retrofit and okHttp i have a bunch of dependencies in implementation, testImplementation and androidTestImplementation. Are network dependencies like Retrofit and okHttp really needed for testImplementation and androidTestImplementation. should I only be using mockwebserver in these testing source sets?

//current
    implementation(Retrofit.okHttp)
    implementation(Retrofit.loggingInterceptor)
    implementation(Retrofit.retrofit)
    implementation(Retrofit.converterGson)
    implementation(Retrofit.converterMoshi)

    testImplementation(UnitTesting.mockwebserver)
    testImplementation(UnitTesting.okHttp)
    testImplementation(UnitTesting.loggingInterceptor)
    testImplementation(UnitTesting.retrofit)
    testImplementation(UnitTesting.converterGson)
    testImplementation(UnitTesting.converterMoshi)

    androidTestImplementation(Testing.mockwebserver)
    androidTestImplementation(Testing.okHttp)
    androidTestImplementation(Testing.loggingInterceptor)
    androidTestImplementation(Testing.retrofit)
    androidTestImplementation(Testing.converterGson)
    androidTestImplementation(Testing.converterMoshi)

//proposed
    implementation(Retrofit.okHttp)
    implementation(Retrofit.loggingInterceptor)
    implementation(Retrofit.retrofit)
    implementation(Retrofit.converterGson)
    implementation(Retrofit.converterMoshi)

    testImplementation(UnitTesting.mockwebserver)

    androidTestImplementation(Testing.mockwebserver)


问:
makemigrations for a second app (branches) throwing 'Django.template module not found' when run
I successfully made migration module for a database for my first app, but when I made a second app with a brand new model, I could not do the same for the second app.

python3 Web_Design/manage.py makemigrations branches
end of error thrown
beggining of error thrown and settings in pyshop package
model created in second app (branches)


问:
Which are the default permissions, owner and group of an azure files share?
Which are the default permissions, owner and group of an Azure files share? (Permissions 770, owner root and group root?)</p>


问:
Get API response after logging in using rvest
Using a browser, I can navigate to https://myaccount.draftkings.com/login and login using a username and password. Then if I navigate to https://api.draftkings.com/scores/v1/leaderboards/9000?format=json&embed=leaderboard in another tab, I can see the API response.

I want to do this programmatically.

There is a python package that I previously used successfully for this purpose. But for some reason, I can't get that package to work now.

I believe the python package hits an API endpoint with a post request to authenticate and saves the cookies to a file that are later used to make requests.

I tried sending a post request to the login endpoint the python package uses with httr2:

req <- httr2::request("https://api.draftkings.com/users/v3/providers/draftkings/logins?format=json") %>%
  httr2::req_method("POST") %>%
  httr2::req_headers(
    "Contest-Type" = "application/json",
    "Accept" = "*/*",
    "Accept-Encoding" = "gzip, deflate, br"
  ) %>%
  httr2::req_body_json(
   list(
     "login" = "email",
     "password" = "password",
     "host" = "api.draftkings.com",
     "challengeResponse" = list("solution" = "", "type" = "Recaptcha")
   )
  )

req %>%
  httr2::req_perform()
```
<p>but I get a 403 error.</p>
<hr />
<p>I also tried logging in using <code>rvest</code>:</p>
<pre class="lang-r prettyprint-override"><code>library(rvest)

url <- "myaccount.draftkings.com/login"
session <- session(url)

form <- session %>%
  html_form() %>%
  magrittr::extract2(1)

form$action <- url

filled_form <- form %>%
  html_form_set(!!! list(EmailOrUsername = "user",
                         Password = 'password'))

html_form_submit(filled_form, submit = 3)

session_jump_to(session, "https://www.draftkings.com/lobby")
</code>```

but that didn't seem to do what I want either. Note that the form object returned an empty action element. I'm not sure what to replace the action element with, but if I leave it null I get an error.

I also tried saving the cookies from a browser session after logging into draftkings.com and passing all the cookies to a GET request with httr:

cook <- jsonlite::read_json("cookies.json")

clean_cook <- unlist(lapply(cook, function(x) {stats::setNames(x$value, x$name)}))

resp <- httr::GET(
  "https://api.draftkings.com/scores/v1/leaderboards/9000?format=json&embed=leaderboard",
  httr::set_cookies(.cookies = clean_cook)
)

httr::content(resp)
```
<p>but this returns a 400 error code and message "Invalid userKey.". This is the same error message I get if I clear my cache in the browser and then visit  https://api.draftkings.com/scores/v1/leaderboards/9000?format=json&embed=leaderboard. I don't think the issue is related to URL encoding of the cache values. I tried restarting my RStudio session.</p>
<hr />
<p><strong>Update</strong></p>
<p>I figured out how to successfully perform the GET request using the cookies saved from my browser and <code>httr2</code>:</p>
<pre class="lang-r prettyprint-override"><code>cook <- jsonlite::read_json("cookies.json")

clean_cook <- paste0(unlist(lapply(cook, function(x) {paste0(x$name, "=", x$value)})), collapse = ";")

req <- httr2::request(
  "https://api.draftkings.com/scores/v1/leaderboards/9000?format=json&embed=leaderboard"
)

req <- httr2::req_headers(req, "cookie" = clean_cook)

resp <- httr2::req_perform(req)

str(httr2::resp_body_json(resp))
</code>```

For some reason, I was unable to get httr::set_cookies() to work. Passing cookies in the header (using httr::add_headers) was also not reliably successful using httr.

Body:
Using a browser, I can navigate to https://myaccount.draftkings.com/login and login using a username and password. Then if I navigate to https://api.draftkings.com/scores/v1/leaderboards/9000?format=json&embed=leaderboard in another tab, I can see the API response.

I want to do this programmatically.

There is a python package that I previously used successfully for this purpose. But for some reason, I can't get that package to work now.

I believe the python package hits an API endpoint with a post request to authenticate and saves the cookies to a file that are later used to make requests.

I tried sending a post request to the login endpoint the python package uses with httr2:

req <- httr2::request("https://api.draftkings.com/users/v3/providers/draftkings/logins?format=json") %>%
  httr2::req_method("POST") %>%
  httr2::req_headers(
    "Contest-Type" = "application/json",
    "Accept" = "*/*",
    "Accept-Encoding" = "gzip, deflate, br"
  ) %>%
  httr2::req_body_json(
   list(
     "login" = "email",
     "password" = "password",
     "host" = "api.draftkings.com",
     "challengeResponse" = list("solution" = "", "type" = "Recaptcha")
   )
  )

req %>%
  httr2::req_perform()

but I get a 403 error.

I also tried logging in using rvest:

library(rvest)

url <- "myaccount.draftkings.com/login"
session <- session(url)

form <- session %>%
  html_form() %>%
  magrittr::extract2(1)

form$action <- url

filled_form <- form %>%
  html_form_set(!!! list(EmailOrUsername = "user",
                         Password = 'password'))

html_form_submit(filled_form, submit = 3)

session_jump_to(session, "https://www.draftkings.com/lobby")

but that didn't seem to do what I want either. Note that the form object returned an empty action element. I'm not sure what to replace the action element with, but if I leave it null I get an error.

I also tried saving the cookies from a browser session after logging into draftkings.com and passing all the cookies to a GET request with httr:

cook <- jsonlite::read_json("cookies.json")

clean_cook <- unlist(lapply(cook, function(x) {stats::setNames(x$value, x$name)}))

resp <- httr::GET(
  "https://api.draftkings.com/scores/v1/leaderboards/9000?format=json&embed=leaderboard",
  httr::set_cookies(.cookies = clean_cook)
)

httr::content(resp)

but this returns a 400 error code and message "Invalid userKey.". This is the same error message I get if I clear my cache in the browser and then visit  https://api.draftkings.com/scores/v1/leaderboards/9000?format=json&embed=leaderboard. I don't think the issue is related to URL encoding of the cache values. I tried restarting my RStudio session.

Update

I figured out how to successfully perform the GET request using the cookies saved from my browser and httr2:

cook <- jsonlite::read_json("cookies.json")

clean_cook <- paste0(unlist(lapply(cook, function(x) {paste0(x$name, "=", x$value)})), collapse = ";")

req <- httr2::request(
  "https://api.draftkings.com/scores/v1/leaderboards/9000?format=json&embed=leaderboard"
)

req <- httr2::req_headers(req, "cookie" = clean_cook)

resp <- httr2::req_perform(req)

str(httr2::resp_body_json(resp))

For some reason, I was unable to get httr::set_cookies() to work. Passing cookies in the header (using httr::add_headers) was also not reliably successful using httr.


问:
In Python, print(lines) only working when code below is uncommented. Not inside conditional or after return
I have a Python script that opens text files and then saves them as newly parsed files.

The code works: print(lines) on line 69 prints the parsed contents and the names of the files are also output if writing is successful.

However, if I remove or comment all of the code below line 70, print(lines) on 69 no longer works.

```<code>import os
import re

def parse_file(file_path):

  # open the file
  with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
    # read the contents
    contents = f.read()

  # split the contents into lines
  lines = contents.split('\n')

  # remove any line that includes the string "END OF TEXT FILE"
  lines = [line for line in lines if "END OF TEXT FILE" not in line]

  # add the part string
  lines[0] = "PART, " + lines[0]

  # filters out empty lines
  lines = [line for line in lines if line.strip()]

  # replace asterisks with an empty string
  lines = [line.replace("*", "") for line in lines]

  # replace asterisks with an empty string
  lines = [line.replace("•", "") for line in lines]

  # replace GB with an empty string
  lines = [re.sub(r'\sGB', '', line) for line in lines]

  # replace "MHz" with an empty string
  lines = [re.sub(r'\sMHz', '', line) for line in lines]

  # replace "mm" with an empty string
  lines = [re.sub(r'\smm', '', line) for line in lines]

  # replace W with an empty string
  lines = [re.sub(r'\sw', '', line) for line in lines]

  # combine the first line and second line if the second line does not start with "VRAM" or "Lighting"
  if len(lines) > 1 and not lines[1].startswith("VRAM") and not lines[1].startswith("Lighting"):
    lines[0] = lines[0] + " " + lines[1]

    lines.pop(1)

  # replace any ":" with ","
  lines = [line.replace(":", ",") for line in lines]

  # Trim the last entry in the list by extracting the digits after the dollar sign using a regular expression
  dollar_amount_regex = r'\$(\d+)'
  last_entry = lines[-1]
  dollar_amount_match = re.search(dollar_amount_regex, last_entry)

  # Extract the digits and construct a new string without the dollar sign
  dollar_amount_digits = dollar_amount_match.group(1)
  dollar_amount = dollar_amount_digits

  # Replace the original string with the dollar amount
  lines[-1] = dollar_amount

  # add "Price, " to the last line
  lines[-1] = "Price, " + lines[-1]

  # remove any extra whitespace from each line
  lines = [line.strip() for line in lines]

  # CHECK OUTPUT
  print(lines)

# WRITING TO FILES

  # extract the first line from the list of lines
  file_name = lines[0].strip()

  # check if the lines contain the word "VRAM"
  if any("VRAM" in line for line in lines):
  # add "gpu-" to the front of the file name
    file_name = "GPU - " + file_name

  # check if the lines contain both "RAM Type" and "Frequency"
  if any("RAM Type" in line for line in lines) and any("Frequency" in line for line in lines):
  # add "ram-" to the front of the file name
    file_name = "RAM - " + file_name

  # create a new file path by joining the directory "D:\\Dev\\PAD\\pcbs-parsed-text" with the first line as the file name and .txt extension
  new_file_path = os.path.join("D:\\Dev\\PAD\\pcbs-parsed-text", file_name + ".txt")

  # save the lines to this file
  with open(new_file_path, 'w') as f:
    for line in lines:
      f.write(line + '\n')

  return file_name

# search for files in the folder "D:\\Dev\\PAD\\pcbs-raw-text" with "output" in the title
raw_text_dir = "D:\\Dev\\PAD\\pcbs-raw-text"
files = [f for f in os.listdir(raw_text_dir) if "output" in f]

successes = []
errors = []

# parse each file
for file in files:
  file_path = os.path.join(raw_text_dir, file)
  try:
    file_name = parse_file(file_path)
    successes.append(file_name)
  except Exception as e:
    errors.append(file_name)
    print(f"Error parsing file {file_name}: {e}")

# check for success and print success or error, listing each file created
if errors:
  print(f"Error parsing files: {errors}")
else:
  print(f"Successfully parsed and saved files: {successes}")

</code>```

I expected the print(lines) call to print the contents of the variable to the console but nothing happens.

To the best of my ability I've checked that print(lines) is not inside a conditional or a returned function.

I thought that Python otherwise executes top down, so I'm not sure about this one.

Still learning so it's probably something silly! Thanks.

Body:
I have a Python script that opens text files and then saves them as newly parsed files.

The code works: print(lines) on line 69 prints the parsed contents and the names of the files are also output if writing is successful.

However, if I remove or comment all of the code below line 70, print(lines) on 69 no longer works.

import os
import re

def parse_file(file_path):

  # open the file
  with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
    # read the contents
    contents = f.read()

  # split the contents into lines
  lines = contents.split('\n')

  # remove any line that includes the string "END OF TEXT FILE"
  lines = [line for line in lines if "END OF TEXT FILE" not in line]

  # add the part string
  lines[0] = "PART, " + lines[0]

  # filters out empty lines
  lines = [line for line in lines if line.strip()]

  # replace asterisks with an empty string
  lines = [line.replace("*", "") for line in lines]

  # replace asterisks with an empty string
  lines = [line.replace("•", "") for line in lines]

  # replace GB with an empty string
  lines = [re.sub(r'\sGB', '', line) for line in lines]

  # replace "MHz" with an empty string
  lines = [re.sub(r'\sMHz', '', line) for line in lines]

  # replace "mm" with an empty string
  lines = [re.sub(r'\smm', '', line) for line in lines]

  # replace W with an empty string
  lines = [re.sub(r'\sw', '', line) for line in lines]

  # combine the first line and second line if the second line does not start with "VRAM" or "Lighting"
  if len(lines) > 1 and not lines[1].startswith("VRAM") and not lines[1].startswith("Lighting"):
    lines[0] = lines[0] + " " + lines[1]

    lines.pop(1)

  # replace any ":" with ","
  lines = [line.replace(":", ",") for line in lines]

  # Trim the last entry in the list by extracting the digits after the dollar sign using a regular expression
  dollar_amount_regex = r'\$(\d+)'
  last_entry = lines[-1]
  dollar_amount_match = re.search(dollar_amount_regex, last_entry)

  # Extract the digits and construct a new string without the dollar sign
  dollar_amount_digits = dollar_amount_match.group(1)
  dollar_amount = dollar_amount_digits

  # Replace the original string with the dollar amount
  lines[-1] = dollar_amount

  # add "Price, " to the last line
  lines[-1] = "Price, " + lines[-1]

  # remove any extra whitespace from each line
  lines = [line.strip() for line in lines]

  # CHECK OUTPUT
  print(lines)

# WRITING TO FILES

  # extract the first line from the list of lines
  file_name = lines[0].strip()

  # check if the lines contain the word "VRAM"
  if any("VRAM" in line for line in lines):
  # add "gpu-" to the front of the file name
    file_name = "GPU - " + file_name

  # check if the lines contain both "RAM Type" and "Frequency"
  if any("RAM Type" in line for line in lines) and any("Frequency" in line for line in lines):
  # add "ram-" to the front of the file name
    file_name = "RAM - " + file_name

  # create a new file path by joining the directory "D:\\Dev\\PAD\\pcbs-parsed-text" with the first line as the file name and .txt extension
  new_file_path = os.path.join("D:\\Dev\\PAD\\pcbs-parsed-text", file_name + ".txt")

  # save the lines to this file
  with open(new_file_path, 'w') as f:
    for line in lines:
      f.write(line + '\n')

  return file_name

# search for files in the folder "D:\\Dev\\PAD\\pcbs-raw-text" with "output" in the title
raw_text_dir = "D:\\Dev\\PAD\\pcbs-raw-text"
files = [f for f in os.listdir(raw_text_dir) if "output" in f]

successes = []
errors = []

# parse each file
for file in files:
  file_path = os.path.join(raw_text_dir, file)
  try:
    file_name = parse_file(file_path)
    successes.append(file_name)
  except Exception as e:
    errors.append(file_name)
    print(f"Error parsing file {file_name}: {e}")

# check for success and print success or error, listing each file created
if errors:
  print(f"Error parsing files: {errors}")
else:
  print(f"Successfully parsed and saved files: {successes}")

I expected the print(lines) call to print the contents of the variable to the console but nothing happens.

To the best of my ability I've checked that print(lines) is not inside a conditional or a returned function.

I thought that Python otherwise executes top down, so I'm not sure about this one.

Still learning so it's probably something silly! Thanks.


问:
How to access terms under custom taxonomy archive
I have a Custom Taxonomy called movie-genres

```<code>'rewrite' => array('slug' => 'movie-genres', 'with_front' => true) );
 register_taxonomy( 'movie-genres', array( 'movies' ), $args );
</code>```

And I have a WP template hierarchy for the Taxonomy and it's associated Terms like below

```<code>archive.php
archive-movie-genres.php

taxonomy.php
taxonomy-movie-genres.php
taxonomy-movie-genres-action.php
</code>```

Now when navigating in the browser I am able to see the CPTs listed for term of action like this

```<code>domain.com/movie-genres/action
</code>```

but when landing at movie-genres to get the all terms listed under this taxonomy like

```<code>domain.com/movie-genres/
</code>```

I am getting the 404 page in return!

As you can see I have the archive-movie-genres.php and taxonomy-movie-genres.php created. Why am I getting ended at 404?

Body:
I have a Custom Taxonomy called movie-genres

'rewrite' => array('slug' => 'movie-genres', 'with_front' => true) );
 register_taxonomy( 'movie-genres', array( 'movies' ), $args );

And I have a WP template hierarchy for the Taxonomy and it's associated Terms like below

archive.php
archive-movie-genres.php

taxonomy.php
taxonomy-movie-genres.php
taxonomy-movie-genres-action.php

Now when navigating in the browser I am able to see the CPTs listed for term of action like this

domain.com/movie-genres/action

but when landing at movie-genres to get the all terms listed under this taxonomy like

domain.com/movie-genres/

I am getting the 404 page in return!

As you can see I have the archive-movie-genres.php and taxonomy-movie-genres.php created. Why am I getting ended at 404?


问:
Issues with GLFW3: undefined reference to `glfwInit'
I am trying to compile a minimal GLFW3 program:

```<code>#include <GLFW/glfw3.h>

int main()
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    return 0;
}
</code>```

However, I am getting the following error:

```<code>PS C:\GitHub\test> g++ -Wall -I GLFW/include -lglfw3 test.cpp -o test.exe
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lglfw3: No such file or directory
collect2.exe: error: ld returned 1 exit status
PS C:\GitHub\test> g++ -Wall -I GLFW/include -L GLFW/lib64 -lglfw3 test.cpp -o test.exe
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0xe): undefined reference to `glfwInit'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x43): undefined reference to `glfwCreateWindow'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x53): undefined reference to `glfwTerminate'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x66): undefined reference to `glfwMakeContextCurrent'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x74): undefined reference to `glfwSwapBuffers'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x79): undefined reference to `glfwPollEvents'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x85): undefined reference to `glfwWindowShouldClose'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x93): undefined reference to `glfwTerminate'
collect2.exe: error: ld returned 1 exit status
</code>```

I am on Windows 10 and have downloaded the 64-bit Windows version of GLFW3. If I try linking with the 32 bit version I get:

```<code>PS C:\GitHub\test> g++ -Wall -I GLFW/include -L GLFW/lib32 -lglfw3 test.cpp -o test.exe
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible GLFW/lib32/libglfw3.a when searching for -lglfw3
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible GLFW/lib32\libglfw3.a when searching for -lglfw3
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible GLFW/lib32/libglfw3.a when searching for -lglfw3
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lglfw3: No such file or directory
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible GLFW/lib32/libglfw3.a when searching for -lglfw3
collect2.exe: error: ld returned 1 exit status
</code>```

This is expected.

Body:
I am trying to compile a minimal GLFW3 program:

#include <GLFW/glfw3.h>

int main()
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    return 0;
}

However, I am getting the following error:

PS C:\GitHub\test> g++ -Wall -I GLFW/include -lglfw3 test.cpp -o test.exe
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lglfw3: No such file or directory
collect2.exe: error: ld returned 1 exit status
PS C:\GitHub\test> g++ -Wall -I GLFW/include -L GLFW/lib64 -lglfw3 test.cpp -o test.exe
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0xe): undefined reference to `glfwInit'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x43): undefined reference to `glfwCreateWindow'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x53): undefined reference to `glfwTerminate'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x66): undefined reference to `glfwMakeContextCurrent'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x74): undefined reference to `glfwSwapBuffers'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x79): undefined reference to `glfwPollEvents'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x85): undefined reference to `glfwWindowShouldClose'
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\emili\AppData\Local\Temp\ccg370QG.o:test.cpp:(.text+0x93): undefined reference to `glfwTerminate'
collect2.exe: error: ld returned 1 exit status

I am on Windows 10 and have downloaded the 64-bit Windows version of GLFW3. If I try linking with the 32 bit version I get:

PS C:\GitHub\test> g++ -Wall -I GLFW/include -L GLFW/lib32 -lglfw3 test.cpp -o test.exe
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible GLFW/lib32/libglfw3.a when searching for -lglfw3
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible GLFW/lib32\libglfw3.a when searching for -lglfw3
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible GLFW/lib32/libglfw3.a when searching for -lglfw3
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lglfw3: No such file or directory
c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible GLFW/lib32/libglfw3.a when searching for -lglfw3
collect2.exe: error: ld returned 1 exit status

This is expected.


问:
AttributeError: 'function' object has no attribute 'login'
I'm trying to import and delete "login" data from one file to a different file but it fails.

file1.py:

```<code>@Client.on_message(filters.command("a"))
async def fileone(cl: Client, msg: Message):

    login = await msg.reply("Hello")
</code>```

to file2:

```<code>from file1 import fileone
# or from file1 import *

@Client.on_callback_query(filters.regex("send"))
async def seend():

    file1.login.delete()
</code>```

error output:

```<code>AttributeError: 'function' object has no attribute 'login'
</code>```

Body:
I'm trying to import and delete "login" data from one file to a different file but it fails.

file1.py:

@Client.on_message(filters.command("a"))
async def fileone(cl: Client, msg: Message):

    login = await msg.reply("Hello")

to file2:

from file1 import fileone
# or from file1 import *

@Client.on_callback_query(filters.regex("send"))
async def seend():

    file1.login.delete()

error output:

AttributeError: 'function' object has no attribute 'login'


问:
Anomaly Detection in Farmland Images
Farmland Image w/ anomaly:

In the picture above, the blue outline outlines the anomalous part of the farmland, where the plants are much more dense also known as "Double Planting".

I'm looking for ideas, approaches, or algorithms I can try, to see if it is able to properly cluster the anomalous parts of the farmland seperately from the rest of the land.

This has been my approach so far howerver it is not able to cluster the image properly and identify the anomalous part of the image.

I divide the image into a set of cells (e.g., 16x16), and cluster the cells using hierarchical clustering with one constraint.

A cluster C1 can be merged with another cluster C2 to make a bigger cluster only if C1 contains a cell c1 and C2 contains a cell c2, and c1 and c2 are neighbours. (capital C indicates cluster while lowercase c indicates cell)

Intially, each cell starts out in its own cluster.

Distance between two clusters C1 and C2 is defined as either the Euclidean or Bhattacharyaa distance between the histogram
over all pixels that are inside C1 and the histogram of all pixels inside C2

Title: Anomaly Detection in Farmland Images


问:
ExtJs - How fixing this error when sencha app build
```<code>#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007ff817e17572, pid=13762, tid=0x0000000000004d03
#
# JRE version: OpenJDK Runtime Environment (8.0_242-b08) (build 1.8.0_242-b08)
# Java VM: OpenJDK 64-Bit Server VM (25.242-b08 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# C  [libsystem_platform.dylib+0x1572]  _platform_strlen+0x12
#
# Core dump written. Default location: /cores/core or core.13762
#
# An error report file with more information is saved as:
# /Library/WebServer/Documents/Learning/info-pd/info-pd-fe/hs_err_pid13762.log
[thread 17923 also had an error]
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
zsh: abort      sudo /Users/xxxxxxxx/bin/Sencha/Cmd/7.3.0.19/sencha app build
</code>```

and i'm try build, i'm getting other error like this

```<code>Sencha Cmd v7.3.0.19
[INF] Using GPL version of Ext JS version 7.0.0.168 from /Library/WebServer/Documents/Learning/info-pd/info-pd-fe/ext.
[INF] The implications of using GPL version can be found here (http://www.sencha.com/products/extjs/licensing).
[INF] Processing Build Descriptor : classic (production environment)
java(14297,0x700002dff000) malloc: Heap corruption detected, free list is damaged at 0x600001cdd390
*** Incorrect guard value: 105553133774736
java(14297,0x700002dff000) malloc: *** set a breakpoint in malloc_error_break to debug
zsh: abort      sudo /Users/xxxxxxxx/bin/Sencha/Cmd/7.3.0.19/sencha app build
</code>```

Whenever I am trying to execute command: sencha app build its failed with this error.
Please help me, how to fixing that?

Info:
I'm use ext-7.0.0 GPL version
and Sencha CMD 7.3.0

Thanks

Body:
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007ff817e17572, pid=13762, tid=0x0000000000004d03
#
# JRE version: OpenJDK Runtime Environment (8.0_242-b08) (build 1.8.0_242-b08)
# Java VM: OpenJDK 64-Bit Server VM (25.242-b08 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# C  [libsystem_platform.dylib+0x1572]  _platform_strlen+0x12
#
# Core dump written. Default location: /cores/core or core.13762
#
# An error report file with more information is saved as:
# /Library/WebServer/Documents/Learning/info-pd/info-pd-fe/hs_err_pid13762.log
[thread 17923 also had an error]
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
zsh: abort      sudo /Users/xxxxxxxx/bin/Sencha/Cmd/7.3.0.19/sencha app build

and i'm try build, i'm getting other error like this

Sencha Cmd v7.3.0.19
[INF] Using GPL version of Ext JS version 7.0.0.168 from /Library/WebServer/Documents/Learning/info-pd/info-pd-fe/ext.
[INF] The implications of using GPL version can be found here (http://www.sencha.com/products/extjs/licensing).
[INF] Processing Build Descriptor : classic (production environment)
java(14297,0x700002dff000) malloc: Heap corruption detected, free list is damaged at 0x600001cdd390
*** Incorrect guard value: 105553133774736
java(14297,0x700002dff000) malloc: *** set a breakpoint in malloc_error_break to debug
zsh: abort      sudo /Users/xxxxxxxx/bin/Sencha/Cmd/7.3.0.19/sencha app build

Whenever I am trying to execute command: sencha app build its failed with this error.
Please help me, how to fixing that?

Info:
I'm use ext-7.0.0 GPL version
and Sencha CMD 7.3.0

Thanks


问:
JPA Specification on union of two tables
I'm trying to create a JPA specification (criteria builder) to retrieve data from two separate tables (union of two tables). Any thought ?

The main purpose is to make it easy to add search filter and pagination when querying from the two tables.


问:
Obtain Keycloak RPT Token by Resource Type
Following this documentation:

https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_obtaining_permissions

You are able to obtain an RPT by a resource name, scope, or both. The ADMIN evaluation API to test your policies, allows you to specify just the resource type. How would I achieve this from a client level?


问:
This YoloV7 SavedModel (converted from PyTorch) is ~13% faster than a CenterNet SavedModel, but after conversion to TFLite it becomes 4x slower?
I have followed these steps to convert the YoloV7 model to tf.SavedModel:

export.py as described in this repo: https://github.com/WongKinYiu/yolov7

onnx-tf convert -i model.onnx -o model.pb

For the CenterNet model, I used Tensorflow's Object Detection API. I then convert both models to TFLite using the CLI command: tflite_convert --saved_model_dir model.pb --output_file .tflite.

I am using the following scripts to measure the inference latency for the models:

SavedModel: https://pastebin.com/YiTPgUQ2

TFLite: https://pastebin.com/zbeDAARc

Both models seem to be getting ~28 FPS as SavedModels (as you can see I am hiding the GPU so the code runs on CPU), and after converting them the CenterNet runs at ~20 FPS while YoloV7 runs at ~5 FPS. Is there any solution to this?


问:
Xamarin.Android Send Whatsapp Message
I use this code to send a Message to WhatsApp:

```<code>string phoneNumberWithCountryCode = "+20>>>>>>>>";
string message = "Test Program \n Test Program \n Test";;
StartActivity(new Intent(Intent.ActionView,
  Android.Net.Uri.Parse(
    "https://api.whatsapp.com/send?phone=" + phoneNumberWithCountryCode + "&text=" + message)));
</code>```

It seems ok, but the message isn't send to a receiver. Instead, it is being sent to the WhatsApp textbox and I need to press Go or Enter to send the Message.
How do I write 'Press go' or 'Enter' in my code to send it directly? I need Send Key like C#.

Title: Xamarin.Android Send Whatsapp Message

Body:
I use this code to send a Message to WhatsApp:

string phoneNumberWithCountryCode = "+20>>>>>>>>";
string message = "Test Program \n Test Program \n Test";;
StartActivity(new Intent(Intent.ActionView,
  Android.Net.Uri.Parse(
    "https://api.whatsapp.com/send?phone=" + phoneNumberWithCountryCode + "&text=" + message)));

It seems ok, but the message isn't send to a receiver. Instead, it is being sent to the WhatsApp textbox and I need to press Go or Enter to send the Message.
How do I write 'Press go' or 'Enter' in my code to send it directly? I need Send Key like C#.


问:
How to bundle next.js app as a javascript widget or npm package?
I have a survey built with Next.js using Incremental Static Regeneration (ISR). I would like to bundle it so I can can either publish it to npm or host a single entry file so I can use the survey on other applications.

It's currently hosted on Vercel and uses getStaticProps and getStaticPaths to call my API of 'surveys' and 'survey questions'. ISR is great because it allows me to dynamically load each step of the survey based off of the API structure and if I modify it then the revalidate property will  regenerate the new order or questions from the survey. It also lets me get away with only having one page for all surveys/question types.

My App structure is like this:

```<code>  - src
    - pages
      - [surveyid]
        - [...question].tsx
</code>```

Based on the request (and response that was received during build time/revalidation) the static files for the survey-id are created and the next router will route to each survey question based off the next step in the json object from the api eg., /surveyid/question-1, /surveyid/question-2 etc..

This is all working well in production when deployed to Vercel.

When it comes to bundling this so a survey can be loaded into other sites I have been quite lost.
When I run next build it builds the prod files that are served to vercel but there are many entry points and not a single .js file.

I tried running next export and serving the .out folder locally and the pages and links are accurate but this breaks the ISR and after reading next.js documentation it states that next export doesn't work with ISR.

Ideally I would like to be able to build the application to a single entry file eg., index.js and then either publish as a package to npm or host on my server. Then load the survey by installing the package or adding the direct url to the src file of a script tag in my other projects eg.,  and provide some settings/options to the request so I can tell it which survey to return.

Is there a way for this to be done while still maintaining ISR?
Would I have to create some sort of entry file to dispatch the request and return the static files from my vercel server instead as a workaround?

I am currently trying to see if I can use rollup to build it out to a single file but I am unsure if this will break the next router when it comes to the dynamic rendering (or revalidation) of pages.

In a perfect world I would like to leverage some of the cool features of next like their middleware to determine the geolocation from the request header as well. But i'm happy if I can just get the survey to render in another project at this point.

Body:
I have a survey built with Next.js using Incremental Static Regeneration (ISR). I would like to bundle it so I can can either publish it to npm or host a single entry file so I can use the survey on other applications.

It's currently hosted on Vercel and uses getStaticProps and getStaticPaths to call my API of 'surveys' and 'survey questions'. ISR is great because it allows me to dynamically load each step of the survey based off of the API structure and if I modify it then the revalidate property will  regenerate the new order or questions from the survey. It also lets me get away with only having one page for all surveys/question types.

My App structure is like this:

  - src
    - pages
      - [surveyid]
        - [...question].tsx

Based on the request (and response that was received during build time/revalidation) the static files for the survey-id are created and the next router will route to each survey question based off the next step in the json object from the api eg., /surveyid/question-1, /surveyid/question-2 etc..

This is all working well in production when deployed to Vercel.

When it comes to bundling this so a survey can be loaded into other sites I have been quite lost.
When I run next build it builds the prod files that are served to vercel but there are many entry points and not a single .js file.

I tried running next export and serving the .out folder locally and the pages and links are accurate but this breaks the ISR and after reading next.js documentation it states that next export doesn't work with ISR.

Ideally I would like to be able to build the application to a single entry file eg., index.js and then either publish as a package to npm or host on my server. Then load the survey by installing the package or adding the direct url to the src file of a script tag in my other projects eg.,  and provide some settings/options to the request so I can tell it which survey to return.

Is there a way for this to be done while still maintaining ISR?
Would I have to create some sort of entry file to dispatch the request and return the static files from my vercel server instead as a workaround?

I am currently trying to see if I can use rollup to build it out to a single file but I am unsure if this will break the next router when it comes to the dynamic rendering (or revalidation) of pages.

In a perfect world I would like to leverage some of the cool features of next like their middleware to determine the geolocation from the request header as well. But i'm happy if I can just get the survey to render in another project at this point.


问:
How to move from filtered results page after opening the particular records
Initially we have 50 records in main page and,
we filter/search the particular records from main page and so we get some records like 5 records after search on main page, and then we open one records among the 5 records ( filtered results) into new page.

From particular new page, suppose we want to go back to the previous page like filtered page (where we have 5 records) instead of main page.

So how can we do this?

Please help on this.

I don't know how to do that.


问:
Backup of Firestore like in Firebase Realtime Database?
I'm looking for a way to backup in Firebase Firestore.  I found https://firebase.google.com/docs/database/backups but this is for the Firebase Realtime Database.

I can't seem to find documentation on an equivalent way to backup for Firestore.

There are manual ways to backup such as described in https://medium.com/@BrodaNoel/how-to-backup-firebase-firestore-8be94a66138c.

But I'm looking for a GCP equivalent before making my own process.


问:
Exception reading Manifest with OneDrive
I am trying to publish a generic WinForm application using OneDrive from Visual Studio 2022 (just a form with a button). I set Publish Location to a folder on Onedrive, and then I share the OneDrive directory to extract the URL, and use that for the Install Location. Visual Studio writes the files out fine, and even creates an .html file for installation, but when I click Install, it gives me an error saying the Manifest is bad. Here is the output

PLATFORM VERSION INFO
Windows             : 10.0.22621.0 (Win32NT)
Common Language Runtime     : 4.0.30319.42000
System.Deployment.dll       : 4.8.9032.0 built by: NET481REL1
clr.dll             : 4.8.9075.0 built by: NET481REL1LAST_C
dfdll.dll           : 4.8.9032.0 built by: NET481REL1
dfshim.dll          : 10.0.22621.30000 (WinBuild.160101.0800)

SOURCES
Deployment url          : https://1drv.ms/u/s!AnxJ9sdoqHuhhbUD2vlxEO-N65DIEw?e=TeFxXK/Form1.application

ERROR SUMMARY
Below is a summary of the errors, details of these errors are listed later in the log.
* Activation of https://1drv.ms/u/s!AnxJ9sdoqHuhhbUD2vlxEO-N65DIEw?e=TeFxXK/Form1.application resulted in exception. Following failure messages were detected:
+ Exception reading manifest from https://onedrive.live.com/redir?resid=A17BA868C7F6497C!88707&authkey=!ANr5cRDvjeuQyBM&e=TeFxXK%2fForm1.application: the manifest may not be valid or the file could not be opened.
+ Parsing and DOM creation of the manifest resulted in error. Following parsing errors were noticed:
-HRESULT:   0x8007001f
Start line:    0
Start column:  0
Host file:

+ A device attached to the system is not functioning. (Exception from HRESULT: 0x8007001F)

COMPONENT STORE TRANSACTION FAILURE SUMMARY
No transaction error was detected.

WARNINGS
There were no warnings during this operation.

OPERATION PROGRESS STATUS
* [12/31/2022 3:52:55 PM] : Activation of https://1drv.ms/u/s!AnxJ9sdoqHuhhbUD2vlxEO-N65DIEw?e=TeFxXK/Form1.application has started.

ERROR DETAILS
Following errors were detected during this operation.
* [12/31/2022 3:52:55 PM] System.Deployment.Application.InvalidDeploymentException (ManifestParse)
- Exception reading manifest from https://onedrive.live.com/redir?resid=A17BA868C7F6497C!88707&authkey=!ANr5cRDvjeuQyBM&e=TeFxXK%2fForm1.application: the manifest may not be valid or the file could not be opened.
- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.ManifestReader.FromDocument(String localPath, ManifestType manifestType, Uri sourceUri)
at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestDirectBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation)
at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl, Uri& deploymentUri)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivationWithRetry(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivationWithRetry(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
--- Inner Exception ---
System.Deployment.Application.InvalidDeploymentException (ManifestParse)
- Parsing and DOM creation of the manifest resulted in error. Following parsing errors were noticed:
-HRESULT:   0x8007001f
Start line:    0
Start column:  0
Host file:

- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.Manifest.AssemblyManifest.LoadCMSFromStream(Stream stream)
at System.Deployment.Application.Manifest.AssemblyManifest..ctor(FileStream fileStream)
at System.Deployment.Application.ManifestReader.FromDocument(String localPath, ManifestType manifestType, Uri sourceUri)
--- Inner Exception ---
System.Runtime.InteropServices.COMException
- A device attached to the system is not functioning. (Exception from HRESULT: 0x8007001F)
- Source: System.Deployment
- Stack trace:
at System.Deployment.Internal.Isolation.IsolationInterop.CreateCMSFromXml(Byte[] buffer, UInt32 bufferSize, IManifestParseErrorCallback Callback, Guid& riid)
at System.Deployment.Application.Manifest.AssemblyManifest.LoadCMSFromStream(Stream stream)

COMPONENT STORE TRANSACTION DETAILS
No transaction information is available.

So my question is: Should I be providing a URL to my OneDrive folder in a different way, other than Sharing it (to get a URL link)? I cannot seem to find any permission issues with the files in that folder using the URL link, but it complains.
So far I have tried different .NET versions, different manifest files, I reset Visual Studio, I uninstalled it and reinstalled it, then uninstalled it and installed a previous version (2019). Everything fails with this same error.

I am using Visual Studio 2022 on Windows 11 computer, if that matters.

Thoughts on what the issue may be? Should I avoid OneDrive for this? Maybe there is a better option?

Thank you.


问:
Can't view keys of hdf5 file after opening it with 'w' with h5py in python
I am attempting to display (and, later, rewrite) some data in an hdf5 file but I cannot see the key names or data after I open the file with the write 'w' argument.

This code works, successfully showing many keys:

```<code>import h5py
with h5py.File('myfile', 'r') as f:
    print(list(f.keys()))
</code>```

but code this doesn't, showing an empty list:

```<code>import h5py
with h5py.File('myfile', 'w') as f:
    print(list(f.keys()))
</code>```

and, weirdest of all, after running the second block (with 'w') the first block (with 'r') now shows an empty list as well!

The file itself appears unchanged; it's the exact same size and when I compare it to my backup copy with "diff", there is no difference (note: running the first block on my backup copy still works). I have no idea what the issue is and oddly couldn't find it discussed anywhere. I'm using python 3.7.

Body:
I am attempting to display (and, later, rewrite) some data in an hdf5 file but I cannot see the key names or data after I open the file with the write 'w' argument.

This code works, successfully showing many keys:

import h5py
with h5py.File('myfile', 'r') as f:
    print(list(f.keys()))

but code this doesn't, showing an empty list:

import h5py
with h5py.File('myfile', 'w') as f:
    print(list(f.keys()))

and, weirdest of all, after running the second block (with 'w') the first block (with 'r') now shows an empty list as well!

The file itself appears unchanged; it's the exact same size and when I compare it to my backup copy with "diff", there is no difference (note: running the first block on my backup copy still works). I have no idea what the issue is and oddly couldn't find it discussed anywhere. I'm using python 3.7.


问:
Helix config.toml keymap that should perform two actions but takes two tries to get them both done
I set this keymap on ./helix/config.toml :

```<code>[keys.normal]
backspace = {r = [":w", ":sh cargo run"]}
</code>```

And when I first call the macro after doing a change in a rust file, it just executes the cargo run command, and only writes the new changes to the disk before running on the second time I do it.

I tried to set the keymap to save twice before the cargo run, but again it just made its work on the second attempt.

Body:
I set this keymap on ./helix/config.toml :

[keys.normal]
backspace = {r = [":w", ":sh cargo run"]}

And when I first call the macro after doing a change in a rust file, it just executes the cargo run command, and only writes the new changes to the disk before running on the second time I do it.

I tried to set the keymap to save twice before the cargo run, but again it just made its work on the second attempt.


问:
Is there a way to access javascript variables within jinja2 template braces?
I have a flask route

```<code>@app.route('/another/<int:value>')
def another():
    return 'another'
</code>```

Using javascript, I'm trying to access the url for this route using url_for within jinja2 template braces

```<code><script>
    const v = 1;
    const sample = "{{url_for('another', value=v)}}";
</script>
</code>```

doing this raises an error jinja2.exceptions.UndefinedError: 'v' is undefined.
I suspect v is outside the scope of the jinja templates.
Is there a way around this?

Body:
I have a flask route

@app.route('/another/<int:value>')
def another():
    return 'another'

Using javascript, I'm trying to access the url for this route using url_for within jinja2 template braces

doing this raises an error jinja2.exceptions.UndefinedError: 'v' is undefined.
I suspect v is outside the scope of the jinja templates.
Is there a way around this?


问:
Error while bot.load_extension has await infront of it
Looked at multiple videos on cogs, They all seem to use await bot.load_extension or await client.load_extension However the error is telling me i cannot have await before bot.load_extension</p>
```<code>    for filename in os.listdir('./cogs/'):
        if filename.endswith('.py'):
           await bot.load_extension(f"cogs.{filename[:-3]}")

  File "d:\Discord Bot Testing\main.py", line 17, in main
    await load()
  File "d:\Discord Bot Testing\main.py", line 13, in load
    await bot.load_extension(f"cogs.{filename[:-3]}")
TypeError: object list can't be used in 'await' expression```

</code>```

Body:
Looked at multiple videos on cogs, They all seem to use await bot.load_extension or await client.load_extension However the error is telling me i cannot have await before bot.load_extension

    for filename in os.listdir('./cogs/'):
        if filename.endswith('.py'):
           await bot.load_extension(f"cogs.{filename[:-3]}")

  File "d:\Discord Bot Testing\main.py", line 17, in main
    await load()
  File "d:\Discord Bot Testing\main.py", line 13, in load
    await bot.load_extension(f"cogs.{filename[:-3]}")
TypeError: object list can't be used in 'await' expression```


问:
gcc inline assembly: What is the difference between output and output-only?
The following assembly works (in -O2) if all of my outputs are "output-only" (=&), but not if they are "output" (=). What is the difference between these two modes, and how can the behavior of the program change when the assembly is not reading the register?

```<code>  __asm (
     "ldrb %[H], %[P0] \n"                 // P[0]
     "ldrb %[L], %[P4] \n"                 // P[4]
     "add %[H], %[Htbl], %[H], lsl #4 \n"  // H = Htbl + P[0]
     "add %[L], %[Htbl], %[L], lsl #4 \n"  // L = Htbl + P[4]
     "mov %[S], %[Z0], LSL #24 \n"         // S = Z0 << 24
     :
     [H]   "=&r" (H),
     [L]   "=&r" (L),
     [S]   "=&r" (S),
     [tmp] "=&r" (tmp)
     :
     [Z0]   "r" (Z0),
     [Htbl] "r" (Htbl),
     [P0]   "m" (P[0]),
     [P4]   "m" (P[4])
     );
</code>```

Body:
The following assembly works (in -O2) if all of my outputs are "output-only" (=&), but not if they are "output" (=). What is the difference between these two modes, and how can the behavior of the program change when the assembly is not reading the register?

  __asm (
     "ldrb %[H], %[P0] \n"                 // P[0]
     "ldrb %[L], %[P4] \n"                 // P[4]
     "add %[H], %[Htbl], %[H], lsl #4 \n"  // H = Htbl + P[0]
     "add %[L], %[Htbl], %[L], lsl #4 \n"  // L = Htbl + P[4]
     "mov %[S], %[Z0], LSL #24 \n"         // S = Z0 << 24
     :
     [H]   "=&r" (H),
     [L]   "=&r" (L),
     [S]   "=&r" (S),
     [tmp] "=&r" (tmp)
     :
     [Z0]   "r" (Z0),
     [Htbl] "r" (Htbl),
     [P0]   "m" (P[0]),
     [P4]   "m" (P[4])
     );


问:
Flutter - Textfield/keyboard issue whenever clicking on special characters button
Whenever I type into a text field and click on the special characters button & then try to edit past text by clicking in between some of the letters, it'll automatically highlight all of the text instead of showing the original single cursor sitting between 2 letters. This can be a bit annoying and confusing for the user experience. Is there any quick fix for this?

Note: I'm using a real device (Samsung Galaxy S8)

Here are 2 images to better explain this problem:

Trying to edit text before clicking on special characters button:

Trying to edit text after clicking on special characters button:


问:
Is there a way to access files other than through excel or google sheets when using data for the jupyter notebook?
I tried using google sheets but I only have a max of 12 projects remaining for my quota in the google cloud console. Is there a better way to import the data from files when on a macbook?

I cannot use excel and google cloud is limiting so I need to find another way to import the data into the jupyter notebook.

Also, what exactly are csv files and how do you use them? Are there any advantages to csv files?


问:
Can you in A-Frame, set opacity and color differently for individual faces of an object?
It would be helpful if I could do it when registering a new custom mesh.
Can you set color and opacity to each individual face, as the face is being pushed to a custom geometry ?

If not? Can you cycle through afterwards in a for-next loop to do it ?

I couldn't even get:

geometry.faces.push(new THREE.Face3(0, 1, 2, 0, "#333"));

to assign a color, much less an opacity.

I know the order is:
(Red, Green, Blue, Normal, Color)
Is there an available entry for opacity as well? Or would I have to assign a complete material as well ?
I'm open do doing it that way if needed.


问:
How to play an animation behind a login box?
I want to run my animation effect in the background, but it's running it over my login box. My question is what needs to be changed in my login box parent element for the animation to be played behind it?

```<code>section {
  position: absolute;
  display: flex;
  width: 100vw;
  height: 100vh;
  justify-content: center;
  align-items: center;
  gap: 2px;
  flex-wrap: wrap;
}

section::before {
  content: '';
  position: relative;
  width: 100%;
  height: 100%;
  background: linear-gradient(rgb(0, 0, 0), rgba(5, 189, 230, 0.922), #000);
  animation: animate 5s linear infinite;
}

section span {
  position: relative;
  display: block;
  width: calc(15.25vw - 6px);
  height: calc(15.25vw - 2px);
  background: #181818;
  z-index: 2;
  transition: 1.5s;
}

}
section .login-box {
  position: absolute;
  top: 40%;
  left: 50%;
  width: 400px;
  padding: 40px;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, .5);
  box-sizing: border-box;
  box-shadow: 0 15px 25px rgba(0, 0, 0, .6);
  border-radius: 10px;
  z-index: 1000;
}
</code>```

I want to know what type of correction needs to be made in this CSS section to fix the animation.

Body:
I want to run my animation effect in the background, but it's running it over my login box. My question is what needs to be changed in my login box parent element for the animation to be played behind it?

section {
  position: absolute;
  display: flex;
  width: 100vw;
  height: 100vh;
  justify-content: center;
  align-items: center;
  gap: 2px;
  flex-wrap: wrap;
}

section::before {
  content: '';
  position: relative;
  width: 100%;
  height: 100%;
  background: linear-gradient(rgb(0, 0, 0), rgba(5, 189, 230, 0.922), #000);
  animation: animate 5s linear infinite;
}

section span {
  position: relative;
  display: block;
  width: calc(15.25vw - 6px);
  height: calc(15.25vw - 2px);
  background: #181818;
  z-index: 2;
  transition: 1.5s;
}

}
section .login-box {
  position: absolute;
  top: 40%;
  left: 50%;
  width: 400px;
  padding: 40px;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, .5);
  box-sizing: border-box;
  box-shadow: 0 15px 25px rgba(0, 0, 0, .6);
  border-radius: 10px;
  z-index: 1000;
}

I want to know what type of correction needs to be made in this CSS section to fix the animation.


问:
MongoDB aggregation limiting transaction data
I was trying to find all the transaction in my database per month. I accidently ran a mongo db aggregate function on the transaction data (essentially filtering all the transactions that happened in December 2022). But I didn't realize that it would also filter all the incoming transactions from the next items. Basically after I ran the aggregation, the only transaction data I was getting from plaid were the transactions that occurred in December 2022. The data is getting pre-filtered from plaid, not my database. Even after deleting the aggregating fucntion from my code the data is still pre filtered. I tried creating a new plaid account(new client Id and sandbox secret), set up a new database, even re wrote all the code in a new project directory but still I'm only getting transactions that happened in December 2022. I think this might be an issue in the sandbox data on Plaid's side, which is weird because the aggregation function I wrote should only impact my database and not the data coming from plaid. Is there anyway to completely refresh the sandbox data and get all the transaction data? I also noticed the transactions that were getting pre-filtered are the ones from Plaid Checkings and Credit Card (sandbox data) as these were the accounts I tested the aggregation on before I deleted it.

This is the aggregation function I wrote:

```<code>collection.aggregate([
        #find the document with given user id
        "$match":{
            "_id": ObjectId(id)
        },
        {
            #find all transactions in the transactions array that happened in December 2022
            "$project":{
                "transactions":{
                    "$filter": {
                        "input": "$transactions",
                        "cond":{
                            "$and":[
                                "$eq": [
                                    "$$transactions.month",12
                                ]
                                "$eq":{
                                    "$$transactions.year",2022
                                }
                            ]
                        }
                    }
                }
            }
        }
    ])
</code>```

I've tried almost everything to get the full transaction data for the past few days, use a completely different plaid credentials and database but I still only get the data that happened in 12/2022. What can I do to get all the transaction data?

Note: I was able to get all the transaction data before I used the aggregation function so Im confident that was the problem but don't know how it affected Plaids transaction sync

Body:
I was trying to find all the transaction in my database per month. I accidently ran a mongo db aggregate function on the transaction data (essentially filtering all the transactions that happened in December 2022). But I didn't realize that it would also filter all the incoming transactions from the next items. Basically after I ran the aggregation, the only transaction data I was getting from plaid were the transactions that occurred in December 2022. The data is getting pre-filtered from plaid, not my database. Even after deleting the aggregating fucntion from my code the data is still pre filtered. I tried creating a new plaid account(new client Id and sandbox secret), set up a new database, even re wrote all the code in a new project directory but still I'm only getting transactions that happened in December 2022. I think this might be an issue in the sandbox data on Plaid's side, which is weird because the aggregation function I wrote should only impact my database and not the data coming from plaid. Is there anyway to completely refresh the sandbox data and get all the transaction data? I also noticed the transactions that were getting pre-filtered are the ones from Plaid Checkings and Credit Card (sandbox data) as these were the accounts I tested the aggregation on before I deleted it.

This is the aggregation function I wrote:

collection.aggregate([
        #find the document with given user id
        "$match":{
            "_id": ObjectId(id)
        },
        {
            #find all transactions in the transactions array that happened in December 2022
            "$project":{
                "transactions":{
                    "$filter": {
                        "input": "$transactions",
                        "cond":{
                            "$and":[
                                "$eq": [
                                    "$$transactions.month",12
                                ]
                                "$eq":{
                                    "$$transactions.year",2022
                                }
                            ]
                        }
                    }
                }
            }
        }
    ])

I've tried almost everything to get the full transaction data for the past few days, use a completely different plaid credentials and database but I still only get the data that happened in 12/2022. What can I do to get all the transaction data?

Note: I was able to get all the transaction data before I used the aggregation function so Im confident that was the problem but don't know how it affected Plaids transaction sync


问:
Locking a pygame screen
If you have ever use the windows calculator for widows 10 or over you will know that the calculator has a button that allows you to lot the app on your screen which mean even if you switch windows you will still be able to see the calculator app. I was wondering if that possible to do in pygame.</p>

Title: Locking a pygame screen


问:
"Undefined symbols for architecture arm64" Error For Node-Api Function Inside "napi-inl.h"
Using Mac M1 Chip, Clang++, and CMake.

I tried to make a node-api addon function using the napi.h given from npm i node-addon-api in my frontend. I'm pretty new to using C++.

main.cpp:

#include <iostream>
#include <string>

#include <napi.h>

napi_value retrieveData(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value args[1];

    std::string date;
    napi_value output;

    napi_get_cb_info(env, info, &argc, args, NULL, NULL);

    napi_get_value_string_utf8(env, args[0], (char *) &date, (size_t) 5, NULL);

    napi_create_string_utf8(env, (const char*) &date, (size_t) 5, &output);

    return output;
}

napi_value init(napi_env env, napi_value exports) {
    napi_value retrieve;

    napi_create_function(env, nullptr, 0, retrieveData, nullptr, &retrieve);

    return retrieve;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, init);
```
<p>CMakeLists.txt:</p>
<pre class="lang-cpp prettyprint-override"><code>cmake_minimum_required(VERSION 3.13)

set(CMAKE_OSX_ARCHITECTURES "arm64" CACHE STRING "" FORCE)

set (CMAKE_CXX_COMPILER "/usr/bin/clang++" CACHE STRING "C++ compiler" FORCE)
set(CMAKE_CXX_STANDARD 20)

project(BCKND)

add_compile_options(-std=c++20 -fcolor-diagnostics -Wall -L/opt/homebrew/Cellar/libpq/15.1/lib -L/opt/homebrew/Cellar/libpqxx/7.7.4/lib -lpqxx -lpq)

add_executable(${PROJECT_NAME} main.cpp)

target_link_directories(BCKND PRIVATE /opt/homebrew/Cellar/libpq/15.1/lib)
target_link_directories(BCKND PRIVATE /opt/homebrew/Cellar/libpqxx/7.7.4/lib)

target_include_directories(BCKND PRIVATE /opt/homebrew/Cellar/libpq/15.1/include)
target_include_directories(BCKND PRIVATE /opt/homebrew/Cellar/libpqxx/7.7.4/include)
target_include_directories(BCKND PRIVATE /Users/name/project/Frontend/node_modules/node-addon-api)
target_include_directories(BCKND PRIVATE /usr/local/include/node)

target_link_libraries(BCKND pq)
target_link_libraries(BCKND pqxx)
</code>```

However, I get this error:

```<code>Undefined symbols for architecture arm64:
  "_napi_create_function", referenced from:
      init(napi_env__*, napi_value__*) in main.cpp.o
  "_napi_create_string_utf8", referenced from:
      retrieveData(napi_env__*, napi_callback_info__*) in main.cpp.o
  "_napi_get_cb_info", referenced from:
      retrieveData(napi_env__*, napi_callback_info__*) in main.cpp.o
  "_napi_get_value_string_utf8", referenced from:
      retrieveData(napi_env__*, napi_callback_info__*) in main.cpp.o
  "_napi_module_register", referenced from:
      _register_main() in main.cpp.o
ld: symbol(s) not found for architecture arm64
</code>```

Which I discovered are all in the napi-inl.h header file for node-addon-api
Nothing from napi.h is creating this error like napi_value and napi_env
I'm also using postgresql's libpqxx and libpq which require arm64 to compile.

Tried looking for errors in my CMake, since it is my first time using CMake but I could not find anything and I am unsure how this error is caused and how to fix it. I used different architectures like arm64 and x86_64 but none of them worked. I think I could have included the node-addon-api folder headers wrong or used deprecated functions?

Body:
Using Mac M1 Chip, Clang++, and CMake.

I tried to make a node-api addon function using the napi.h given from npm i node-addon-api in my frontend. I'm pretty new to using C++.

main.cpp:

#include <iostream>
#include <string>

#include <napi.h>

napi_value retrieveData(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value args[1];

    std::string date;
    napi_value output;

    napi_get_cb_info(env, info, &argc, args, NULL, NULL);

    napi_get_value_string_utf8(env, args[0], (char *) &date, (size_t) 5, NULL);

    napi_create_string_utf8(env, (const char*) &date, (size_t) 5, &output);

    return output;
}

napi_value init(napi_env env, napi_value exports) {
    napi_value retrieve;

    napi_create_function(env, nullptr, 0, retrieveData, nullptr, &retrieve);

    return retrieve;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, init);

CMakeLists.txt:

cmake_minimum_required(VERSION 3.13)

set(CMAKE_OSX_ARCHITECTURES "arm64" CACHE STRING "" FORCE)

set (CMAKE_CXX_COMPILER "/usr/bin/clang++" CACHE STRING "C++ compiler" FORCE)
set(CMAKE_CXX_STANDARD 20)

project(BCKND)

add_compile_options(-std=c++20 -fcolor-diagnostics -Wall -L/opt/homebrew/Cellar/libpq/15.1/lib -L/opt/homebrew/Cellar/libpqxx/7.7.4/lib -lpqxx -lpq)

add_executable(${PROJECT_NAME} main.cpp)

target_link_directories(BCKND PRIVATE /opt/homebrew/Cellar/libpq/15.1/lib)
target_link_directories(BCKND PRIVATE /opt/homebrew/Cellar/libpqxx/7.7.4/lib)

target_include_directories(BCKND PRIVATE /opt/homebrew/Cellar/libpq/15.1/include)
target_include_directories(BCKND PRIVATE /opt/homebrew/Cellar/libpqxx/7.7.4/include)
target_include_directories(BCKND PRIVATE /Users/name/project/Frontend/node_modules/node-addon-api)
target_include_directories(BCKND PRIVATE /usr/local/include/node)

target_link_libraries(BCKND pq)
target_link_libraries(BCKND pqxx)

However, I get this error:

Undefined symbols for architecture arm64:
  "_napi_create_function", referenced from:
      init(napi_env__*, napi_value__*) in main.cpp.o
  "_napi_create_string_utf8", referenced from:
      retrieveData(napi_env__*, napi_callback_info__*) in main.cpp.o
  "_napi_get_cb_info", referenced from:
      retrieveData(napi_env__*, napi_callback_info__*) in main.cpp.o
  "_napi_get_value_string_utf8", referenced from:
      retrieveData(napi_env__*, napi_callback_info__*) in main.cpp.o
  "_napi_module_register", referenced from:
      _register_main() in main.cpp.o
ld: symbol(s) not found for architecture arm64

Which I discovered are all in the napi-inl.h header file for node-addon-api
Nothing from napi.h is creating this error like napi_value and napi_env
I'm also using postgresql's libpqxx and libpq which require arm64 to compile.

Tried looking for errors in my CMake, since it is my first time using CMake but I could not find anything and I am unsure how this error is caused and how to fix it. I used different architectures like arm64 and x86_64 but none of them worked. I think I could have included the node-addon-api folder headers wrong or used deprecated functions?


问:
CSS grid and flexbox
Do I need to explicitly set width and height to the container if I am using grid or flexbox?

I was trying to give the height of my container div but got confused if I should skip that since grid can handle it for me in the grid-template-columns and grid-template-rows properties.

Title: CSS grid and flexbox


问:
Azure AD SSO component useEffect() running multiple times causing issues
I'm trying to implement Azure AD SSO into my application, but am running into an issue where my app tries to use the code it pulls our the the URL more than once (not sure why it is running multiple times), but this causes Azure AD to send an error.

The error is: AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.

I think I understand that the error is because my app is trying to use the code more than once - but it SHOULD NOT BE.

I'm trying to figure out why it is and then stop it. I'm going to try and add all the relevant code snippets, but if you feel like something is missing, let me know and I can try and help.

I tried many things - mostly in regard to the AzureRedirect.jsx useEffect() since this is where the logic that is running more than once when it should run once is.

I added console logs to make sure that I was right about the useEffect() running more than once and also I added a console log into just the component, outside of the useEffect() to see that the component was rendering several times

I tried moving the logic that creates the 'code' object and populates it from the URL outside of the useEffect()

I tried moving the if(user) {navigate('/')} logic outside of the useEffect into the if/else statement below the useEffect()

I checked that the window.location.search value is not changing unexpectedly by using console.log

I tried messing around with the dependencies for the useEffect() - removing and adding various combinations of dependencies. Nothing worked, though some did 'sometimes' produce slightly different results, but then if I ran the test again, I'd be back to the same original error (weird!)

I also tried adding a return statement into the useEffect() to make sure it only ran once, but this didn't stop it from running multiple times... and at this point, I'm not sure the useEffect() doesn't need to be accessed more than once.

Now onto the code, hopefully this clears up any confusion from reading my previous problem/what I tried.

The component with the useEffect() that gets the URL code and is trying to reuse it:

```<code>import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { azureRedirect } from '../features/auth/authSlice';
import { Link, useNavigate } from 'react-router-dom';
import Spinner from './Spinner';

const AzureRedirect = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { user } = useSelector((state) => state.auth);

  useEffect(() => {
    console.log('Im in AzureRedirect.jsx useEffect()');

    const code = {
      code: new URLSearchParams(window.location.search).get('code'),
    };

    if (user) {
      navigate('/');
    } else if (code) {
      dispatch(azureRedirect(code));
    } else {
      console.log('No code found in URL');
    }
  }, [dispatch, navigate, user]);

  let displayedOutput;

  if (!user) {
    displayedOutput = (
      <div>
        An error has been encountered, please contact your administrator.
        <br />
        <Link to='/login'>Return to Login</Link>
      </div>
    );
  } else {
    return <Spinner />;
  }

  return <div className='pt-4'>{displayedOutput}</div>;
};

export default AzureRedirect;
</code>```

Now I'm going to post the following code - the AzureRedirect action from my slice(redux), service(redux), and controller(backend)

authSlice.js

```<code>export const azureRedirect = createAsyncThunk(
  'users/azureRedirect',
  async (code, thunkAPI) => {
    try {
      console.log('Im in users/azureRedirect');
      return await authService.azureRedirect(code);
    } catch (error) {
      return thunkAPI.rejectWithValue(extractErrorMessage(error));
    }
  }
);
</code>```

authService.js

```<code>const azureRedirect = async (code) => {
  console.log('Im in azureRedirect in the authService.js file');

  try {
    const response = await axios.post(API_URL + 'az-redirect', code);
    // Save to localStorage
    const { token, user } = response.data;
    user.token = token;
    localStorage.setItem('user', JSON.stringify(response.data.user));
    return user;
  } catch (error) {
    console.log('error from azureRedirect (authService.js): ', error);
  }
};
</code>```

userController.js

```<code>// @desc    Login Azure AD User / Returning JWT Token
// @route   POST api/users/az-redirect
// @access  Public
const azRedirect = asyncHandler(async (req, res) => {
  const errors = {};

  const tokenRequest = {
    code: req.body.code,
    scopes: ['user.read'],
    redirectUri: process.env.REDIRECT_URI,
  };

  try {
    const response = await cca.acquireTokenByCode(tokenRequest);
    console.log(
      'response from the original cca.acquireTokenByCode request',
      response
    );
    const user = await User.findOne({ email: response.account.username });

    if (!user) {
      let nameArray = response.account.name.split(' ');
      const newUser = new User({
        firstName: nameArray[0],
        lastName: nameArray[nameArray.length - 1],
        email: response.account.username,
        azureID: response.uniqueId,
      });

      user = await User.create(newUser);
      console.log('\nNew user created: \n', user);

      const payload = {
        id: user.id,
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        isTechnician: user.isTechnician,
        isAdmin: user.isAdmin,
      };

      jwt.sign(
        payload,
        process.env.JWT_SECRET,
        { expiresIn: '30d' },
        (err, token) => {
          res.json({
            success: true,
            token: token,
            user: user,
          });
        }
      );
    } else if (!user.isActive) {
      errors.azure = 'User is no longer permitted to access this application';
      return res.status(401).json(errors);
    } else {
      if (!user.azureID) {
        user.azureID = response.uniqueId;
        user.save().catch((err) => console.log(err));
      }
      const payload = {
        id: user.id,
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        isAdmin: user.isAdmin,
        isSupervisor: user.isSupervisor,
      };

      jwt.sign(
        payload,
        process.env.JWT_SECRET,
        { expiresIn: '30d' },
        (err, token) => {
          res.json({
            success: true,
            token: token,
            user: user,
          });
        }
      );
    }
  } catch (error) {
    console.log(error);
    res.status(500).send(error);
  }
});
</code>```

Any ideas/help would be greatly appreciated!

EDIT:

Turning off strict mode has helped solve the issue, but that isn't a good long-term solution. I'm looking for a solution that either ensures that the dispatch(azureRedirect(code)); will only run once, or if there is a better practice here I don't know of. Thanks!

Body:
I'm trying to implement Azure AD SSO into my application, but am running into an issue where my app tries to use the code it pulls our the the URL more than once (not sure why it is running multiple times), but this causes Azure AD to send an error.

The error is: AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.

I think I understand that the error is because my app is trying to use the code more than once - but it SHOULD NOT BE.

I'm trying to figure out why it is and then stop it. I'm going to try and add all the relevant code snippets, but if you feel like something is missing, let me know and I can try and help.

I tried many things - mostly in regard to the AzureRedirect.jsx useEffect() since this is where the logic that is running more than once when it should run once is.

I added console logs to make sure that I was right about the useEffect() running more than once and also I added a console log into just the component, outside of the useEffect() to see that the component was rendering several times

I tried moving the logic that creates the 'code' object and populates it from the URL outside of the useEffect()

I tried moving the if(user) {navigate('/')} logic outside of the useEffect into the if/else statement below the useEffect()

I checked that the window.location.search value is not changing unexpectedly by using console.log

I tried messing around with the dependencies for the useEffect() - removing and adding various combinations of dependencies. Nothing worked, though some did 'sometimes' produce slightly different results, but then if I ran the test again, I'd be back to the same original error (weird!)

I also tried adding a return statement into the useEffect() to make sure it only ran once, but this didn't stop it from running multiple times... and at this point, I'm not sure the useEffect() doesn't need to be accessed more than once.

Now onto the code, hopefully this clears up any confusion from reading my previous problem/what I tried.

The component with the useEffect() that gets the URL code and is trying to reuse it:

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { azureRedirect } from '../features/auth/authSlice';
import { Link, useNavigate } from 'react-router-dom';
import Spinner from './Spinner';

const AzureRedirect = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { user } = useSelector((state) => state.auth);

  useEffect(() => {
    console.log('Im in AzureRedirect.jsx useEffect()');

    const code = {
      code: new URLSearchParams(window.location.search).get('code'),
    };

    if (user) {
      navigate('/');
    } else if (code) {
      dispatch(azureRedirect(code));
    } else {
      console.log('No code found in URL');
    }
  }, [dispatch, navigate, user]);

  let displayedOutput;

  if (!user) {
    displayedOutput = (

        An error has been encountered, please contact your administrator.

        <Link to='/login'>Return to Login</Link>

    );
  } else {
    return <Spinner />;
  }

  return
{displayedOutput}
;
};

export default AzureRedirect;

Now I'm going to post the following code - the AzureRedirect action from my slice(redux), service(redux), and controller(backend)

authSlice.js

export const azureRedirect = createAsyncThunk(
  'users/azureRedirect',
  async (code, thunkAPI) => {
    try {
      console.log('Im in users/azureRedirect');
      return await authService.azureRedirect(code);
    } catch (error) {
      return thunkAPI.rejectWithValue(extractErrorMessage(error));
    }
  }
);

authService.js

const azureRedirect = async (code) => {
  console.log('Im in azureRedirect in the authService.js file');

  try {
    const response = await axios.post(API_URL + 'az-redirect', code);
    // Save to localStorage
    const { token, user } = response.data;
    user.token = token;
    localStorage.setItem('user', JSON.stringify(response.data.user));
    return user;
  } catch (error) {
    console.log('error from azureRedirect (authService.js): ', error);
  }
};

userController.js

// @desc    Login Azure AD User / Returning JWT Token
// @route   POST api/users/az-redirect
// @access  Public
const azRedirect = asyncHandler(async (req, res) => {
  const errors = {};

  const tokenRequest = {
    code: req.body.code,
    scopes: ['user.read'],
    redirectUri: process.env.REDIRECT_URI,
  };

  try {
    const response = await cca.acquireTokenByCode(tokenRequest);
    console.log(
      'response from the original cca.acquireTokenByCode request',
      response
    );
    const user = await User.findOne({ email: response.account.username });

    if (!user) {
      let nameArray = response.account.name.split(' ');
      const newUser = new User({
        firstName: nameArray[0],
        lastName: nameArray[nameArray.length - 1],
        email: response.account.username,
        azureID: response.uniqueId,
      });

      user = await User.create(newUser);
      console.log('\nNew user created: \n', user);

      const payload = {
        id: user.id,
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        isTechnician: user.isTechnician,
        isAdmin: user.isAdmin,
      };

      jwt.sign(
        payload,
        process.env.JWT_SECRET,
        { expiresIn: '30d' },
        (err, token) => {
          res.json({
            success: true,
            token: token,
            user: user,
          });
        }
      );
    } else if (!user.isActive) {
      errors.azure = 'User is no longer permitted to access this application';
      return res.status(401).json(errors);
    } else {
      if (!user.azureID) {
        user.azureID = response.uniqueId;
        user.save().catch((err) => console.log(err));
      }
      const payload = {
        id: user.id,
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        isAdmin: user.isAdmin,
        isSupervisor: user.isSupervisor,
      };

      jwt.sign(
        payload,
        process.env.JWT_SECRET,
        { expiresIn: '30d' },
        (err, token) => {
          res.json({
            success: true,
            token: token,
            user: user,
          });
        }
      );
    }
  } catch (error) {
    console.log(error);
    res.status(500).send(error);
  }
});

Any ideas/help would be greatly appreciated!

EDIT:

Turning off strict mode has helped solve the issue, but that isn't a good long-term solution. I'm looking for a solution that either ensures that the dispatch(azureRedirect(code)); will only run once, or if there is a better practice here I don't know of. Thanks!