问:
How to prevent memory leak (OOM) when running two streams in one spark app?
I have a two streaming query in one app:

landing to cleaning zone: Move new data on landing zone(raw data format) to cleaning zone and save them as a delta format

Read log data from kafka and joining with delta format table(cleaning zone) and save not-joined data into landing zone again

Below is the code (Not whole code, but core and important code):

```<code>landing_label_path = "s3a://AWS_landing_PATH/folder1"
cleansing_label_path = "s3a://AWS_cleaning_PATH/folder2"

deltaTable = None
def upsert_to_cleaned_delta(pdf, batchId):
    global deltaTable

    if deltaTable is None:
        try:
            # If first time read, delta table will not exist --> raise Exception
            deltaTable = DeltaTable.forPath(spark, cleansing_label_path)
        except Exception as e:
            pdf.write.format("delta").partitionBy("year", "month", "day").save(cleansing_label_path)
            deltaTable = DeltaTable.forPath(spark, cleansing_label_path)
            return

    deltaTable.alias("old_data").merge(
        pdf.alias("new_data"), "old_data.token_address = new_data.token_address"
    ).whenMatchedUpdateAll(
    ).whenNotMatchedInsertAll().execute()

def main():
    #
    # App1. landing zone(raw parquet file) --> cleansing zone (delta format)
    #
    spark.sparkContext.setLocalProperty("spark.scheduler.pool", "pool1")
    _ = (
        spark.readStream.schema(raw_data_schema)
        .parquet(landing_label_path)
        .writeStream.format("delta")
        .option("checkpointLocation", landing_to_cleansing_chk_path)
        .foreachBatch(lambda pdf, batch_id: upsert_to_cleaned_delta(pdf, batch_id))
        .trigger(processingTime="1 second")
        .outputMode("append")
        .start()
    )

    #
    # App2. labeling on log streaming
    #
    # Wait until delta path appears
    time.sleep(100)

    spark.sparkContext.setLocalProperty("spark.scheduler.pool", "pool2")

    complete_label_df = spark.read.format("delta").load(cleansing_label_path)
    complete_label_df = complete_label_df.select(for_join_schema.fieldNames())

    # From kafka
    group_id = f"spark_{app_name}_{env}"
    kafka_options = {
        "kafka.sasl.jaas.config": f'org.apache.kafka.common.security.plain.PlainLoginModule required username="{bootstrap_username}" password="{bootstrap_password}";',
        "kafka.sasl.mechanism": "PLAIN",
        "kafka.security.protocol": "SASL_SSL",
        "kafka.bootstrap.servers": bootstrap_server,
        "group.id": group_id,
        "subscribe": topic_name,
        "maxOffsetsPerTrigger": 10,
    }
    log_streaming_df = spark.readStream.format("kafka").options(**kafka_options).load()
    # decode
    sr_client = SchemaRegistryClient(
        {
            "url": sr_server,
            "basic.auth.credentials.source": "USER_INFO",
            "basic.auth.user.info": f"{sr_username}:{sr_password}",
        }
    )
    schema_obj = sr_client.get_schema(f"{topic_name}-value", version="latest")
    decoded_log_streaming_df = (
        log_streaming_df.selectExpr("timestamp", "substring(value, 6) as avro_value")
        .select("timestamp", from_avro(col("avro_value"), json.dumps(schema_obj.schema.raw_schema)).alias("data"))
        .select(
            col("data.address").alias("token_address"),
            col("timestamp").alias("kafka_dt"),
        )
    )

    no_label_token_df = (
        decoded_log_streaming_df.join(complete_label_df, on="token_address", how="left")
        .filter(col("token_type").isNull())
    )
    new_label_token_df = no_label_token_df.mapInPandas(fill_the_label, label_schema)
    _ = (
        new_label_token_df.withColumn("update_dt", current_timestamp())
        .withColumn("year", date_format(col("update_dt"), "yyyy"))
        .withColumn("month", date_format(col("update_dt"), "MM"))
        .withColumn("day", date_format(col("update_dt"), "dd"))
        .writeStream.format("parquet")
        .option("path", landing_label_path)
        .option("checkpointLocation", newly_labeling_chk_path)
        .partitionBy("year", "month", "day")
        .trigger(processingTime="1 second")
        .outputMode("append")
        .start()
    )

    spark.streams.awaitAnyTermination()

if __name__ == "__main__":
    main()

</code>```

With sparkconf:

```<code>spark.eventLog.enabled: "true"
spark.hadoop.fs.s3a.connection.maximum: "200"
spark.hadoop.fs.s3a.connection.timeout: "1200000"
spark.hadoop.fs.s3a.fast.upload: "true"
spark.hadoop.fs.s3a.impl: org.apache.hadoop.fs.s3a.S3AFileSystem
spark.hadoop.fs.s3a.input.fadvise: random
spark.hadoop.fs.s3a.path.style.access: "true"
spark.hadoop.fs.s3a.readahead.range: 256K
spark.local.dir: /local1
spark.network.timeout: "2400"   # second
spark.speculation: "false"
spark.sql.catalog.spark_catalog: org.apache.spark.sql.delta.catalog.DeltaCatalog
spark.sql.extensions: io.delta.sql.DeltaSparkSessionExtension
spark.sql.parquet.compression.codec: gzip
spark.executor.heartbeatInterval: 60s

</code>```

Driver and Executor info:

```<code>driver:
  annotations: {} # TODO: add .Values.annotations
  labels:
    version: 3.2.1
  coreLimit: 1500m
  cores:
  memory: 4g
  memoryOverhead: 2g
  env:
  - name: PYTHONPATH
    value: /local1/python/lib
  - name: ENVIRONMENT
    value: dev
  serviceAccount: spark-operator
  volumeMounts:
  - mountPath: /local1
    name: spark-local-dir-1
    readOnly: false
  initContainers:
  - command:
    - sh
    - -c
    - chown -R 185 /local1
    image: public.ecr.aws/y4g4v0z7/busybox
    name: volume-permissions
    volumeMounts:
    - mountPath: /local1
      name: spark-local-dir-1
  - image: cimg/aws:2022.06
    name: download-python-dependencies
    command:
      - sh
      - -c
      - |
        mkdir -p /local1/python/lib
        aws s3 cp /libs.zip /tmp/libs.zip
        aws s3 cp /scripts.zip /tmp/scripts.zip
        unzip -o /tmp/libs.zip -d /local1/python/lib
        unzip -o /tmp/scripts.zip -d /local1/python/lib
    volumeMounts:
    - mountPath: /local1
      name: spark-local-dir-1
    resources:
      limits:
        cpu: 100m
        memory: 512Mi
      requests:
        cpu: 100m
        memory: 512Mi
    securityContext:
      runAsUser: 185

executor:
  annotations: {} # TODO: add .Values.annotations
  coreLimit: 1500m
  cores:
  instances: 1
  labels:
    version: 3.2.1
  memory: 4g
  memoryOverhead: 2g
  podSecurityContext:
    fsGroup: 185
  env:
  - name: PYTHONPATH
    value: /local1/python/lib
  - name: ENVIRONMENT
    value: dev
  volumeMounts:
  - mountPath: /local1
    name: spark-local-dir-1
    readOnly: false
  serviceAccount: spark-operator
  initContainers:
  - command:
    - sh
    - -c
    - chown -R 185 /local1
    image: public.ecr.aws/y4g4v0z7/busybox
    name: volume-permissions
    volumeMounts:
    - mountPath: /local1
      name: spark-local-dir-1
  - image: cimg/aws:2022.06
    name: download-python-dependencies
    command:
      - sh
      - -c
      - |
        mkdir -p /local1/python/lib
        aws s3 cp /libs.zip /tmp/libs.zip
        aws s3 cp /scripts.zip /tmp/scripts.zip
        unzip -o /tmp/libs.zip -d /local1/python/lib
        unzip -o /tmp/scripts.zip -d /local1/python/lib
    volumeMounts:
    - mountPath: /local1
      name: spark-local-dir-1
    resources:
      limits:
        cpu: 100m
        memory: 512Mi
      requests:
        cpu: 100m
        memory: 512Mi
    securityContext:
      runAsUser: 185
image: datamechanics/spark:3.2.1-hadoop-3.3.1-java-11-scala-2.12-python-3.8-latest

</code>```

Every time I run above code, after 10~12hours later, it raised OOM errors..

Driver memory keep increasing as time goes:

Body:
I have a two streaming query in one app:

landing to cleaning zone: Move new data on landing zone(raw data format) to cleaning zone and save them as a delta format

Read log data from kafka and joining with delta format table(cleaning zone) and save not-joined data into landing zone again

Below is the code (Not whole code, but core and important code):

landing_label_path = "s3a://AWS_landing_PATH/folder1"
cleansing_label_path = "s3a://AWS_cleaning_PATH/folder2"

deltaTable = None
def upsert_to_cleaned_delta(pdf, batchId):
    global deltaTable

    if deltaTable is None:
        try:
            # If first time read, delta table will not exist --> raise Exception
            deltaTable = DeltaTable.forPath(spark, cleansing_label_path)
        except Exception as e:
            pdf.write.format("delta").partitionBy("year", "month", "day").save(cleansing_label_path)
            deltaTable = DeltaTable.forPath(spark, cleansing_label_path)
            return

    deltaTable.alias("old_data").merge(
        pdf.alias("new_data"), "old_data.token_address = new_data.token_address"
    ).whenMatchedUpdateAll(
    ).whenNotMatchedInsertAll().execute()

def main():
    #
    # App1. landing zone(raw parquet file) --> cleansing zone (delta format)
    #
    spark.sparkContext.setLocalProperty("spark.scheduler.pool", "pool1")
    _ = (
        spark.readStream.schema(raw_data_schema)
        .parquet(landing_label_path)
        .writeStream.format("delta")
        .option("checkpointLocation", landing_to_cleansing_chk_path)
        .foreachBatch(lambda pdf, batch_id: upsert_to_cleaned_delta(pdf, batch_id))
        .trigger(processingTime="1 second")
        .outputMode("append")
        .start()
    )

    #
    # App2. labeling on log streaming
    #
    # Wait until delta path appears
    time.sleep(100)

    spark.sparkContext.setLocalProperty("spark.scheduler.pool", "pool2")

    complete_label_df = spark.read.format("delta").load(cleansing_label_path)
    complete_label_df = complete_label_df.select(for_join_schema.fieldNames())

    # From kafka
    group_id = f"spark_{app_name}_{env}"
    kafka_options = {
        "kafka.sasl.jaas.config": f'org.apache.kafka.common.security.plain.PlainLoginModule required username="{bootstrap_username}" password="{bootstrap_password}";',
        "kafka.sasl.mechanism": "PLAIN",
        "kafka.security.protocol": "SASL_SSL",
        "kafka.bootstrap.servers": bootstrap_server,
        "group.id": group_id,
        "subscribe": topic_name,
        "maxOffsetsPerTrigger": 10,
    }
    log_streaming_df = spark.readStream.format("kafka").options(**kafka_options).load()
    # decode
    sr_client = SchemaRegistryClient(
        {
            "url": sr_server,
            "basic.auth.credentials.source": "USER_INFO",
            "basic.auth.user.info": f"{sr_username}:{sr_password}",
        }
    )
    schema_obj = sr_client.get_schema(f"{topic_name}-value", version="latest")
    decoded_log_streaming_df = (
        log_streaming_df.selectExpr("timestamp", "substring(value, 6) as avro_value")
        .select("timestamp", from_avro(col("avro_value"), json.dumps(schema_obj.schema.raw_schema)).alias("data"))
        .select(
            col("data.address").alias("token_address"),
            col("timestamp").alias("kafka_dt"),
        )
    )

    no_label_token_df = (
        decoded_log_streaming_df.join(complete_label_df, on="token_address", how="left")
        .filter(col("token_type").isNull())
    )
    new_label_token_df = no_label_token_df.mapInPandas(fill_the_label, label_schema)
    _ = (
        new_label_token_df.withColumn("update_dt", current_timestamp())
        .withColumn("year", date_format(col("update_dt"), "yyyy"))
        .withColumn("month", date_format(col("update_dt"), "MM"))
        .withColumn("day", date_format(col("update_dt"), "dd"))
        .writeStream.format("parquet")
        .option("path", landing_label_path)
        .option("checkpointLocation", newly_labeling_chk_path)
        .partitionBy("year", "month", "day")
        .trigger(processingTime="1 second")
        .outputMode("append")
        .start()
    )

    spark.streams.awaitAnyTermination()

if __name__ == "__main__":
    main()

With sparkconf:

spark.eventLog.enabled: "true"
spark.hadoop.fs.s3a.connection.maximum: "200"
spark.hadoop.fs.s3a.connection.timeout: "1200000"
spark.hadoop.fs.s3a.fast.upload: "true"
spark.hadoop.fs.s3a.impl: org.apache.hadoop.fs.s3a.S3AFileSystem
spark.hadoop.fs.s3a.input.fadvise: random
spark.hadoop.fs.s3a.path.style.access: "true"
spark.hadoop.fs.s3a.readahead.range: 256K
spark.local.dir: /local1
spark.network.timeout: "2400"   # second
spark.speculation: "false"
spark.sql.catalog.spark_catalog: org.apache.spark.sql.delta.catalog.DeltaCatalog
spark.sql.extensions: io.delta.sql.DeltaSparkSessionExtension
spark.sql.parquet.compression.codec: gzip
spark.executor.heartbeatInterval: 60s

Driver and Executor info:

driver:
  annotations: {} # TODO: add .Values.annotations
  labels:
    version: 3.2.1
  coreLimit: 1500m
  cores:
  memory: 4g
  memoryOverhead: 2g
  env:
  - name: PYTHONPATH
    value: /local1/python/lib
  - name: ENVIRONMENT
    value: dev
  serviceAccount: spark-operator
  volumeMounts:
  - mountPath: /local1
    name: spark-local-dir-1
    readOnly: false
  initContainers:
  - command:
    - sh
    - -c
    - chown -R 185 /local1
    image: public.ecr.aws/y4g4v0z7/busybox
    name: volume-permissions
    volumeMounts:
    - mountPath: /local1
      name: spark-local-dir-1
  - image: cimg/aws:2022.06
    name: download-python-dependencies
    command:
      - sh
      - -c
      - |
        mkdir -p /local1/python/lib
        aws s3 cp /libs.zip /tmp/libs.zip
        aws s3 cp /scripts.zip /tmp/scripts.zip
        unzip -o /tmp/libs.zip -d /local1/python/lib
        unzip -o /tmp/scripts.zip -d /local1/python/lib
    volumeMounts:
    - mountPath: /local1
      name: spark-local-dir-1
    resources:
      limits:
        cpu: 100m
        memory: 512Mi
      requests:
        cpu: 100m
        memory: 512Mi
    securityContext:
      runAsUser: 185

executor:
  annotations: {} # TODO: add .Values.annotations
  coreLimit: 1500m
  cores:
  instances: 1
  labels:
    version: 3.2.1
  memory: 4g
  memoryOverhead: 2g
  podSecurityContext:
    fsGroup: 185
  env:
  - name: PYTHONPATH
    value: /local1/python/lib
  - name: ENVIRONMENT
    value: dev
  volumeMounts:
  - mountPath: /local1
    name: spark-local-dir-1
    readOnly: false
  serviceAccount: spark-operator
  initContainers:
  - command:
    - sh
    - -c
    - chown -R 185 /local1
    image: public.ecr.aws/y4g4v0z7/busybox
    name: volume-permissions
    volumeMounts:
    - mountPath: /local1
      name: spark-local-dir-1
  - image: cimg/aws:2022.06
    name: download-python-dependencies
    command:
      - sh
      - -c
      - |
        mkdir -p /local1/python/lib
        aws s3 cp /libs.zip /tmp/libs.zip
        aws s3 cp /scripts.zip /tmp/scripts.zip
        unzip -o /tmp/libs.zip -d /local1/python/lib
        unzip -o /tmp/scripts.zip -d /local1/python/lib
    volumeMounts:
    - mountPath: /local1
      name: spark-local-dir-1
    resources:
      limits:
        cpu: 100m
        memory: 512Mi
      requests:
        cpu: 100m
        memory: 512Mi
    securityContext:
      runAsUser: 185
image: datamechanics/spark:3.2.1-hadoop-3.3.1-java-11-scala-2.12-python-3.8-latest

Every time I run above code, after 10~12hours later, it raised OOM errors..

Driver memory keep increasing as time goes:


来源: stackexchange

问:
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
Its my first time posting please help. I deploy this project on render.com then error happen. It works locally but in hosting site its not. Please help thank you for all responses.

```<code>import { useState } from 'react';
import { useAuthContext } from './useAuthContext';

export const useLogin = () => {
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(null);
  const { dispatch } = useAuthContext();

  const login = async (email, password) => {
    setIsLoading(true);
    setError(null);

    const response = await fetch('/api/skilledInfo/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });
    const json = await response.json();

    if (!response.ok) {
      setIsLoading(false);
      setError(json.error);
    }
    if (response.ok) {
      // save the user to local storage
      localStorage.setItem('user', JSON.stringify(json));

      // update the auth context
      dispatch({ type: 'LOGIN', payload: json });

      // update loading state
      setIsLoading(false);
    }
  };

  return { login, isLoading, error };
};
</code>```

Here is the error
Error Message then the code'const json = await response.json();' highlighted.

If I understand correctly this code return promise object and I need to turn it into JSON. But I do not know how. Please help

ContentLicense: CC BY-SA 4.0

Body:
Its my first time posting please help. I deploy this project on render.com then error happen. It works locally but in hosting site its not. Please help thank you for all responses.

import { useState } from 'react';
import { useAuthContext } from './useAuthContext';

export const useLogin = () => {
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(null);
  const { dispatch } = useAuthContext();

  const login = async (email, password) => {
    setIsLoading(true);
    setError(null);

    const response = await fetch('/api/skilledInfo/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });
    const json = await response.json();

    if (!response.ok) {
      setIsLoading(false);
      setError(json.error);
    }
    if (response.ok) {
      // save the user to local storage
      localStorage.setItem('user', JSON.stringify(json));

      // update the auth context
      dispatch({ type: 'LOGIN', payload: json });

      // update loading state
      setIsLoading(false);
    }
  };

  return { login, isLoading, error };
};

Here is the error
Error Message then the code'const json = await response.json();' highlighted.

If I understand correctly this code return promise object and I need to turn it into JSON. But I do not know how. Please help


问:
Clang can't find system headers without --stdlib=libc++
On my system (Ubuntu 22.04) I have a problem where clang doesn't find system headers but gcc does. I have a simple test program...

```<code>#include <iostream>

int main(int argc, char** argv) {
    using namespace std;
    cout << "hello world!" << endl;
}
</code>```

I can compile this just fine with g++ main.cpp -o test but clang++ main.cpp -o test will fail with...

```<code>main.cpp:1:10: fatal error: 'iostream' file not found
#include <iostream>
         ^~~~~~~~~~
1 error generated.
</code>```

Output of clang++ -E -xc++ - -v -std=c++17 --stdlib=libc++:

```<code>Ubuntu clang version 14.0.0-1ubuntu1
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/11
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/12
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/12
Candidate multilib: .;@m64
Selected multilib: .;@m64
 (in-process)
 "/usr/lib/llvm-14/bin/clang" -cc1 -triple x86_64-pc-linux-gnu -E -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name - -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=all -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -v -fcoverage-compilation-dir=/home/david -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -internal-isystem /usr/lib/llvm-14/bin/../include/c++/v1 -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/home/david -ferror-limit 19 -fgnuc-version=4.2.1 -fcxx-exceptions -fexceptions -fcolor-diagnostics -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o - -x c++ -
clang -cc1 version 14.0.0 based upon LLVM 14.0.0 default target x86_64-pc-linux-gnu
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include"
ignoring nonexistent directory "/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/lib/llvm-14/bin/../include/c++/v1
 /usr/lib/llvm-14/lib/clang/14.0.0/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
^C
</code>```

Output of clang++ -E -xc++ - -v -std=c++17

```<code>Ubuntu clang version 14.0.0-1ubuntu1
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/11
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/12
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/12
Candidate multilib: .;@m64
Selected multilib: .;@m64
 (in-process)
 "/usr/lib/llvm-14/bin/clang" -cc1 -triple x86_64-pc-linux-gnu -E -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name - -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=all -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -v -fcoverage-compilation-dir=/home/david -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++ -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/x86_64-linux-gnu -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/home/david -ferror-limit 19 -fgnuc-version=4.2.1 -fcxx-exceptions -fexceptions -fcolor-diagnostics -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o - -x c++ -
clang -cc1 version 14.0.0 based upon LLVM 14.0.0 default target x86_64-pc-linux-gnu
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/backward"
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include"
ignoring nonexistent directory "/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++
 /usr/lib/llvm-14/lib/clang/14.0.0/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
^C
</code>```

if I use clang++ main.cpp -o test --stdlib=libc++ it will work fine, shouldn't this be the default though? How can I configure clang to find the header without having to pass that argument?

Body:
On my system (Ubuntu 22.04) I have a problem where clang doesn't find system headers but gcc does. I have a simple test program...

#include <iostream>

int main(int argc, char** argv) {
    using namespace std;
    cout << "hello world!" << endl;
}

I can compile this just fine with g++ main.cpp -o test but clang++ main.cpp -o test will fail with...

main.cpp:1:10: fatal error: 'iostream' file not found
#include <iostream>
         ^~~~~~~~~~
1 error generated.

Output of clang++ -E -xc++ - -v -std=c++17 --stdlib=libc++:

Ubuntu clang version 14.0.0-1ubuntu1
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/11
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/12
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/12
Candidate multilib: .;@m64
Selected multilib: .;@m64
 (in-process)
 "/usr/lib/llvm-14/bin/clang" -cc1 -triple x86_64-pc-linux-gnu -E -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name - -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=all -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -v -fcoverage-compilation-dir=/home/david -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -internal-isystem /usr/lib/llvm-14/bin/../include/c++/v1 -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/home/david -ferror-limit 19 -fgnuc-version=4.2.1 -fcxx-exceptions -fexceptions -fcolor-diagnostics -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o - -x c++ -
clang -cc1 version 14.0.0 based upon LLVM 14.0.0 default target x86_64-pc-linux-gnu
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include"
ignoring nonexistent directory "/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/lib/llvm-14/bin/../include/c++/v1
 /usr/lib/llvm-14/lib/clang/14.0.0/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
^C

Output of clang++ -E -xc++ - -v -std=c++17

Ubuntu clang version 14.0.0-1ubuntu1
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/11
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/12
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/12
Candidate multilib: .;@m64
Selected multilib: .;@m64
 (in-process)
 "/usr/lib/llvm-14/bin/clang" -cc1 -triple x86_64-pc-linux-gnu -E -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name - -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=all -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -v -fcoverage-compilation-dir=/home/david -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++ -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/x86_64-linux-gnu -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/home/david -ferror-limit 19 -fgnuc-version=4.2.1 -fcxx-exceptions -fexceptions -fcolor-diagnostics -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o - -x c++ -
clang -cc1 version 14.0.0 based upon LLVM 14.0.0 default target x86_64-pc-linux-gnu
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/backward"
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include"
ignoring nonexistent directory "/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++
 /usr/lib/llvm-14/lib/clang/14.0.0/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
^C

if I use clang++ main.cpp -o test --stdlib=libc++ it will work fine, shouldn't this be the default though? How can I configure clang to find the header without having to pass that argument?


问:
How to get the item name and not its address when requesting with a "condition event" from a Simpy-Store
A Simpy-Store is filled with elements {0}...{9}

```<code>car_Fleet = simpy.Store(env, capacity=10)
i = 0
for i in range(10):
    car_Fleet.put({i})
    i += 1
</code>```

When requesting an item from that store

```<code>    car_id = yield car_Fleet.get()
    print(car_id)
</code>```

the print statement returns the "value" of the Simpy-Store item, for example {4}

But when using a simpy condition event

```<code>with car_Fleet.get() as req:
    patience = 2
    results = yield req | env.timeout(patience)

    wait = env.now - arrive

    if req in results:
        .....
        print(req)
        .....

    else:
        # We quit
        ...

</code>```

The print(req) (also print(req.value) ) statement returns "<StoreGet() object at 0x7f8e2681da50>" and not the value of the requested item as in the code above.
Also print(results) returns:  <ConditionValue {<StoreGet() object at 0x7fe1c37f4b80>: <StoreGet() object at 0x7fe1c37f41f0>}>

How can one access the value instead of the address of the item requested from the store?

Edit: Michaels comment solved the problem. The results variable can be accessed as follows. By using results[req] one can retrieve the name of the requested item. When returning an Item to the store it's also important to pass results[req] with carFleet.put .

Body:
A Simpy-Store is filled with elements {0}...{9}

car_Fleet = simpy.Store(env, capacity=10)
i = 0
for i in range(10):
    car_Fleet.put({i})
    i += 1

When requesting an item from that store

    car_id = yield car_Fleet.get()
    print(car_id)

the print statement returns the "value" of the Simpy-Store item, for example {4}

But when using a simpy condition event

with car_Fleet.get() as req:
    patience = 2
    results = yield req | env.timeout(patience)

    wait = env.now - arrive

    if req in results:
        .....
        print(req)
        .....

    else:
        # We quit
        ...

The print(req) (also print(req.value) ) statement returns "<StoreGet() object at 0x7f8e2681da50>" and not the value of the requested item as in the code above.
Also print(results) returns:  <ConditionValue {<StoreGet() object at 0x7fe1c37f4b80>: <StoreGet() object at 0x7fe1c37f41f0>}>

How can one access the value instead of the address of the item requested from the store?

Edit: Michaels comment solved the problem. The results variable can be accessed as follows. By using results[req] one can retrieve the name of the requested item. When returning an Item to the store it's also important to pass results[req] with carFleet.put .


问:
Alternative add programatically generated Tailwind classes (Vue, Nuxt)
According to this question and article inside. It's not possible with Tailwind CSS to programatically generate dynamic classes.

What's the alternative If my usecase must be dynamic? I have a progress bar div with a primary background and a span with dynamic progress coming from the api. I want to set a width class on the span like the following

```<code><script setup>
  const items = [...] // Data
  const getWidthClass = (progressValue) => `'w-[${progressValue}]'`;
</script>

<template>
  <div v-for="item in items" class="bg-red-500">
    <p class="bg-green-500" :class="getWidthClass(item.progressValue)" />
   <div/>
</template>
</code>```

The utility class (w-[50%] for example) is added correctly but it has no styles as the questions explained.

Body:
According to this question and article inside. It's not possible with Tailwind CSS to programatically generate dynamic classes.

What's the alternative If my usecase must be dynamic? I have a progress bar div with a primary background and a span with dynamic progress coming from the api. I want to set a width class on the span like the following

<template>

</template>

The utility class (w-[50%] for example) is added correctly but it has no styles as the questions explained.


问:
Keep iOS dev app running using Background Modes
I've written a basic FTP Server app in Swift 5 using SwiftUI, it needs to keep a TCP socket listener open waiting for incoming ftp client connections. Ideally I'll keep it running with the phone locked.

I've read you can hijack the Background modes in Swift to run other code, which is fine as this app will never be published - it's for my use only to transfer pics off a DSLR. Someone suggested in a thread to use the Audio mode to play a silent file and that would keep everything running. Does anyone know if what I'm trying to do is possible?

I've added an AVAudioPlayer that just loops a random file and updated Info.plist to add the Audio BG mode, but I think more than this is required as it doesn't appear to be working.

Based off this post it looks like I could maybe use VoIP bg mode? Any input or advice appreciated :)


问:
How to convert runtime audio(not in file format) to text form in Collab?
I have recorded audio from the microphone using Javascript code in collab. Audio not be stored in any file.  Now I wanted to convert this audio to text form but I do not find any function/ method for the conversion.

Here is my last line of code to display the audio.

```<code>import IPython.display as ipd

ipd.display(ipd.Audio(audio))
</code>```

How to convert this audio to text form in a collab?

Body:
I have recorded audio from the microphone using Javascript code in collab. Audio not be stored in any file.  Now I wanted to convert this audio to text form but I do not find any function/ method for the conversion.

Here is my last line of code to display the audio.

import IPython.display as ipd

ipd.display(ipd.Audio(audio))

How to convert this audio to text form in a collab?


问:
How to return a flatten field in a mongodb document
I have a document with this structure:

```<code>{
  "_id": {
    "$oid": "639a1d134338565900901bc2"
  },
  "eventId": 6,
  "userId": {
    "$oid": "636d3ffb7d4cf8067dedc5d4"
  },
  "createdAt": {
    "$date": {
      "$numberLong": "1671044371692"
    }
  },
  "lastModified": {
    "$date": {
      "$numberLong": "1671132870160"
    }
  },
  "type": "Feature",
  "geometry": {
    "coordinates": [
      -71.820159,
      41.877574
    ],
    "type": "Point"
  },
  "properties": {
    "timestamp": {
      "$date": {
        "$numberLong": "1671044350325"
      }
    },
    "forms": [
      {
        "formId": 14,
        "field0": "CFS1 Fire",
        "field1": "Dispatched",
        "field2": null,
        "_id": {
          "$oid": "639a1d134338565900901bc3"
        }
      },
      {
        "formId": 13,
        "field1": "test",
        "_id": {
          "$oid": "639b76c64338565900901c42"
        }
      }
    ]
  },
  "favoriteUserIds": [],
  "states": [
    {
      "name": "active",
      "userId": {
        "$oid": "636d3ffb7d4cf8067dedc5d4"
      },
      "_id": {
        "$oid": "639a1d134338565900901bc4"
      }
    }
  ],
  "attachments": [],
  "__v": 1
}
</code>```

I am working on mongodb compass. I want to create a new view where when I call the above document, the fields nested inside the "properties" field are at the top level. Meaning that the above document would turn to this:

```<code>{
  "_id": {
    "$oid": "639a1d134338565900901bc2"
  },
  "eventId": 6,
  "userId": {
    "$oid": "636d3ffb7d4cf8067dedc5d4"
  },
  "createdAt": {
    "$date": {
      "$numberLong": "1671044371692"
    }
  },
  "lastModified": {
    "$date": {
      "$numberLong": "1671132870160"
    }
  },
  "type": "Feature",
  "geometry": {
    "coordinates": [
      -71.820159,
      41.877574
    ],
    "type": "Point"
  },
  "formId1": 14,
  "form_1_field0": "CFS1 Fire",
  "form_1_field1": "Dispatched",
  "form_1_field2": null,
  "_id": {"$oid": "639a1d134338565900901bc3"},

  "formId2": 13,
  "form_2_field1": "test",
  "_id": {"$oid": "639b76c64338565900901c42"}

  "properties": {
    "timestamp": {
      "$date": {
        "$numberLong": "1671044350325"
      }
    },
  },
  "favoriteUserIds": [],
  "states": [
    {
      "name": "active",
      "userId": {
        "$oid": "636d3ffb7d4cf8067dedc5d4"
      },
      "_id": {
        "$oid": "639a1d134338565900901bc4"
      }
    }
  ],
  "attachments": [],
  "__v": 1
}
</code>```

I want to do this only with the "properties" field. Also, there may be instances where the "forms" array inside the "properties" field is empty. Also, each object has different number of fields.

I'm new to mongodb and therefor new to mongodb compass. I suspect I can do this by using aggregations in compass, but not sure if I compass is what I am supposed to be using or something else.

Body:
I have a document with this structure:

{
  "_id": {
    "$oid": "639a1d134338565900901bc2"
  },
  "eventId": 6,
  "userId": {
    "$oid": "636d3ffb7d4cf8067dedc5d4"
  },
  "createdAt": {
    "$date": {
      "$numberLong": "1671044371692"
    }
  },
  "lastModified": {
    "$date": {
      "$numberLong": "1671132870160"
    }
  },
  "type": "Feature",
  "geometry": {
    "coordinates": [
      -71.820159,
      41.877574
    ],
    "type": "Point"
  },
  "properties": {
    "timestamp": {
      "$date": {
        "$numberLong": "1671044350325"
      }
    },
    "forms": [
      {
        "formId": 14,
        "field0": "CFS1 Fire",
        "field1": "Dispatched",
        "field2": null,
        "_id": {
          "$oid": "639a1d134338565900901bc3"
        }
      },
      {
        "formId": 13,
        "field1": "test",
        "_id": {
          "$oid": "639b76c64338565900901c42"
        }
      }
    ]
  },
  "favoriteUserIds": [],
  "states": [
    {
      "name": "active",
      "userId": {
        "$oid": "636d3ffb7d4cf8067dedc5d4"
      },
      "_id": {
        "$oid": "639a1d134338565900901bc4"
      }
    }
  ],
  "attachments": [],
  "__v": 1
}

I am working on mongodb compass. I want to create a new view where when I call the above document, the fields nested inside the "properties" field are at the top level. Meaning that the above document would turn to this:

{
  "_id": {
    "$oid": "639a1d134338565900901bc2"
  },
  "eventId": 6,
  "userId": {
    "$oid": "636d3ffb7d4cf8067dedc5d4"
  },
  "createdAt": {
    "$date": {
      "$numberLong": "1671044371692"
    }
  },
  "lastModified": {
    "$date": {
      "$numberLong": "1671132870160"
    }
  },
  "type": "Feature",
  "geometry": {
    "coordinates": [
      -71.820159,
      41.877574
    ],
    "type": "Point"
  },
  "formId1": 14,
  "form_1_field0": "CFS1 Fire",
  "form_1_field1": "Dispatched",
  "form_1_field2": null,
  "_id": {"$oid": "639a1d134338565900901bc3"},

  "formId2": 13,
  "form_2_field1": "test",
  "_id": {"$oid": "639b76c64338565900901c42"}

  "properties": {
    "timestamp": {
      "$date": {
        "$numberLong": "1671044350325"
      }
    },
  },
  "favoriteUserIds": [],
  "states": [
    {
      "name": "active",
      "userId": {
        "$oid": "636d3ffb7d4cf8067dedc5d4"
      },
      "_id": {
        "$oid": "639a1d134338565900901bc4"
      }
    }
  ],
  "attachments": [],
  "__v": 1
}

I want to do this only with the "properties" field. Also, there may be instances where the "forms" array inside the "properties" field is empty. Also, each object has different number of fields.

I'm new to mongodb and therefor new to mongodb compass. I suspect I can do this by using aggregations in compass, but not sure if I compass is what I am supposed to be using or something else.


问:
ScrollView React Native with Flexbox won't work
I created a set of 8 boxes. I used flexbox to position them. The boxes will not all fit on the screen so I added a  to vertically scroll through them. But somehow it won't work. Only 8 boxes are shown and I cannot scroll down to see the rest. I am frustrated.

Any ideas what is wrong here?

Here is my code:

```<code><View style={styles.background}>
      <ScrollView style={styles.scrollView}>
             <View style={styles.LessonBoxRow}>
            <Animated.View
              entering={FadeInDown.delay(300).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
              <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
             <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
              <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
              <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
              <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
             <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
              <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
             <LessonBox/>
            </Animated.View>
            </View>
      </ScrollView>
      </View>
  );
}

const styles = StyleSheet.create({

  scrollView: {
    backgroundColor: 'pink',
    flex: 1,
  },
  LessonBoxRow: {
    flexDirection: "row",
    justifyContent: "space-evenly",
    top: 140,
    flexWrap: "wrap",
    marginTop: 10,
  },

  background: {
    height: "100%",
  },

});
</code>```

Body:
I created a set of 8 boxes. I used flexbox to position them. The boxes will not all fit on the screen so I added a  to vertically scroll through them. But somehow it won't work. Only 8 boxes are shown and I cannot scroll down to see the rest. I am frustrated.

Any ideas what is wrong here?

Here is my code:

<View style={styles.background}>
      <ScrollView style={styles.scrollView}>
             <View style={styles.LessonBoxRow}>
            <Animated.View
              entering={FadeInDown.delay(300).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
              <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
             <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
              <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
              <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
              <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
             <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
              <LessonBox/>
            </Animated.View>
            <Animated.View
              entering={FadeInDown.delay(400).duration(200)}
              easing={Easing.bezier(0.5, 0.01, 0, 1)}
            >
             <LessonBox/>
            </Animated.View>
            </View>
      </ScrollView>
      </View>
  );
}

const styles = StyleSheet.create({

  scrollView: {
    backgroundColor: 'pink',
    flex: 1,
  },
  LessonBoxRow: {
    flexDirection: "row",
    justifyContent: "space-evenly",
    top: 140,
    flexWrap: "wrap",
    marginTop: 10,
  },

  background: {
    height: "100%",
  },

});


问:
Issue using add_row() and add_sub_row() in Advanced Custom Fields (Pro)
I'm using some PHP code to add fields into Advanced Custom Fields promgrammatically and it's working perfectly except I'm stuck on one field.

```<code>add_row('layouts', [
    'acf_fc_layout' => 'background_image_with_content_block',
    'slide_images' => 248,
    'overlay' => 'Blue',
    'include_job_search' => 'No',
    'heading_type' => 'Heading 2',
    'heading' => 'Upload your CV today',
    'content' => 'Upload your CV today, and we will be in touch to help you find your perfect career. Upload your CV today, and we will be in touch to help you find your perfect career.',
], $post_id);
</code>```

I have a Flexible Content field called "Layouts" and within this I have a field called "background_image_with_content_block". My code above is adding fields to that ACF layout.

All of it works, however I have a repeater field called "links" inside this which I would like to be able to add rows too and subsequently data to the fields inside of my "links" repeater.

I have two fields inside my "links" repeater field. One is a "link" type field and the other is a "select" type field. Is there a way to do this?

I've tried this but I don't think I've used it correctly:

```<code>add_row('layouts', [
    'acf_fc_layout' => 'background_image_with_content_block',
    'slide_images' => 248,
    'overlay' => 'Blue',
    'include_job_search' => 'No',
    'heading_type' => 'Heading 2',
    'heading' => 'Upload your CV today',
    'content' => 'Upload your CV today, and we will be in touch to help you find your perfect career. Upload your CV today, and we will be in touch to help you find your perfect career.',
     add_sub_row('links', [
        'acf_fc_layout' => 'background_image_with_content_block',
        'link_colour' => 'White',
    ], $post_id)
], $post_id);
</code>```

Any help would be much appreciated, thanks!

Body:
I'm using some PHP code to add fields into Advanced Custom Fields promgrammatically and it's working perfectly except I'm stuck on one field.

add_row('layouts', [
    'acf_fc_layout' => 'background_image_with_content_block',
    'slide_images' => 248,
    'overlay' => 'Blue',
    'include_job_search' => 'No',
    'heading_type' => 'Heading 2',
    'heading' => 'Upload your CV today',
    'content' => 'Upload your CV today, and we will be in touch to help you find your perfect career. Upload your CV today, and we will be in touch to help you find your perfect career.',
], $post_id);

I have a Flexible Content field called "Layouts" and within this I have a field called "background_image_with_content_block". My code above is adding fields to that ACF layout.

All of it works, however I have a repeater field called "links" inside this which I would like to be able to add rows too and subsequently data to the fields inside of my "links" repeater.

I have two fields inside my "links" repeater field. One is a "link" type field and the other is a "select" type field. Is there a way to do this?

I've tried this but I don't think I've used it correctly:

add_row('layouts', [
    'acf_fc_layout' => 'background_image_with_content_block',
    'slide_images' => 248,
    'overlay' => 'Blue',
    'include_job_search' => 'No',
    'heading_type' => 'Heading 2',
    'heading' => 'Upload your CV today',
    'content' => 'Upload your CV today, and we will be in touch to help you find your perfect career. Upload your CV today, and we will be in touch to help you find your perfect career.',
     add_sub_row('links', [
        'acf_fc_layout' => 'background_image_with_content_block',
        'link_colour' => 'White',
    ], $post_id)
], $post_id);

Any help would be much appreciated, thanks!


问:
How do I parse a web page from its URL using JavaScript?
I'm trying to use ZenQuotes to get a random quote.

When I click on this link: https://zenquotes.io/api/random/

I get redirected to a page with a random quote in it. How can I get this text and put it into JSON in JavaScript?

I found this on a website to do a HTTP request:

```<code>const Http = new XMLHttpRequest();
const url='https://zenquotes.io/api/quotes/';
Http.open("GET", url);
Http.send();

Http.onreadystatechange = (e) => {
  console.log(Http)
}
</code>```

However, I'm not sure what I'm looking for.

Body:
I'm trying to use ZenQuotes to get a random quote.

When I click on this link: https://zenquotes.io/api/random/

I get redirected to a page with a random quote in it. How can I get this text and put it into JSON in JavaScript?

I found this on a website to do a HTTP request:

const Http = new XMLHttpRequest();
const url='https://zenquotes.io/api/quotes/';
Http.open("GET", url);
Http.send();

Http.onreadystatechange = (e) => {
  console.log(Http)
}

However, I'm not sure what I'm looking for.


问:
ASP.NET - CreatedAtRoute with two parameters
How can I use my GetUser function in the CreatedAtRoute function?

```<code>    [HttpGet]
    public ActionResult GetUser(string login, string password)
    {
        return Ok(_map.Map<UserReadDTO>(_dataStore.GetUser(login, password)));
    }

    [HttpPost]
    public ActionResult AddUser(UserWriteDTO userDTO)
    {
        User user = _map.Map<User>(userDTO);
        _dataStore.AddUser(user);
        _dataStore.SaveChanges();
        return CreatedAtRoute(nameof(GetUser), new { }, new { Login = user.Login, Password = user.Password });
    }
</code>```

I tried many parameters but everytime I got the error that the route isn't correct.

Body:
How can I use my GetUser function in the CreatedAtRoute function?

    [HttpGet]
    public ActionResult GetUser(string login, string password)
    {
        return Ok(_map.Map<UserReadDTO>(_dataStore.GetUser(login, password)));
    }

    [HttpPost]
    public ActionResult AddUser(UserWriteDTO userDTO)
    {
        User user = _map.Map<User>(userDTO);
        _dataStore.AddUser(user);
        _dataStore.SaveChanges();
        return CreatedAtRoute(nameof(GetUser), new { }, new { Login = user.Login, Password = user.Password });
    }

I tried many parameters but everytime I got the error that the route isn't correct.


问:
How to make Pycharm Console "behave" like Visual Studio Interactive window?
Somehow using the VS Interactive window has always felt more user friendly to me than the console in Pycharm.

Is there a way that one can make the Pycharm console "behave" like the Interactive window in Visual Studio? In the sense that...

...the input field, which in Pycharm is a separate field which for some reason always sticks to the bottom of the console, can be "scrolled up" just like the rest of the console

...and such that one can navigate the caret around freely in the console using the arrow keys (e.g. to select previous output), instead of only being able to use arrow keys to toggle through previous commands

Thanks


问:
JWT Introspect with JOSE
I have inherited a node express application, which exposes rest APIs.
That system can get a jwt in the request and verify using jose.verify method.
Means that it verifies the jwks.
The task I have is to be able to check if there was a revoke on the jwt.
Means that I have to call the IDP with the token to be verified.
I think that what I have to do is "introspect" but as far as I investigated,
I didn't see a introspect option upon JOSE.
Must say that I almost couldn't find a documentation for JOSE.
Does anyone know if I can do introspect with JOSE and if not, what is the
suggested way to do it with node ?
Thanks in advance!</p>

Title: JWT Introspect with JOSE


问:
How to get extension service_worker (Background page) object in WebdriverIO
I am new to WebdriverIO.

I want test my browser extension using WebdriverIO, I am able to install extension using .crx file, but I want to get control over the extension to execute few tests.

**Extension Install Code: (config.js)
**

```<code>capabilities: [
    {
      maxInstances: 5,
      browserName: "chrome",
      "goog:chromeOptions": {
        args: ["disable-popup-blocking", "allow-insecure-localhost"],
        extensions: [
          require("fs").readFileSync("/path/extension_file.crx").toString("base64"),
        ],
      },
      acceptInsecureCerts: true,
    },
</code>```

Thank you in advance

I tried to open extension popup and get control of the it but that did not work as I am not able to open extension popup programmatically (Using Chrome API & WebdriverIO). Also, I am not sure how to configure the browser to have access to the background page (or service).
I went through the WebdriverIO documentation as well the Chrome API documentation and since both of it did not work posting this here!

Expected behaviour
After the installation :

To be able to launch the extension pop up after installation

To get access to the extension background page (or service worker)

Body:
I am new to WebdriverIO.

I want test my browser extension using WebdriverIO, I am able to install extension using .crx file, but I want to get control over the extension to execute few tests.

**Extension Install Code: (config.js)
**

capabilities: [
    {
      maxInstances: 5,
      browserName: "chrome",
      "goog:chromeOptions": {
        args: ["disable-popup-blocking", "allow-insecure-localhost"],
        extensions: [
          require("fs").readFileSync("/path/extension_file.crx").toString("base64"),
        ],
      },
      acceptInsecureCerts: true,
    },

Thank you in advance

I tried to open extension popup and get control of the it but that did not work as I am not able to open extension popup programmatically (Using Chrome API & WebdriverIO). Also, I am not sure how to configure the browser to have access to the background page (or service).
I went through the WebdriverIO documentation as well the Chrome API documentation and since both of it did not work posting this here!

Expected behaviour
After the installation :

To be able to launch the extension pop up after installation

To get access to the extension background page (or service worker)


问:
Attempting to reload window makes the window close
I am trying to extend an existing Macos application which is built on the Electron framework.  The code is written in HTML5, JS and CSS.  I have been editing the files inside the bundle which has been working fine.

The only thing is, I want to use the developer console, which I can successfully launch.  However, to get the console to update, it requires reloading the window, without restarting the app.

I have been gleaning from various sources methods to do this.  However, when I do, the window closes, triggering both unload and beforeunload events.  The app is still running.  This is the code I came up with:

```<code>const { BrowserWindow, getCurrentWindow, globalShortcut } = require('electron').remote;
getCurrentWindow().reload();

</code>```

EDIT: I have also tried location.href = location.href (which is what I use in NWJS apps) but nothing happens.  I have also tried location.reload() but that also closes the window.

EDIT2: I have also tried the following:

```<code>getCurrentWindow().loadURL(`file://${__dirname}/index.html`);
getCurrentWindow().loadFile("./index.html");
</code>```

Body:
I am trying to extend an existing Macos application which is built on the Electron framework.  The code is written in HTML5, JS and CSS.  I have been editing the files inside the bundle which has been working fine.

The only thing is, I want to use the developer console, which I can successfully launch.  However, to get the console to update, it requires reloading the window, without restarting the app.

I have been gleaning from various sources methods to do this.  However, when I do, the window closes, triggering both unload and beforeunload events.  The app is still running.  This is the code I came up with:

const { BrowserWindow, getCurrentWindow, globalShortcut } = require('electron').remote;
getCurrentWindow().reload();

EDIT: I have also tried location.href = location.href (which is what I use in NWJS apps) but nothing happens.  I have also tried location.reload() but that also closes the window.

EDIT2: I have also tried the following:

getCurrentWindow().loadURL(`file://${__dirname}/index.html`);
getCurrentWindow().loadFile("./index.html");


问:
Parse string in mongodb
Parsing a string in mongodb into alpha and numeric components.

Goal is to set new fields for each document with components of the string.

Desired result:

```<code>{ code: "A1357" }
</code>```

parse to:

```<code>{
    code: 'A1357',
    codeAlpha: 'A',
    codeNum: 1357
}
</code>```

The following parses the code, but sets codeAlpha and codeNum to expressions:

```<code>db.coll.updateMany({},{$set:{"codeAlpha":{$substrCP: ["$code",0,1]},"codeNum":{$toInt:{$substrCP: ["$code",1,4]}}}})
</code>```

result:

```<code>{
  code: 'A1357',
  codeAlpha: ['{$substrCP': ['$code',0,1]}],
  codeNum: [{'$toInt':{'$substrCP': ['$code',1,4]}}]
}
</code>```

How do I $set the actual value?

```<code>{
    code: 'A1357',
    codeAlpha: 'A',
    codeNum: 1357
}
</code>```

Title: Parse string in mongodb

Body:
Parsing a string in mongodb into alpha and numeric components.

Goal is to set new fields for each document with components of the string.

Desired result:

{ code: "A1357" }

parse to:

{
    code: 'A1357',
    codeAlpha: 'A',
    codeNum: 1357
}

The following parses the code, but sets codeAlpha and codeNum to expressions:

db.coll.updateMany({},{$set:{"codeAlpha":{$substrCP: ["$code",0,1]},"codeNum":{$toInt:{$substrCP: ["$code",1,4]}}}})

result:

{
  code: 'A1357',
  codeAlpha: ['{$substrCP': ['$code',0,1]}],
  codeNum: [{'$toInt':{'$substrCP': ['$code',1,4]}}]
}

How do I $set the actual value?

{
    code: 'A1357',
    codeAlpha: 'A',
    codeNum: 1357
}


问:
Make square to follow mouse cursor in python
I'm trying to write code for following rectangle to mouse cursor by python.

I'm using SetPixel function in win32gui.

I'm using win32api because I want to use this entire screen not only one window.

But there are two problems.

It makes many rectangle whenever move mouse.

Rectangle is flashed.

```<code>import keyboard
import mouse
import win32clipboard
import win32api
import win32gui, win32ui
import win32con
from win32api import GetSystemMetrics
import os
import time

filepath = os.path.expanduser('~') + "\Desktop"
print(filepath)

class draw:
    dc = None
    dcObj = None
    hwnd = None

    def __init__(self):
        # self.dcObj = win32ui.CreateDCFromHandle(self.hdc)
        self.hwnd = win32gui.GetDesktopWindow()
        self.hdc = win32gui.GetDC(self.hwnd)

    def rect(self, x, y, w, h, color=False):
        win32gui.InvalidateRect(self.hwnd, (0, 0, GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN), GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)), True)

        color = win32api.RGB(0, 255, 0)
        for i in range(x, x + w):
            win32gui.SetPixel(self.hdc, i, y, color)
            win32gui.SetPixel(self.hdc, i, y + h, color)
        for j in range(y, y + h):
            win32gui.SetPixel(self.hdc, x, j, color)
            win32gui.SetPixel(self.hdc, x + w, j, color)

app = draw()

while True:
    fail = 0
    size = 600

    (x, y) = mouse.get_position()
    app.rect(x, y, size, size)
    print(x, y, size)
</code>```

How can I fix this problem?

I tried to use InvalidateRect to delete duplicated rectangle. But it wan't deleted.
I hope to fix flashed square and delete duplicated square in whole screen not only window

Body:
I'm trying to write code for following rectangle to mouse cursor by python.

I'm using SetPixel function in win32gui.

I'm using win32api because I want to use this entire screen not only one window.

But there are two problems.

It makes many rectangle whenever move mouse.

Rectangle is flashed.

import keyboard
import mouse
import win32clipboard
import win32api
import win32gui, win32ui
import win32con
from win32api import GetSystemMetrics
import os
import time

filepath = os.path.expanduser('~') + "\Desktop"
print(filepath)

class draw:
    dc = None
    dcObj = None
    hwnd = None

    def __init__(self):
        # self.dcObj = win32ui.CreateDCFromHandle(self.hdc)
        self.hwnd = win32gui.GetDesktopWindow()
        self.hdc = win32gui.GetDC(self.hwnd)

    def rect(self, x, y, w, h, color=False):
        win32gui.InvalidateRect(self.hwnd, (0, 0, GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN), GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)), True)

        color = win32api.RGB(0, 255, 0)
        for i in range(x, x + w):
            win32gui.SetPixel(self.hdc, i, y, color)
            win32gui.SetPixel(self.hdc, i, y + h, color)
        for j in range(y, y + h):
            win32gui.SetPixel(self.hdc, x, j, color)
            win32gui.SetPixel(self.hdc, x + w, j, color)

app = draw()

while True:
    fail = 0
    size = 600

    (x, y) = mouse.get_position()
    app.rect(x, y, size, size)
    print(x, y, size)

How can I fix this problem?

I tried to use InvalidateRect to delete duplicated rectangle. But it wan't deleted.
I hope to fix flashed square and delete duplicated square in whole screen not only window


问:
postgres (timescaledb): merge two views more efficiently
Try it out: https://db-fiddle.com/f/4XzRZw5DxHML7bYy1mNMmY/1

DB-dump from 2022-10 and 2022-11: https://easyupload.io/1yh4wj

I query my gas heating device and save the data in a Postgres database. For time series I use timescaledb.

I then aggregate various metrics over a month (heating water vs heating building, active burner time ...) to plot some graphs.

A record looks like this, I added english translations with "--"

```<code>timest               | 2022-12-18 15:49:07+01
temp_warmwasser_ist  | 53.2 -- hot water actual temperature
temp_warmwasser_soll | 54 -- hot water set temperature
temp_vorlauf_ist     | 51.3 -- flow temperature
temp_kessel_ist      | 51.3 -- boiler temperature
temp_abgas           | 40.5 -- exhaust gas temperature
temp_raumsollm1      | 20 -- room temperature
temp_raumsollm2      | 20
brenner_stunden      | 13330.1 -- burner active in cumulative hours
brenner_starts       | 15026 -- amount of burner starts
brenner_status       | 0 -- burner status (1 = on, 0 = off)
alarm_status         | 0 -- alarm
betrieb_2301         | 0 --
betrieb_2323         | 1 --
ventil               | 3 -- which heating circuit is active 1 = warmwater, 3 = building
pump_power           | 0
brenner_power        | 0 -- burner power
</code>```

To aggregate I use these views:

```<code>                               View "public.v_heizung_ww_hz"
 Column |           Type           | Collation | Nullable | Default | Storage | Description
--------+--------------------------+-----------+----------+---------+---------+-------------
 time   | timestamp with time zone |           |          |         | plain   |
 ww     | double precision         |           |          |         | plain   |
 hz     | double precision         |           |          |         | plain   |
View definition:
 SELECT date_trunc('month'::text, heizung.timest) AS "time",
    sum(
        CASE
            WHEN heizung.ventil = 3 THEN heizung.brenner_status::integer
            ELSE 0
        END)::double precision / sum(heizung.brenner_status)::double precision AS ww,
    sum(
        CASE
            WHEN heizung.ventil = 1 THEN heizung.brenner_status::integer
            ELSE 0
        END)::double precision / sum(heizung.brenner_status)::double precision AS hz
   FROM heizung
  GROUP BY (date_trunc('month'::text, heizung.timest));
</code>```

What I am doing here is summing up the time which circuit is heated up to get a ratio of warmwater vs. building heating.

Output:

```<code>          time          |         ww         |         hz
------------------------+--------------------+--------------------
 2020-04-01 00:00:00+02 | 0.0254730713245997 | 0.0941775836972343
 2020-05-01 00:00:00+02 |  0.199101468332238 |  0.800898531667762
</code>```

But I also want to get the actual hour count and gas consumption (0.65 empirically determined):

```<code>                               View "public.v_heizung_monthly"
 Column  |           Type           | Collation | Nullable | Default | Storage | Description
---------+--------------------------+-----------+----------+---------+---------+-------------
 time    | timestamp with time zone |           |          |         | plain   |
 stunden | double precision         |           |          |         | plain   |
 Gas %   | double precision         |           |          |         | plain   |
 Gas l   | double precision         |           |          |         | plain   |
View definition:
 SELECT date_trunc('month'::text, v_heizung_daily."time"::timestamp with time zone) AS "time",
    sum(v_heizung_daily.stunden) AS stunden,
    sum(v_heizung_daily.stunden) * 0.65::double precision / 50::double precision AS "Gas %",
    sum(v_heizung_daily.stunden) * 0.65::double precision AS "Gas l"
   FROM v_heizung_daily
  GROUP BY (date_trunc('month'::text, v_heizung_daily."time"::timestamp with time zone))
  ORDER BY (date_trunc('month'::text, v_heizung_daily."time"::timestamp with time zone));
</code>```

Output:

```<code>          time          |     stunden     |      Gas %       |      Gas l
------------------------+-----------------+------------------+------------------
 2020-04-01 00:00:00+02 |  36.64990234375 | 0.47644873046875 | 23.8224365234375
 2020-05-01 00:00:00+02 | 156.43017578125 | 2.03359228515625 | 101.679614257813
</code>```

v_heizung_daily looks like this:

```<code>                            View "public.v_heizung_daily"
 Column  |       Type       | Collation | Nullable | Default | Storage | Description
---------+------------------+-----------+----------+---------+---------+-------------
 time    | date             |           |          |         | plain   |
 stunden | double precision |           |          |         | plain   |
 starts  | double precision |           |          |         | plain   |
View definition:
 SELECT s.timest::date AS "time",
    s.brenner_stunden::double precision - lag(s.brenner_stunden::double precision, 1) OVER (ORDER BY s.timest) AS stunden,
    s.brenner_starts::double precision - lag(s.brenner_starts::double precision, 1) OVER (ORDER BY s.timest) AS starts
   FROM ( SELECT DISTINCT ON ((heizung.timest::date)) heizung.timest,
            heizung.brenner_stunden,
            heizung.brenner_starts
           FROM heizung
          ORDER BY (heizung.timest::date) DESC, heizung.timest DESC) s;
</code>```

Long story short:
The issue is then when combining those views. I use this join:

```<code>select a.time, stunden, stunden*0.65*7 as "kWh", ww, hz, "Gas %", "Gas l", "Gas l"*ww as "ww_l", "Gas l"*hz as "hz_l" from v_heizung_ww_hz a join v_heizung_monthly b on a.time = b.time;
</code>```

Which takes a long time:

```<code>          time          |     stunden     |       kWh        |         ww         |         hz         |      Gas %       |      Gas l       |       ww_l        |       hz_l
------------------------+-----------------+------------------+--------------------+--------------------+------------------+------------------+-------------------+------------------
 2020-04-01 00:00:00+02 |  36.64990234375 | 166.757055664063 | 0.0254730713245997 | 0.0941775836972343 | 0.47644873046875 | 23.8224365234375 | 0.606830624687273 | 2.24353950955809
Time: 1546.846 ms (00:01.547)
</code>```

So I am wondering if there is a better way to do this 2 queries. I think I have some flaws that makes this operating take this so long. Or should I use materialized views? Thanks for any suggestions.

Body:
Try it out: https://db-fiddle.com/f/4XzRZw5DxHML7bYy1mNMmY/1

DB-dump from 2022-10 and 2022-11: https://easyupload.io/1yh4wj

I query my gas heating device and save the data in a Postgres database. For time series I use timescaledb.

I then aggregate various metrics over a month (heating water vs heating building, active burner time ...) to plot some graphs.

A record looks like this, I added english translations with "--"

timest               | 2022-12-18 15:49:07+01
temp_warmwasser_ist  | 53.2 -- hot water actual temperature
temp_warmwasser_soll | 54 -- hot water set temperature
temp_vorlauf_ist     | 51.3 -- flow temperature
temp_kessel_ist      | 51.3 -- boiler temperature
temp_abgas           | 40.5 -- exhaust gas temperature
temp_raumsollm1      | 20 -- room temperature
temp_raumsollm2      | 20
brenner_stunden      | 13330.1 -- burner active in cumulative hours
brenner_starts       | 15026 -- amount of burner starts
brenner_status       | 0 -- burner status (1 = on, 0 = off)
alarm_status         | 0 -- alarm
betrieb_2301         | 0 --
betrieb_2323         | 1 --
ventil               | 3 -- which heating circuit is active 1 = warmwater, 3 = building
pump_power           | 0
brenner_power        | 0 -- burner power

To aggregate I use these views:

                               View "public.v_heizung_ww_hz"
 Column |           Type           | Collation | Nullable | Default | Storage | Description
--------+--------------------------+-----------+----------+---------+---------+-------------
 time   | timestamp with time zone |           |          |         | plain   |
 ww     | double precision         |           |          |         | plain   |
 hz     | double precision         |           |          |         | plain   |
View definition:
 SELECT date_trunc('month'::text, heizung.timest) AS "time",
    sum(
        CASE
            WHEN heizung.ventil = 3 THEN heizung.brenner_status::integer
            ELSE 0
        END)::double precision / sum(heizung.brenner_status)::double precision AS ww,
    sum(
        CASE
            WHEN heizung.ventil = 1 THEN heizung.brenner_status::integer
            ELSE 0
        END)::double precision / sum(heizung.brenner_status)::double precision AS hz
   FROM heizung
  GROUP BY (date_trunc('month'::text, heizung.timest));

What I am doing here is summing up the time which circuit is heated up to get a ratio of warmwater vs. building heating.

Output:

          time          |         ww         |         hz
------------------------+--------------------+--------------------
 2020-04-01 00:00:00+02 | 0.0254730713245997 | 0.0941775836972343
 2020-05-01 00:00:00+02 |  0.199101468332238 |  0.800898531667762

But I also want to get the actual hour count and gas consumption (0.65 empirically determined):

                               View "public.v_heizung_monthly"
 Column  |           Type           | Collation | Nullable | Default | Storage | Description
---------+--------------------------+-----------+----------+---------+---------+-------------
 time    | timestamp with time zone |           |          |         | plain   |
 stunden | double precision         |           |          |         | plain   |
 Gas %   | double precision         |           |          |         | plain   |
 Gas l   | double precision         |           |          |         | plain   |
View definition:
 SELECT date_trunc('month'::text, v_heizung_daily."time"::timestamp with time zone) AS "time",
    sum(v_heizung_daily.stunden) AS stunden,
    sum(v_heizung_daily.stunden) * 0.65::double precision / 50::double precision AS "Gas %",
    sum(v_heizung_daily.stunden) * 0.65::double precision AS "Gas l"
   FROM v_heizung_daily
  GROUP BY (date_trunc('month'::text, v_heizung_daily."time"::timestamp with time zone))
  ORDER BY (date_trunc('month'::text, v_heizung_daily."time"::timestamp with time zone));

Output:

          time          |     stunden     |      Gas %       |      Gas l
------------------------+-----------------+------------------+------------------
 2020-04-01 00:00:00+02 |  36.64990234375 | 0.47644873046875 | 23.8224365234375
 2020-05-01 00:00:00+02 | 156.43017578125 | 2.03359228515625 | 101.679614257813

v_heizung_daily looks like this:

                            View "public.v_heizung_daily"
 Column  |       Type       | Collation | Nullable | Default | Storage | Description
---------+------------------+-----------+----------+---------+---------+-------------
 time    | date             |           |          |         | plain   |
 stunden | double precision |           |          |         | plain   |
 starts  | double precision |           |          |         | plain   |
View definition:
 SELECT s.timest::date AS "time",
    s.brenner_stunden::double precision - lag(s.brenner_stunden::double precision, 1) OVER (ORDER BY s.timest) AS stunden,
    s.brenner_starts::double precision - lag(s.brenner_starts::double precision, 1) OVER (ORDER BY s.timest) AS starts
   FROM ( SELECT DISTINCT ON ((heizung.timest::date)) heizung.timest,
            heizung.brenner_stunden,
            heizung.brenner_starts
           FROM heizung
          ORDER BY (heizung.timest::date) DESC, heizung.timest DESC) s;

Long story short:
The issue is then when combining those views. I use this join:

select a.time, stunden, stunden*0.65*7 as "kWh", ww, hz, "Gas %", "Gas l", "Gas l"*ww as "ww_l", "Gas l"*hz as "hz_l" from v_heizung_ww_hz a join v_heizung_monthly b on a.time = b.time;

Which takes a long time:

          time          |     stunden     |       kWh        |         ww         |         hz         |      Gas %       |      Gas l       |       ww_l        |       hz_l
------------------------+-----------------+------------------+--------------------+--------------------+------------------+------------------+-------------------+------------------
 2020-04-01 00:00:00+02 |  36.64990234375 | 166.757055664063 | 0.0254730713245997 | 0.0941775836972343 | 0.47644873046875 | 23.8224365234375 | 0.606830624687273 | 2.24353950955809
Time: 1546.846 ms (00:01.547)

So I am wondering if there is a better way to do this 2 queries. I think I have some flaws that makes this operating take this so long. Or should I use materialized views? Thanks for any suggestions.


问:
My own VSCode extension only works in the Extension Development Host
My own VSCode extension is working inside the Extension Development Host but does not work when I open VSCode. I have copied my extension folder - named sasm - in the .vscode/extensions folder.

.vscode/extensions folder

Content of my sasm extension folder

When I open a project folder with some .sasm files, VSCode keeps the 'Plain text' mode for these files - and hence no keywords are colored - even though the Extension Development Host manages to do it.

Extension works in the Extension Dev. Host

Extension does not work/is not loaded in a "regular" launch of VSCode


问:
PHP 8 Compatibility - Deprecated: Required parameter $show_name follows optional parameter $grid in
Good Afternoon,

Clearing up some PHP errors to make our site PHP 8 compatible and have been stuck with this one.

The error message Deprecated:

Required parameter $show_name follows optional parameter $grid in

relates to the following line of code:

```<code>function wpsc_parent_category_image($show_thumbnails , $category_image , $width, $height, $grid=false, $show_name){

    if(!$show_thumbnails) return;

    if($category_image == WPSC_CATEGORY_URL){
        if(!$show_name) return;
    ?>
    <span class='wpsc_category_image item_no_image ' style='width:<?php echo $width; ?>px; height: <?php echo $height; ?>px;'>
        <span class='link_substitute' >
            <span><?php _e('N/A', 'wp-e-commerce'); ?></span>
        </span>
    </span>
    <?php
    }else{
        ?><img src='<?php echo $category_image; ?>' width='<?php echo $width; ?>' height='<?php echo $height; ?>' /><?php
    }
}
</code>```

Would anyone have any suggestions on tweaking the above code, so that it is compatible with PHP 8?

Any help would be really appreciated!

Kind Regards,

Andy

Body:
Good Afternoon,

Clearing up some PHP errors to make our site PHP 8 compatible and have been stuck with this one.

The error message Deprecated:

Required parameter $show_name follows optional parameter $grid in

relates to the following line of code:

function wpsc_parent_category_image($show_thumbnails , $category_image , $width, $height, $grid=false, $show_name){

    if(!$show_thumbnails) return;

    if($category_image == WPSC_CATEGORY_URL){
        if(!$show_name) return;
    ?>
    <span class='wpsc_category_image item_no_image ' style='width:<?php echo $width; ?>px; height: <?php echo $height; ?>px;'>

            <?php _e('N/A', 'wp-e-commerce'); ?>

    <?php
    }else{
        ?><img src='<?php echo $category_image; ?>' width='<?php echo $width; ?>' height='<?php echo $height; ?>' /><?php
    }
}

Would anyone have any suggestions on tweaking the above code, so that it is compatible with PHP 8?

Any help would be really appreciated!

Kind Regards,

Andy


问:
EditText.getText() returns "1" instead of the entered text
I'm new to mobile development and I'm building a To-Do mobile application, I created a BottomSheetDialogFragment for entering new task.
This is the code of the dialog class:

public class AddNewTask extends BottomSheetDialogFragment {
    public static final String TAG = "ActionBottomDialog" ;
    private EditText newTaskText ;
    private Button newTaskButton ;
    private DatabaseHandler db ;

    public static AddNewTask newInstance(){
        return new AddNewTask();
    }

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.DialogStyle);

    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.new_task, container, false);
        getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        return view ;
    }

    public void onViewCreated(View view, Bundle savedInstanceState){
        super.onViewCreated(view, savedInstanceState);
        newTaskText = view.findViewById(R.id.newTask);
        newTaskButton = view.findViewById(R.id.newTaskButton);

        db = new DatabaseHandler(getActivity());
        db.openDatabase();
        boolean isUpdate = false ;
        final Bundle bundle = getArguments();
        if(bundle != null) {
            isUpdate = true;
            String task = bundle.getString("task");
            newTaskText.setText(task);
            if (task.length() > 0)
                newTaskButton.setTextColor(ContextCompat.getColor(getContext(), R.color.primary));
        }
                newTaskText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                        if(s.toString().equals("")){
                            newTaskButton.setEnabled(false);
                            newTaskButton.setTextColor(Color.GRAY);
                        }
                        else{
                            newTaskButton.setEnabled(true);
                            newTaskButton.setTextColor(ContextCompat.getColor(getContext(), R.color.primary));
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {

                    }
                });
                final boolean finalIsUpdate = isUpdate;
                newTaskButton.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v){
                        String text = newTaskText.getText().toString();
                        Log.d("INFO", ""+text);
                        if(finalIsUpdate){
                            db.updateTask(bundle.getInt("id"),text);
                        }
                        else{
                            Task task = new Task();
                            task.setTask(text);

                            task.setStatus(false);
                            db.insertTask(task);
                        }
                        dismiss();

                    }
                });
            }

            @Override
           public void onDismiss(@NonNull DialogInterface dialog){
                Activity activity = getActivity();
                if(activity instanceof DialogCloseListener)
                    ((DialogCloseListener)activity).handleDialogClose(dialog);

            }
        }
```
<p>the new_task layout:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
    <EditText
            android:id="@+id/newTask"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:hint="New task"
            android:textSize="20dp"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
    />
    <Button
            android:id="@+id/newTaskButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/newTask"
            android:layout_alignParentEnd="true"
            android:textSize="20dp"
            android:text="Add"
            android:textAllCaps="false"
            android:background="@android:color/transparent"
            android:textColor="@android:color/darker_gray"
    />
</RelativeLayout>
</code>```

and this is the code of MainActivity:

public class MainActivity extends AppCompatActivity implements DialogCloseListener{
    private RecyclerView taskRecyclerView ;
    private ToDoAdapter taskAdapter ;
    private List<Task> taskList ;
    private DatabaseHandler db;
    private FloatingActionButton addTask ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Objects.requireNonNull(getSupportActionBar()).setTitle("To Do");
        db = new DatabaseHandler(this);
        db.openDatabase();
        taskRecyclerView = findViewById(R.id.taskList);
        taskRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        taskAdapter = new ToDoAdapter(db,this);
        taskRecyclerView.setAdapter(taskAdapter);

        addTask = findViewById(R.id.button);

        taskList = new ArrayList<Task>();
        Task task = new Task();
        taskList = db.getAllTasks();
        Collections.reverse(taskList);
        taskAdapter.setTasks(taskList);

        addTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddNewTask.newInstance().show(getSupportFragmentManager(), AddNewTask.TAG);
            }
        });
    }

    @Override
    public void handleDialogClose(DialogInterface dialog){
        taskList = db.getAllTasks();
        Collections.reverse(taskList);
        taskAdapter.setTasks(taskList);
        taskAdapter.notifyDataSetChanged();
    }
}
```

The problem is when I run it, it give me "1" in RecyclerView items. I added Log.d so that I can see the variable before it's stored in the DB, and even in the console it shows me "1", which means that the problem is in the EditText itself. How can I fix it?

Body:
I'm new to mobile development and I'm building a To-Do mobile application, I created a BottomSheetDialogFragment for entering new task.
This is the code of the dialog class:

public class AddNewTask extends BottomSheetDialogFragment {
    public static final String TAG = "ActionBottomDialog" ;
    private EditText newTaskText ;
    private Button newTaskButton ;
    private DatabaseHandler db ;

    public static AddNewTask newInstance(){
        return new AddNewTask();
    }

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.DialogStyle);

    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.new_task, container, false);
        getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        return view ;
    }

    public void onViewCreated(View view, Bundle savedInstanceState){
        super.onViewCreated(view, savedInstanceState);
        newTaskText = view.findViewById(R.id.newTask);
        newTaskButton = view.findViewById(R.id.newTaskButton);

        db = new DatabaseHandler(getActivity());
        db.openDatabase();
        boolean isUpdate = false ;
        final Bundle bundle = getArguments();
        if(bundle != null) {
            isUpdate = true;
            String task = bundle.getString("task");
            newTaskText.setText(task);
            if (task.length() > 0)
                newTaskButton.setTextColor(ContextCompat.getColor(getContext(), R.color.primary));
        }
                newTaskText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                        if(s.toString().equals("")){
                            newTaskButton.setEnabled(false);
                            newTaskButton.setTextColor(Color.GRAY);
                        }
                        else{
                            newTaskButton.setEnabled(true);
                            newTaskButton.setTextColor(ContextCompat.getColor(getContext(), R.color.primary));
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {

                    }
                });
                final boolean finalIsUpdate = isUpdate;
                newTaskButton.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v){
                        String text = newTaskText.getText().toString();
                        Log.d("INFO", ""+text);
                        if(finalIsUpdate){
                            db.updateTask(bundle.getInt("id"),text);
                        }
                        else{
                            Task task = new Task();
                            task.setTask(text);

                            task.setStatus(false);
                            db.insertTask(task);
                        }
                        dismiss();

                    }
                });
            }

            @Override
           public void onDismiss(@NonNull DialogInterface dialog){
                Activity activity = getActivity();
                if(activity instanceof DialogCloseListener)
                    ((DialogCloseListener)activity).handleDialogClose(dialog);

            }
        }

the new_task layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
    <EditText
            android:id="@+id/newTask"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:hint="New task"
            android:textSize="20dp"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
    />
    <Button
            android:id="@+id/newTaskButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/newTask"
            android:layout_alignParentEnd="true"
            android:textSize="20dp"
            android:text="Add"
            android:textAllCaps="false"
            android:background="@android:color/transparent"
            android:textColor="@android:color/darker_gray"
    />
</RelativeLayout>

and this is the code of MainActivity:

public class MainActivity extends AppCompatActivity implements DialogCloseListener{
    private RecyclerView taskRecyclerView ;
    private ToDoAdapter taskAdapter ;
    private List<Task> taskList ;
    private DatabaseHandler db;
    private FloatingActionButton addTask ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Objects.requireNonNull(getSupportActionBar()).setTitle("To Do");
        db = new DatabaseHandler(this);
        db.openDatabase();
        taskRecyclerView = findViewById(R.id.taskList);
        taskRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        taskAdapter = new ToDoAdapter(db,this);
        taskRecyclerView.setAdapter(taskAdapter);

        addTask = findViewById(R.id.button);

        taskList = new ArrayList<Task>();
        Task task = new Task();
        taskList = db.getAllTasks();
        Collections.reverse(taskList);
        taskAdapter.setTasks(taskList);

        addTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddNewTask.newInstance().show(getSupportFragmentManager(), AddNewTask.TAG);
            }
        });
    }

    @Override
    public void handleDialogClose(DialogInterface dialog){
        taskList = db.getAllTasks();
        Collections.reverse(taskList);
        taskAdapter.setTasks(taskList);
        taskAdapter.notifyDataSetChanged();
    }
}

The problem is when I run it, it give me "1" in RecyclerView items. I added Log.d so that I can see the variable before it's stored in the DB, and even in the console it shows me "1", which means that the problem is in the EditText itself. How can I fix it?