问:
fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [map type; class java.util.HashMap, [simple
```<code>**POM dependency**
    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.4.13</version>
            <relativePath />
        </parent>
    <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>2020.0.2</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>

    <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-bootstrap</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-config</artifactId>
                <version>3.0.1</version>
            </dependency>
Jars used by call hierarchy:
    org.springframework.boot:spring-boot-starter-web:jar:2.4.13:compile
     org.springframework.boot:spring-boot-starter-json:jar:2.4.13:compile
     com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.11.4:compile
     com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.11.4:compile
     com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.11.4:compile
    org.springframework.boot:spring-boot-starter-tomcat:jar:2.4.13:compile

</code>```

Error log:
==================================================   "org.springframework.boot.SpringApplication","methodName":"reportFailure","fileName":"SpringApplication.java","lineNumber":860},"msg":"Application run failed","throwable":"java.lang.IllegalStateException: Failed to execute ApplicationRunner\n\tat org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:802)\n\tat org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:789)\n\tat org.springframework.boot.SpringApplication.run(SpringApplication.java:346)\n\tat org.springframework.boot.SpringApplication.run(SpringApplication.java:1329)\n\tat org.springframework.boot.SpringApplication.run(SpringApplication.java:1318)\n\tat
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:498)\n\tat org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49)\n\tat org.springframework.boot.loader.Launcher.launch(Launcher.java:108)\n\tat org.springframework.boot.loader.Launcher.launch(Launcher.java:58)\n\tat org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88)\nCaused by: java.lang.IllegalArgumentException: Unable to deserialize the execution context\n\tat org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:328)\n\tat org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:312)\n\tat org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:94)\n\tat org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:61)\n\tat org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:723)\n\tat org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:651)\n\tat org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:713)\n\tat org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:744)\n\tat org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:757)\n\tat org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:815)\n\tat org.springframework.batch.core.repository.dao.JdbcExecutionContextDao.getExecutionContext(JdbcExecutionContextDao.java:114)\n\tat org.springframework.batch.core.explore.support.SimpleJobExplorer.getJobExecutionDependencies(SimpleJobExplorer.java:239)\n\tat org.springframework.batch.core.explore.support.SimpleJobExplorer.getLastJobExecution(SimpleJobExplorer.java:104)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:498)\n\tat org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)\n\tat org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:128)\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\n\tat org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)\n\tat com.sun.proxy.$Proxy87.getLastJobExecution(Unknown Source)\n\tat org.springframework.batch.core.JobParametersBuilder.getNextJobParameters(JobParametersBuilder.java:265)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.getNextJobParameters(JobLauncherApplicationRunner.java:213)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.execute(JobLauncherApplicationRunner.java:198)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.executeLocalJobs(JobLauncherApplicationRunner.java:173)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.launchJobFromProperties(JobLauncherApplicationRunner.java:160)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.run(JobLauncherApplicationRunner.java:155)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.run(JobLauncherApplicationRunner.java:150)\n\tat org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:799)\n\t... 13 more\nCaused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [map type; class java.util.HashMap, [simple type, class java.lang.String] -> [simple type, class java.lang.Object]]: missing type id property '@class'\n at [Source: (ByteArrayInputStream); line: 1, column: 46]\n\tat com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43)\n\tat com.fasterxml.jackson.databind.DeserializationContext.missingTypeIdException(DeserializationContext.java:1794)\n\tat com.fasterxml.jackson.databind.DeserializationContext.handleMissingTypeId(DeserializationContext.java:1323)\n\tat com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._handleMissingTypeId(TypeDeserializerBase.java:302)\n\tat com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedUsingDefaultImpl(AsPropertyTypeDeserializer.java:166)\n\tat com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:107)\n\tat com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserializeWithType(MapDeserializer.java:413)\n\tat com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:68)\n\tat com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526)\n\tat com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3513)\n\tat org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer.deserialize(Jackson2ExecutionContextStringSerializer.java:133)\n\tat org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer.deserialize(Jackson2ExecutionContextStringSerializer.java:104)\n\tat org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:325)\n\t... 44 more\n"}

Body:
**POM dependency**
    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.4.13</version>
            <relativePath />
        </parent>
    <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>2020.0.2</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>

    <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-bootstrap</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-config</artifactId>
                <version>3.0.1</version>
            </dependency>
Jars used by call hierarchy:
    org.springframework.boot:spring-boot-starter-web:jar:2.4.13:compile
     org.springframework.boot:spring-boot-starter-json:jar:2.4.13:compile
     com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.11.4:compile
     com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.11.4:compile
     com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.11.4:compile
    org.springframework.boot:spring-boot-starter-tomcat:jar:2.4.13:compile

Error log:
==================================================   "org.springframework.boot.SpringApplication","methodName":"reportFailure","fileName":"SpringApplication.java","lineNumber":860},"msg":"Application run failed","throwable":"java.lang.IllegalStateException: Failed to execute ApplicationRunner\n\tat org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:802)\n\tat org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:789)\n\tat org.springframework.boot.SpringApplication.run(SpringApplication.java:346)\n\tat org.springframework.boot.SpringApplication.run(SpringApplication.java:1329)\n\tat org.springframework.boot.SpringApplication.run(SpringApplication.java:1318)\n\tat
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:498)\n\tat org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49)\n\tat org.springframework.boot.loader.Launcher.launch(Launcher.java:108)\n\tat org.springframework.boot.loader.Launcher.launch(Launcher.java:58)\n\tat org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88)\nCaused by: java.lang.IllegalArgumentException: Unable to deserialize the execution context\n\tat org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:328)\n\tat org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:312)\n\tat org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:94)\n\tat org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:61)\n\tat org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:723)\n\tat org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:651)\n\tat org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:713)\n\tat org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:744)\n\tat org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:757)\n\tat org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:815)\n\tat org.springframework.batch.core.repository.dao.JdbcExecutionContextDao.getExecutionContext(JdbcExecutionContextDao.java:114)\n\tat org.springframework.batch.core.explore.support.SimpleJobExplorer.getJobExecutionDependencies(SimpleJobExplorer.java:239)\n\tat org.springframework.batch.core.explore.support.SimpleJobExplorer.getLastJobExecution(SimpleJobExplorer.java:104)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:498)\n\tat org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)\n\tat org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:128)\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\n\tat org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)\n\tat com.sun.proxy.$Proxy87.getLastJobExecution(Unknown Source)\n\tat org.springframework.batch.core.JobParametersBuilder.getNextJobParameters(JobParametersBuilder.java:265)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.getNextJobParameters(JobLauncherApplicationRunner.java:213)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.execute(JobLauncherApplicationRunner.java:198)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.executeLocalJobs(JobLauncherApplicationRunner.java:173)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.launchJobFromProperties(JobLauncherApplicationRunner.java:160)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.run(JobLauncherApplicationRunner.java:155)\n\tat org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.run(JobLauncherApplicationRunner.java:150)\n\tat org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:799)\n\t... 13 more\nCaused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [map type; class java.util.HashMap, [simple type, class java.lang.String] -> [simple type, class java.lang.Object]]: missing type id property '@class'\n at [Source: (ByteArrayInputStream); line: 1, column: 46]\n\tat com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43)\n\tat com.fasterxml.jackson.databind.DeserializationContext.missingTypeIdException(DeserializationContext.java:1794)\n\tat com.fasterxml.jackson.databind.DeserializationContext.handleMissingTypeId(DeserializationContext.java:1323)\n\tat com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._handleMissingTypeId(TypeDeserializerBase.java:302)\n\tat com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedUsingDefaultImpl(AsPropertyTypeDeserializer.java:166)\n\tat com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:107)\n\tat com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserializeWithType(MapDeserializer.java:413)\n\tat com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:68)\n\tat com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526)\n\tat com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3513)\n\tat org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer.deserialize(Jackson2ExecutionContextStringSerializer.java:133)\n\tat org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer.deserialize(Jackson2ExecutionContextStringSerializer.java:104)\n\tat org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:325)\n\t... 44 more\n"}


来源: stackexchange

问:
Pass multiple custom variables to other jobs
Trying to effectively pass multiple custom variables (about 10 of them) to other pipeline jobs through dotenv, by not creating 10x "- echo Var=Var". The custom variables have different values depending if the Environment is Dev,Test,Prod etc (about 8 different environments) as well.

From my understanding I can use child jobs to differentiate between environments, and use extends functionality as a config file to create all the variables for the different environments. Problem is that it's very cumbersome logic to use the bellow code when I’m going to add all the variables for all the environments.

Example code:

```<code>#Seperate file
.environment:Test:
  variables:
    CustomVar_ExtendServerFQDN: 'TestHost'
    CustomVar_Datacenter: 'TestDatacenter'

.environment:Dev:
  variables:
    CustomVar_ExtendServerFQDN: 'DevHost'
    CustomVar_Datacenter: 'DevDatacenter'

#Prep file
EnvironmentPrep:Dev:
  stage: build
  extends: .environment:Dev
  script:
    - echo "ServerFQDN=$CustomVar_ServerFQDN" >> build.env
    - echo "Datacenter=$CustomVar_Datacenter" >> build.env
    - echo "GitLab CI/CD | Print all environment variables"
    - env
  artifacts:
    reports:
      dotenv: build.env
  rules:
  - if: '$Environment=="Dev"'

EnvironmentPrep:Test:
  stage: build
  extends: .environment:Test
  script:
    - echo "ServerFQDN=$CustomVar_ServerFQDN" >> build.env
    - echo "Datacenter=$CustomVar_Datacenter" >> build.env
    - echo "GitLab CI/CD | Print all environment variables"
    - env
  artifacts:
    reports:
      dotenv: build.env
  rules:
   - if: '$Environment=="Test"'

#Main job file
MainJob:
  stage: deploy
  script:
    - echo "Main Environment variable is [$Environment] [$Server]"
    - echo "GitLab CI/CD | Print all environment variables"
    - env

variables:
  Environment: 'Test'
</code>```

With this logic it means 10x "-echo var=$var", in each environment job, total of 80 "-echo var=$var" for the merged YAML.

Is there a more effective logic to make sure the MainJob gets the custom variables retrieved from a build stage job?

I'm looking for something like the bellow example, but I'm not sure how to create the logic or filter on only the custom variables "CustomVar_*" for variable $scriptBlock:

```<code>#Seperate file
.environment:Test:
  variables:
    CustomVar_ExtendServerFQDN: 'TestHost'
    CustomVar_Datacenter: 'TestDatacenter'

.environment:Dev:
  variables:
    CustomVar_ExtendServerFQDN: 'DevHost'
    CustomVar_Datacenter: 'DevDatacenter'

EnvironmentPrep:Dev:
  stage: build
  extends: .environment:Dev
  script:
    - $scriptBlock >> build.env
  artifacts:
    reports:
      dotenv: build.env
  rules:
  - if: '$Environment=="Dev"'

EnvironmentPrep:Test:
  stage: build
  extends: .environment:Test
  script:
    - $scriptBlock >> build.env
  artifacts:
    reports:
      dotenv: build.env
  rules:
   - if: '$Environment=="Test"'

MainJob:
  stage: deploy
  script:
    - echo "Main Environment variable is [$Environment] [$Server]"
    - echo "GitLab CI/CD | Print all environment variables"
    - env

variables:
  Environment: 'Test'
  scriptBlock: <SOME FILTER LOGIC ON "CustomVar_*">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Trying to effectively pass multiple custom variables (about 10 of them) to other pipeline jobs through dotenv, by not creating 10x "- echo Var=Var". The custom variables have different values depending if the Environment is Dev,Test,Prod etc (about 8 different environments) as well.

From my understanding I can use child jobs to differentiate between environments, and use extends functionality as a config file to create all the variables for the different environments. Problem is that it's very cumbersome logic to use the bellow code when I’m going to add all the variables for all the environments.

Example code:

#Seperate file
.environment:Test:
  variables:
    CustomVar_ExtendServerFQDN: 'TestHost'
    CustomVar_Datacenter: 'TestDatacenter'

.environment:Dev:
  variables:
    CustomVar_ExtendServerFQDN: 'DevHost'
    CustomVar_Datacenter: 'DevDatacenter'

#Prep file
EnvironmentPrep:Dev:
  stage: build
  extends: .environment:Dev
  script:
    - echo "ServerFQDN=$CustomVar_ServerFQDN" >> build.env
    - echo "Datacenter=$CustomVar_Datacenter" >> build.env
    - echo "GitLab CI/CD | Print all environment variables"
    - env
  artifacts:
    reports:
      dotenv: build.env
  rules:
  - if: '$Environment=="Dev"'

EnvironmentPrep:Test:
  stage: build
  extends: .environment:Test
  script:
    - echo "ServerFQDN=$CustomVar_ServerFQDN" >> build.env
    - echo "Datacenter=$CustomVar_Datacenter" >> build.env
    - echo "GitLab CI/CD | Print all environment variables"
    - env
  artifacts:
    reports:
      dotenv: build.env
  rules:
   - if: '$Environment=="Test"'

#Main job file
MainJob:
  stage: deploy
  script:
    - echo "Main Environment variable is [$Environment] [$Server]"
    - echo "GitLab CI/CD | Print all environment variables"
    - env

variables:
  Environment: 'Test'

With this logic it means 10x "-echo var=$var", in each environment job, total of 80 "-echo var=$var" for the merged YAML.

Is there a more effective logic to make sure the MainJob gets the custom variables retrieved from a build stage job?

I'm looking for something like the bellow example, but I'm not sure how to create the logic or filter on only the custom variables "CustomVar_*" for variable $scriptBlock:

#Seperate file
.environment:Test:
  variables:
    CustomVar_ExtendServerFQDN: 'TestHost'
    CustomVar_Datacenter: 'TestDatacenter'

.environment:Dev:
  variables:
    CustomVar_ExtendServerFQDN: 'DevHost'
    CustomVar_Datacenter: 'DevDatacenter'

EnvironmentPrep:Dev:
  stage: build
  extends: .environment:Dev
  script:
    - $scriptBlock >> build.env
  artifacts:
    reports:
      dotenv: build.env
  rules:
  - if: '$Environment=="Dev"'

EnvironmentPrep:Test:
  stage: build
  extends: .environment:Test
  script:
    - $scriptBlock >> build.env
  artifacts:
    reports:
      dotenv: build.env
  rules:
   - if: '$Environment=="Test"'

MainJob:
  stage: deploy
  script:
    - echo "Main Environment variable is [$Environment] [$Server]"
    - echo "GitLab CI/CD | Print all environment variables"
    - env

variables:
  Environment: 'Test'
  scriptBlock: <SOME FILTER LOGIC ON "CustomVar_*">


问:
Update a model with test data to make new forecasts after training it on training data
I would like to understand if the procedure I'm following is standard or if I'm making some mistake.
I have a time series of 48 values (one value per month from 2018 to 2021), stored in the data frame df:

```<code>             Amount
2018-01      125.6
...          ...
2020-12      145.2
2021-01      148.4
...          ...
2021-12      198.8
</code>```

I would like to create a model that can predict the quantity for the months I want.

In short, I take the first three years (36 months) and use this data to train my model, and then test it on the last year (2021), as follows:

```<code>df_train = df[:36]
df_test = df[36:]

arima = pm.auto_arima(df_train, error_action='ignore', trace=True,
                      suppress_warnings=True, maxiter=50,
                      seasonal=True, m=12,
                      random_state=1)

# Best model: ARIMA(1,1,1)(0,1,0)[12]

predictions, conf_int = arima.predict(n_periods=12, return_conf_int=True)

df_predictions = pd.DataFrame(predictions, index=df_test.index)
df_predictions.columns = ['Predicted amount']
</code>```

Then, I use:

```<code>r2_score(df_test['Amount'], df_predictions['Predicted amount'])
</code>```

getting about 0.92, so everything seems to be fine. Is this correct up to here?

Finally, I want to forecast 2022 amounts, where I have no control data.
To do this, I update the model and repeat the process from before:

```<code>arima.update(df_test)
df_forecasts = pd.DataFrame(arima.predict(n_periods=12), index=pd.date_range(start='2022-01-01', end='2022-12-01', freq='MS'))
df_forecasts.columns = ['Forecasted amount']
</code>```

I'm more unsure about this last part, is that correct?

I have made a very concise summary of the procedure, but I am interested in understanding if the path I have followed is standard and correct. Thanks to anyone who can answer me.

Body:
I would like to understand if the procedure I'm following is standard or if I'm making some mistake.
I have a time series of 48 values (one value per month from 2018 to 2021), stored in the data frame df:

             Amount
2018-01      125.6
...          ...
2020-12      145.2
2021-01      148.4
...          ...
2021-12      198.8

I would like to create a model that can predict the quantity for the months I want.

In short, I take the first three years (36 months) and use this data to train my model, and then test it on the last year (2021), as follows:

df_train = df[:36]
df_test = df[36:]

arima = pm.auto_arima(df_train, error_action='ignore', trace=True,
                      suppress_warnings=True, maxiter=50,
                      seasonal=True, m=12,
                      random_state=1)

# Best model: ARIMA(1,1,1)(0,1,0)[12]

predictions, conf_int = arima.predict(n_periods=12, return_conf_int=True)

df_predictions = pd.DataFrame(predictions, index=df_test.index)
df_predictions.columns = ['Predicted amount']

Then, I use:

r2_score(df_test['Amount'], df_predictions['Predicted amount'])

getting about 0.92, so everything seems to be fine. Is this correct up to here?

Finally, I want to forecast 2022 amounts, where I have no control data.
To do this, I update the model and repeat the process from before:

arima.update(df_test)
df_forecasts = pd.DataFrame(arima.predict(n_periods=12), index=pd.date_range(start='2022-01-01', end='2022-12-01', freq='MS'))
df_forecasts.columns = ['Forecasted amount']

I'm more unsure about this last part, is that correct?

I have made a very concise summary of the procedure, but I am interested in understanding if the path I have followed is standard and correct. Thanks to anyone who can answer me.


问:
Map view problems
struct SchoolsMap: View {

```<code>@EnvironmentObject private var newMap : SchoolModel

var share = SchoolModel().schools

@State private var latitudinal = 0.0
@State private var longitude = 0.0

let pin = MKPointAnnotation()

@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D( latitude: 40.503851973654783, longitude: -74.450847996722231), span: MKCoordinateSpan (latitudeDelta: 0.9, longitudeDelta: 0.9))

var body: some View {
    NavigationView{
        ZStack{

            Map(coordinateRegion: $region, annotationItems: share){ location in

                MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: 40.503851973654, longitude: -74.45084799672)) {
                    VStack{
                        NavigationLink{
                            SchoolsDetailView(data: location)
                        } label: {
                            Text(location.properties.name!)
                                .bold()
                            Circle()
                                .stroke(.red)
                                .frame(width: 44, height: 44)
                        }

                    }
                }
            }

        }
        .ignoresSafeArea()
    }
}
</code>```

}

My map view doesn't show up with the annotations. The region updates whenever I change it, but the map doesn't show any of my annotations. Anyone know why?

Title: Map view problems

Body:
struct SchoolsMap: View {

@EnvironmentObject private var newMap : SchoolModel

var share = SchoolModel().schools

@State private var latitudinal = 0.0
@State private var longitude = 0.0

let pin = MKPointAnnotation()

@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D( latitude: 40.503851973654783, longitude: -74.450847996722231), span: MKCoordinateSpan (latitudeDelta: 0.9, longitudeDelta: 0.9))

var body: some View {
    NavigationView{
        ZStack{

            Map(coordinateRegion: $region, annotationItems: share){ location in

                MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: 40.503851973654, longitude: -74.45084799672)) {
                    VStack{
                        NavigationLink{
                            SchoolsDetailView(data: location)
                        } label: {
                            Text(location.properties.name!)
                                .bold()
                            Circle()
                                .stroke(.red)
                                .frame(width: 44, height: 44)
                        }

                    }
                }
            }

        }
        .ignoresSafeArea()
    }
}

}

My map view doesn't show up with the annotations. The region updates whenever I change it, but the map doesn't show any of my annotations. Anyone know why?


问:
How to securely limit access to Node fs in Electron?
I know it's recommended to use fs (filesystem module) only from the main process - but that's only half the battle, because if the code outside of main is determining what files are to be deleted, then the main process is still just receiving a path to a file to delete - which could be hijacked by a malicious action via something like window.api.filesystem.deleteFile(somePath)

So I considered to hardcode allowed/disallowed directories, but that's not particularly great either, because as soon as a user actually has a legitimate purpose to be reading/writing/deleting outside of the prescribed directory, you're right back in the same predicament of an attacker potentially being able to access their entire filesystem.

But the code can't all run in main without a thousand hour re-write of everything - nor does it seem advisable as blocking the main thread for even a moment freezes the app, its windows, its context menus, etc, for that moment.

The Electron security docs leave an enormous amount to be desired in this regard. What approaches are available to limit access by a potential attacker?

There's a recommendation to "validate the sender of all IPC messages," but that doesn't really seem to resolve the issue, because the privileged preload script APIs are available globally via window.api..., so an attacker could theoretically send a malicious command from a trusted window.

Otherwise, the security docs seem to entirely neglect this subject.


问:
How can I send a data image url to discord as an image file?
how can I send a data image url to discord as an image file?
I have tried this

import requests
import base64

# I hid the webhook so nobody trolls me and deletes the webhook
WEBHOOK_URL = "https://discord.com/api/webhooks/10304540869963366XXX/XXXXXXXXXXXXXXbiAhIF68Yt-yGBsSKlcKUsDvQdJ"

# Read the image file and encode it as a base64 string
with open("image.jpg", "rb") as image_file:
    image_data = image_file.read()
    image_data_base64 = base64.b64encode(image_data).decode("utf-8")

# Set the content type to "application/json"
headers = {"Content-Type": "application/json"}

# Set the payload of the request to a JSON object containing the base64-encoded image data
payload = {
    "username": "My Bot",
    "avatar_url": "https://cdn.discordapp.com/attachments/434487340535382018/1053728327036305418/Screen_Shot_2022-12-17_at_12.40.07_PM.png",
    "content": f"data:image/jpeg;base64,{image_data_base64}",
}

# Make the POST request to the Discord webhook
response = requests.post(WEBHOOK_URL, headers=headers, json=payload)

# Check the status code of the response to ensure the request was successful
if response.status_code == 200:
    print("Image sent successfully")
else:
    print(f"Error sending image: {response.status_code}")
```

but I get Error sending image: 400 (bad request)
I got no idea what I could try, I have searched for couple hours but couldn't find a solution, I don't want to save the data url to hard disk then upload it, I am trying not to use the hard disk, only memory

Body:
how can I send a data image url to discord as an image file?
I have tried this

import requests
import base64

# I hid the webhook so nobody trolls me and deletes the webhook
WEBHOOK_URL = "https://discord.com/api/webhooks/10304540869963366XXX/XXXXXXXXXXXXXXbiAhIF68Yt-yGBsSKlcKUsDvQdJ"

# Read the image file and encode it as a base64 string
with open("image.jpg", "rb") as image_file:
    image_data = image_file.read()
    image_data_base64 = base64.b64encode(image_data).decode("utf-8")

# Set the content type to "application/json"
headers = {"Content-Type": "application/json"}

# Set the payload of the request to a JSON object containing the base64-encoded image data
payload = {
    "username": "My Bot",
    "avatar_url": "https://cdn.discordapp.com/attachments/434487340535382018/1053728327036305418/Screen_Shot_2022-12-17_at_12.40.07_PM.png",
    "content": f"data:image/jpeg;base64,{image_data_base64}",
}

# Make the POST request to the Discord webhook
response = requests.post(WEBHOOK_URL, headers=headers, json=payload)

# Check the status code of the response to ensure the request was successful
if response.status_code == 200:
    print("Image sent successfully")
else:
    print(f"Error sending image: {response.status_code}")

but I get Error sending image: 400 (bad request)
I got no idea what I could try, I have searched for couple hours but couldn't find a solution, I don't want to save the data url to hard disk then upload it, I am trying not to use the hard disk, only memory


问:
predicting time series: my python code prints out a (very long) list rather than a (small) array
I am learning neural network modeling and its uses in time series prediction.

First, thank you for reading this post and for your help :)

On this page there are various NN models (LSTM, CNN etc.) for predicting "traffic volume":

https://michael-fuchs-python.netlify.app/2020/11/01/time-series-analysis-neural-networks-for-forecasting-univariate-variables/#train-validation-split

I got inspired and decided to use/shorten/adapt the code in there for a problem of my own: predicting the bitcoin price.

I have the bitcoin daily prices starting 1.1.2017

in total 2024 daily prices

I use the first 85% of the data for the training data, and the rest as the validation (except the last 10 observation, which I would like to use as test data to see how good my model is)

I would like to use a Feedforward model

My goal is merely having a code that runs.

I have managed so far to have most of my code run. However, I get a strange format for my test forecast results: It should be simply an array of 10 numbers (i.e. predicted prices corresponding to the 10 day at the end of my data). To my surprise what is printed out is a long list of numbers. I need help to find out what changes I need to make to make to the code to make it run.

Thank you for helping me :)

The code is pasted down there, followed by the error:

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing #import MinMaxScaler
from sklearn import metrics #import mean_squared_error
import seaborn as sns
sns.set()

import tensorflow as tf
from tensorflow import keras
from keras.layers import Input, Dense, Flatten
from keras.optimizers import Adam
from keras.models import Sequential
from keras.callbacks import EarlyStopping
tf.__version__

df = pd.read_csv('/content/BTC-USD.csv')

def mean_absolute_percentage_error_func(y_true, y_pred):

    y_true, y_pred = np.array(y_true), np.array(y_pred)
    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100

def timeseries_evaluation_metrics_func(y_true, y_pred):

    print('Evaluation metric results: ')
    print(f'MSE is : {metrics.mean_squared_error(y_true, y_pred)}')
    print(f'MAE is : {metrics.mean_absolute_error(y_true, y_pred)}')
    print(f'RMSE is : {np.sqrt(metrics.mean_squared_error(y_true, y_pred))}')
    print(f'MAPE is : {mean_absolute_percentage_error_func(y_true, y_pred)}')
    print(f'R2 is : {metrics.r2_score(y_true, y_pred)}',end='\n\n')

def univariate_data_prep_func(dataset, start, end, window, horizon):

    X = []
    y = []

    start = start + window
    if end is None:
        end = len(dataset) - horizon

    for i in range(start, end):
        indicesx = range(i-window, i)
        X.append(np.reshape(dataset[indicesx], (window, 1)))
        indicesy = range(i,i+horizon)
        y.append(dataset[indicesy])
    return np.array(X), np.array(y)

# Generating the test set
test_data = df['close'].tail(10)
df = df.drop(df['close'].tail(10).index)
df.shape

# Defining the target variable
uni_data = df['close']
uni_data.index = df['formatted_date']
uni_data.head()

#scaling
from sklearn import preprocessing
uni_data = uni_data.values
scaler_x = preprocessing.MinMaxScaler()
x_scaled = scaler_x.fit_transform(uni_data.reshape(-1, 1))

#  Single Step Style (sss) modeling
univar_hist_window_sss = 50
horizon_sss = 1
# 2014 observations in total
# 2014*0.85=1710 should be part of the training (304 validation)
train_split_sss = 1710

x_train_uni_sss, y_train_uni_sss = univariate_data_prep_func(x_scaled, 0, train_split_sss,
                                                             univar_hist_window_sss, horizon_sss)

x_val_uni_sss, y_val_uni_sss = univariate_data_prep_func(x_scaled, train_split_sss, None,
                                                         univar_hist_window_sss, horizon_sss)

print ('Length of first Single Window:')
print (len(x_train_uni_sss[0]))
print()
print ('Target horizon:')
print (y_train_uni_sss[0])

BATCH_SIZE_sss = 32
BUFFER_SIZE_sss = 150

train_univariate_sss = tf.data.Dataset.from_tensor_slices((x_train_uni_sss, y_train_uni_sss))
train_univariate_sss = train_univariate_sss.cache().shuffle(BUFFER_SIZE_sss).batch(BATCH_SIZE_sss).repeat()

validation_univariate_sss = tf.data.Dataset.from_tensor_slices((x_val_uni_sss, y_val_uni_sss))
validation_univariate_sss = validation_univariate_sss.batch(BATCH_SIZE_sss).repeat()

n_steps_per_epoch = 55
n_validation_steps = 10
n_epochs = 100

#FFNN architecture
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(8, input_shape=x_train_uni_sss.shape[-2:]),
    tf.keras.layers.Dense(units=horizon_sss)])

model.compile(loss='mse',
              optimizer='adam')

#fit the model
model_path = '/content/FFNN_model_sss.h5'
keras_callbacks = [tf.keras.callbacks.EarlyStopping(monitor='val_loss',
                                                    min_delta=0, patience=10,
                                                    verbose=1, mode='min'),
                   tf.keras.callbacks.ModelCheckpoint(model_path,monitor='val_loss',
                                                      save_best_only=True,
                                                      mode='min', verbose=0)]

history = model.fit(train_univariate_sss, epochs=n_epochs, steps_per_epoch=n_steps_per_epoch,
                    validation_data=validation_univariate_sss, validation_steps=n_validation_steps, verbose =1,
                    callbacks = keras_callbacks)

#validation
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(1, len(loss) + 1)

plt.plot(epochs, loss, 'r', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()

plt.show()

# Testing our model
trained_ffnn_model_sss = tf.keras.models.load_model(model_path)
df_temp = df['close']
test_horizon = df_temp.tail(univar_hist_window_sss)
test_history = test_horizon.values

result = []
# Define Forecast length here

window_len = len(test_data)
test_scaled = scaler_x.fit_transform(test_history.reshape(-1, 1))

for i in range(1, window_len+1):
    test_scaled = test_scaled.reshape((1, test_scaled.shape[0], 1))

    # Inserting the model
    predicted_results = trained_ffnn_model_sss.predict(test_scaled)

    print(f'predicted : {predicted_results}')
    result.append(predicted_results[0])
    test_scaled = np.append(test_scaled[:,1:],[[predicted_results]])

result_inv_trans = scaler_x.inverse_transform(result)
result_inv_trans
</code>```

I believe the problem might have to do with the shapes of data. How exactly I do not yet know.

Data:
click here

Traceback:
click here

Body:
I am learning neural network modeling and its uses in time series prediction.

First, thank you for reading this post and for your help :)

On this page there are various NN models (LSTM, CNN etc.) for predicting "traffic volume":

https://michael-fuchs-python.netlify.app/2020/11/01/time-series-analysis-neural-networks-for-forecasting-univariate-variables/#train-validation-split

I got inspired and decided to use/shorten/adapt the code in there for a problem of my own: predicting the bitcoin price.

I have the bitcoin daily prices starting 1.1.2017

in total 2024 daily prices

I use the first 85% of the data for the training data, and the rest as the validation (except the last 10 observation, which I would like to use as test data to see how good my model is)

I would like to use a Feedforward model

My goal is merely having a code that runs.

I have managed so far to have most of my code run. However, I get a strange format for my test forecast results: It should be simply an array of 10 numbers (i.e. predicted prices corresponding to the 10 day at the end of my data). To my surprise what is printed out is a long list of numbers. I need help to find out what changes I need to make to make to the code to make it run.

Thank you for helping me :)

The code is pasted down there, followed by the error:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing #import MinMaxScaler
from sklearn import metrics #import mean_squared_error
import seaborn as sns
sns.set()

import tensorflow as tf
from tensorflow import keras
from keras.layers import Input, Dense, Flatten
from keras.optimizers import Adam
from keras.models import Sequential
from keras.callbacks import EarlyStopping
tf.__version__

df = pd.read_csv('/content/BTC-USD.csv')

def mean_absolute_percentage_error_func(y_true, y_pred):

    y_true, y_pred = np.array(y_true), np.array(y_pred)
    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100

def timeseries_evaluation_metrics_func(y_true, y_pred):

    print('Evaluation metric results: ')
    print(f'MSE is : {metrics.mean_squared_error(y_true, y_pred)}')
    print(f'MAE is : {metrics.mean_absolute_error(y_true, y_pred)}')
    print(f'RMSE is : {np.sqrt(metrics.mean_squared_error(y_true, y_pred))}')
    print(f'MAPE is : {mean_absolute_percentage_error_func(y_true, y_pred)}')
    print(f'R2 is : {metrics.r2_score(y_true, y_pred)}',end='\n\n')

def univariate_data_prep_func(dataset, start, end, window, horizon):

    X = []
    y = []

    start = start + window
    if end is None:
        end = len(dataset) - horizon

    for i in range(start, end):
        indicesx = range(i-window, i)
        X.append(np.reshape(dataset[indicesx], (window, 1)))
        indicesy = range(i,i+horizon)
        y.append(dataset[indicesy])
    return np.array(X), np.array(y)

# Generating the test set
test_data = df['close'].tail(10)
df = df.drop(df['close'].tail(10).index)
df.shape

# Defining the target variable
uni_data = df['close']
uni_data.index = df['formatted_date']
uni_data.head()

#scaling
from sklearn import preprocessing
uni_data = uni_data.values
scaler_x = preprocessing.MinMaxScaler()
x_scaled = scaler_x.fit_transform(uni_data.reshape(-1, 1))

#  Single Step Style (sss) modeling
univar_hist_window_sss = 50
horizon_sss = 1
# 2014 observations in total
# 2014*0.85=1710 should be part of the training (304 validation)
train_split_sss = 1710

x_train_uni_sss, y_train_uni_sss = univariate_data_prep_func(x_scaled, 0, train_split_sss,
                                                             univar_hist_window_sss, horizon_sss)

x_val_uni_sss, y_val_uni_sss = univariate_data_prep_func(x_scaled, train_split_sss, None,
                                                         univar_hist_window_sss, horizon_sss)

print ('Length of first Single Window:')
print (len(x_train_uni_sss[0]))
print()
print ('Target horizon:')
print (y_train_uni_sss[0])

BATCH_SIZE_sss = 32
BUFFER_SIZE_sss = 150

train_univariate_sss = tf.data.Dataset.from_tensor_slices((x_train_uni_sss, y_train_uni_sss))
train_univariate_sss = train_univariate_sss.cache().shuffle(BUFFER_SIZE_sss).batch(BATCH_SIZE_sss).repeat()

validation_univariate_sss = tf.data.Dataset.from_tensor_slices((x_val_uni_sss, y_val_uni_sss))
validation_univariate_sss = validation_univariate_sss.batch(BATCH_SIZE_sss).repeat()

n_steps_per_epoch = 55
n_validation_steps = 10
n_epochs = 100

#FFNN architecture
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(8, input_shape=x_train_uni_sss.shape[-2:]),
    tf.keras.layers.Dense(units=horizon_sss)])

model.compile(loss='mse',
              optimizer='adam')

#fit the model
model_path = '/content/FFNN_model_sss.h5'
keras_callbacks = [tf.keras.callbacks.EarlyStopping(monitor='val_loss',
                                                    min_delta=0, patience=10,
                                                    verbose=1, mode='min'),
                   tf.keras.callbacks.ModelCheckpoint(model_path,monitor='val_loss',
                                                      save_best_only=True,
                                                      mode='min', verbose=0)]

history = model.fit(train_univariate_sss, epochs=n_epochs, steps_per_epoch=n_steps_per_epoch,
                    validation_data=validation_univariate_sss, validation_steps=n_validation_steps, verbose =1,
                    callbacks = keras_callbacks)

#validation
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(1, len(loss) + 1)

plt.plot(epochs, loss, 'r', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()

plt.show()

# Testing our model
trained_ffnn_model_sss = tf.keras.models.load_model(model_path)
df_temp = df['close']
test_horizon = df_temp.tail(univar_hist_window_sss)
test_history = test_horizon.values

result = []
# Define Forecast length here

window_len = len(test_data)
test_scaled = scaler_x.fit_transform(test_history.reshape(-1, 1))

for i in range(1, window_len+1):
    test_scaled = test_scaled.reshape((1, test_scaled.shape[0], 1))

    # Inserting the model
    predicted_results = trained_ffnn_model_sss.predict(test_scaled)

    print(f'predicted : {predicted_results}')
    result.append(predicted_results[0])
    test_scaled = np.append(test_scaled[:,1:],[[predicted_results]])

result_inv_trans = scaler_x.inverse_transform(result)
result_inv_trans

I believe the problem might have to do with the shapes of data. How exactly I do not yet know.

Data:
click here

Traceback:
click here


问:
ExpressJS and passportJS error: passport.use is not a function
I am trying to set up user authentication using passport but am getting the error:

TypeError: passport.use is not a function

I am calling initialize from my server.js file here, where I pass in the imported passport.

```<code>import express from "express";
const app = express();
import passport from "passport";
import initializePassport from "./passport-config.js";

initializePassport(passport);
</code>```

This is the passport-config.js file

```<code>import newConnection from "./DBConnection.js";
import { Strategy } from "passport-local";

function initialize(passport) {
  const authenticateUser = async (email, password, done) => {
         // DB code here
      }
    );
  };

  let LocalStrategy = new Strategy(
    { usernameField: "email" },
    authenticateUser
  );

  passport.use(LocalStrategy);

  passport.serializeUser((user, done) => done(null, user.id));
  passport.deserializeUser((id, done) => {
    let conn = newConnection();
    conn.query(
      `SELECT * FROM admins WHERE id=${id}`,
      (err, results, fields) => {
        if (err) return done(error);
        let user = results[0];
        return done(null, user);
      }
    );
  });
}

export default initialize;
</code>```

What am I doing wrong? Is there another library I have to import?

Body:
I am trying to set up user authentication using passport but am getting the error:

TypeError: passport.use is not a function

I am calling initialize from my server.js file here, where I pass in the imported passport.

import express from "express";
const app = express();
import passport from "passport";
import initializePassport from "./passport-config.js";

initializePassport(passport);

This is the passport-config.js file

import newConnection from "./DBConnection.js";
import { Strategy } from "passport-local";

function initialize(passport) {
  const authenticateUser = async (email, password, done) => {
         // DB code here
      }
    );
  };

  let LocalStrategy = new Strategy(
    { usernameField: "email" },
    authenticateUser
  );

  passport.use(LocalStrategy);

  passport.serializeUser((user, done) => done(null, user.id));
  passport.deserializeUser((id, done) => {
    let conn = newConnection();
    conn.query(
      `SELECT * FROM admins WHERE id=${id}`,
      (err, results, fields) => {
        if (err) return done(error);
        let user = results[0];
        return done(null, user);
      }
    );
  });
}

export default initialize;

What am I doing wrong? Is there another library I have to import?


问:
PM2 Caching Array, not cleared with pm2 kill
I have an app that generates an array from an API, that each object in the array has the following params title, start, end

For testing at one point I added a colour param, but this now needs to be removed. This has been removed from the code but pm2 is still adding colour to each item in the array. I have no idea where it is getting this information from.

```<code>let tmp = {
            title: i.subject,
            start: start.slice(0,-1),
            end: end
          }

//console.log(tmp)
events.push(tmp)
</code>```

and the is the output from the pm2 instance:

colour is no longer in my code so I'm not sure where it is coming from. I've tried clearing the npm cache and also pm2 kill but nothing seems to solve the problem. I have also tried completely deleting the app from my server and re-uploading it, I still get the same results.

Body:
I have an app that generates an array from an API, that each object in the array has the following params title, start, end

For testing at one point I added a colour param, but this now needs to be removed. This has been removed from the code but pm2 is still adding colour to each item in the array. I have no idea where it is getting this information from.

let tmp = {
            title: i.subject,
            start: start.slice(0,-1),
            end: end
          }

//console.log(tmp)
events.push(tmp)

and the is the output from the pm2 instance:

colour is no longer in my code so I'm not sure where it is coming from. I've tried clearing the npm cache and also pm2 kill but nothing seems to solve the problem. I have also tried completely deleting the app from my server and re-uploading it, I still get the same results.


问:
Distributing values across a tree evenly
If you had an undirected tree, with each node having an amount (not the same for each node, but can be the same) of coins, and one "action" consisted of moving an amount of coins (any amount from 1-the amount that the node has so no node can have negative at any time) from one node to an adjacent node, what would be the least amount of "action"s needed to have the same value in each node? (assume every node has integer values and the amount of nodes is divisible by total sum of coins)

Not really sure how to approach this

for example,
node 1 connects to node 2, node 1 connects to node 3
node 1 has 2 coins, node 2 has 2 coins, node 3 has 5 coins

This would take only 2 actions, (node 3 moving 2 coins to node 1, which then moves 1 to node 2)


问:
Python/Pillow: receiving indexerror when trying to hide a smaller image in a larger image (steganography)
I'm trying to hide an image, 'moon' (355x585 pixels) inside another image, 'loss' (960x676 pixels) by replacing the Least Significant Bits in each of loss's RGB values with the Most Significant Bits of moon's RGB values.

However, the program returns:

```<code>Traceback (most recent call last):
  File "D:\Business\Programming\Python\projects\Steg\steg.py", line 25, in <module>
    mr, mg, mb = moonpx[x,y]
IndexError: image index out of range
</code>```

whenever I run it. I don't know why it does this.
here is the code:

```<code>#!remember to list order as 'Red', 'Green, then 'Blue'!
import PIL
from PIL import Image

#assigns image paths to variables:
loss = Image.open(r"C:\Users\xxx\Desktop\Loss.png")
moon = Image.open(r"C:\Users\xxx\Desktop\moon2.png")
#tells code to open image from path (a real image now)

#loads the image pixel information:
losspx = loss.load()
moonpx = moon.load()

#defines new image (with same width/height as loss) and loads pixels as rgb info:
combo = Image.new('RGB', (loss.width,loss.height),'black')
combopx = combo.load()

for x in range(0,combo.width):
    for y in range(0,combo.height):
        mr, mg, mb = moonpx[x,y]
        lr, lg, lb = losspx[x,y]
'''
takes the first 4 bytes of loss: (f'{lr:08b}') & first 4 bytes of moon: (f'{mr:08b}')
and adds them together. the left half of the string are the Most Significant Bits & the second half of the string are the Least Significant Bits
'''
cr = int(f'{lr:08b}'+f'{mr:08b}'[:4],2)
cg = int(f'{lg:08b}'+f'{mg:08b}'[:4],2)
cb = int(f'{lb:08b}'+f'{mb:08b}'[:4],2)

combopx[x,y] = (cr, cg, cb)

combo.show()
</code>```

I have tried replacing line 20:

```<code>combo = Image.new('RGB', (loss.width,loss.height),'black')
</code>```

with

```<code>combo = Image.new('RGB', (moon.width,moon.height),'black')
</code>```

which returned a black image with moon's dimensions.

Body:
I'm trying to hide an image, 'moon' (355x585 pixels) inside another image, 'loss' (960x676 pixels) by replacing the Least Significant Bits in each of loss's RGB values with the Most Significant Bits of moon's RGB values.

However, the program returns:

Traceback (most recent call last):
  File "D:\Business\Programming\Python\projects\Steg\steg.py", line 25, in <module>
    mr, mg, mb = moonpx[x,y]
IndexError: image index out of range

whenever I run it. I don't know why it does this.
here is the code:

#!remember to list order as 'Red', 'Green, then 'Blue'!
import PIL
from PIL import Image

#assigns image paths to variables:
loss = Image.open(r"C:\Users\xxx\Desktop\Loss.png")
moon = Image.open(r"C:\Users\xxx\Desktop\moon2.png")
#tells code to open image from path (a real image now)

#loads the image pixel information:
losspx = loss.load()
moonpx = moon.load()

#defines new image (with same width/height as loss) and loads pixels as rgb info:
combo = Image.new('RGB', (loss.width,loss.height),'black')
combopx = combo.load()

for x in range(0,combo.width):
    for y in range(0,combo.height):
        mr, mg, mb = moonpx[x,y]
        lr, lg, lb = losspx[x,y]
'''
takes the first 4 bytes of loss: (f'{lr:08b}') & first 4 bytes of moon: (f'{mr:08b}')
and adds them together. the left half of the string are the Most Significant Bits & the second half of the string are the Least Significant Bits
'''
cr = int(f'{lr:08b}'+f'{mr:08b}'[:4],2)
cg = int(f'{lg:08b}'+f'{mg:08b}'[:4],2)
cb = int(f'{lb:08b}'+f'{mb:08b}'[:4],2)

combopx[x,y] = (cr, cg, cb)

combo.show()

I have tried replacing line 20:

combo = Image.new('RGB', (loss.width,loss.height),'black')

with

combo = Image.new('RGB', (moon.width,moon.height),'black')

which returned a black image with moon's dimensions.


问:
Force function to implement interface
Wouldn't it be cool if there was a way to ensure a typescript function uses all of its input parameters?

Example I'm writing database queries as functions for my backend application to use, and would like every find query to implement SELECT functionality.

```<code>// Params shared across all Find queries.
interface FindQueryParams {
  select?: string // which columns to select.
};

// Params for the specific function, extending Shared Params.
interface FindUserParams extends FindQueryParams {
  userId: number // id of the user.
}
function findUser(params: FindUserParams){
  const user = ...
  ... // code to find the user.
  return user;
}
</code>```

I want to ensure that the method uses the select parameter passed into it and Typescript to complain if my function does not user params.select.

There is no way to make sure function uses it without using classes as far as I know.

Title: Force function to implement interface

Body:
Wouldn't it be cool if there was a way to ensure a typescript function uses all of its input parameters?

Example I'm writing database queries as functions for my backend application to use, and would like every find query to implement SELECT functionality.

// Params shared across all Find queries.
interface FindQueryParams {
  select?: string // which columns to select.
};

// Params for the specific function, extending Shared Params.
interface FindUserParams extends FindQueryParams {
  userId: number // id of the user.
}
function findUser(params: FindUserParams){
  const user = ...
  ... // code to find the user.
  return user;
}

I want to ensure that the method uses the select parameter passed into it and Typescript to complain if my function does not user params.select.

There is no way to make sure function uses it without using classes as far as I know.


问:
How to settle multy-local datanodes and with datas out of the tmp file on Mac ? Location = null
(first participation, please do not hesite to ask further elements)

I try too follow a tuto (https://openclassrooms.com/fr/courses/4467481-creez-votre-data-lake/4509436-deployez-hdfs-en-production-et-passez-a-l-echelle) to create a multi datanode on my laptop.
First we start with a namenode and one data node, then we add other data nodes.

The problem seems to be in two steps :
- During the namenode -format : I have a "location = null ??"
- I can run two datanodes but not two or more

The protocol is for the first part (1 datanode) :

Edit core-site.xml

Edit hdfs-site.xml

Create the folders corresponding the previous path edition

namenode -format

lunch namenode

lunch datanode

Second part (Three new datanodes) :

Create config files for new datanodes

lunch namenode

lunch datanodes : ./bin/hdfs datanode -conf ./etc/hadoop/datanode1.xml

NB : I define new folder for the data because we don't want them in the tmp file.

In the second part of the protocol, configuration files are edited (cf files) and we lunch the datanodes with. Thus, is the "dfs.data.dir" part in the hdfs-site file useless for more than one datanode ?

Issues :
When I do namenode -format i have these ligne : "Re-format filesystem in Storage Directory root= /Users/XXXXX/code/hdfs/namenode; location= null ? (Y or N)." I do Y

At this point, i don't understand the location = null ? It is not present in the tutorial, thus i think that my path is not ok. If I double chekcs my files, it appears to be ok.

Then i run my namode : It is ok
Then i run my firts datanode : It is ok

But when i run my seconde data node : Not ok : "datanode is running as process 72080.  Stop it first and ensure /tmp/hadoop-XXXX-datanode.pid file is empty before retry"

I tend to think that it is all related to a path issue.
I looked in my tmp folder, and there is the .pid files. I don't understand because i though that i decide not to use the tmp files thanks to the change in my configuration

Here my files :

hdfs-site :

```<code>
`<configuration>
    <property>
        <name>dfs.name.dir</name>
        <value>/Users/XXXX/code/hdfs/namenode/</value>
    </property>
    <property>
        <name>dfs.data.dir</name>
        <value>/Users/XXXX/code/hdfs/datanode/</value>
    </property>
 </configuration>`

</code>```

Core-site

```<code>`<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>fs.defaultFS</name>
        <value>hdfs://localhost:9000</value>
        </property>
</configuration>`

</code>```

DatanodeX

```<code>
`<configuration>
    <property>
        <name>dfs.datanode.address</name>
        <value>0.0.0.0:50012</value>
    </property>
    <property>
        <name>dfs.datanode.http.address</name>
        <value>0.0.0.0:50077</value>
    </property>
    <property>
        <name>dfs.datanode.ipc.address</name>
        <value>0.0.0.0:50022</value>
    </property>
    <property>
        <name>dfs.data.dir</name>
        <value>/Users/XXXX/code/hdfs/datanode2/</value>
    </property>
</configuration>
`
</code>```

Body:
(first participation, please do not hesite to ask further elements)

I try too follow a tuto (https://openclassrooms.com/fr/courses/4467481-creez-votre-data-lake/4509436-deployez-hdfs-en-production-et-passez-a-l-echelle) to create a multi datanode on my laptop.
First we start with a namenode and one data node, then we add other data nodes.

The problem seems to be in two steps :
- During the namenode -format : I have a "location = null ??"
- I can run two datanodes but not two or more

The protocol is for the first part (1 datanode) :

Edit core-site.xml

Edit hdfs-site.xml

Create the folders corresponding the previous path edition

namenode -format

lunch namenode

lunch datanode

Second part (Three new datanodes) :

Create config files for new datanodes

lunch namenode

lunch datanodes : ./bin/hdfs datanode -conf ./etc/hadoop/datanode1.xml

NB : I define new folder for the data because we don't want them in the tmp file.

In the second part of the protocol, configuration files are edited (cf files) and we lunch the datanodes with. Thus, is the "dfs.data.dir" part in the hdfs-site file useless for more than one datanode ?

Issues :
When I do namenode -format i have these ligne : "Re-format filesystem in Storage Directory root= /Users/XXXXX/code/hdfs/namenode; location= null ? (Y or N)." I do Y

At this point, i don't understand the location = null ? It is not present in the tutorial, thus i think that my path is not ok. If I double chekcs my files, it appears to be ok.

Then i run my namode : It is ok
Then i run my firts datanode : It is ok

But when i run my seconde data node : Not ok : "datanode is running as process 72080.  Stop it first and ensure /tmp/hadoop-XXXX-datanode.pid file is empty before retry"

I tend to think that it is all related to a path issue.
I looked in my tmp folder, and there is the .pid files. I don't understand because i though that i decide not to use the tmp files thanks to the change in my configuration

Here my files :

hdfs-site :

`<configuration>
    <property>
        <name>dfs.name.dir</name>
        <value>/Users/XXXX/code/hdfs/namenode/</value>
    </property>
    <property>
        <name>dfs.data.dir</name>
        <value>/Users/XXXX/code/hdfs/datanode/</value>
    </property>
 </configuration>`

Core-site

`<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>fs.defaultFS</name>
        <value>hdfs://localhost:9000</value>
        </property>
</configuration>`

DatanodeX

`<configuration>
    <property>
        <name>dfs.datanode.address</name>
        <value>0.0.0.0:50012</value>
    </property>
    <property>
        <name>dfs.datanode.http.address</name>
        <value>0.0.0.0:50077</value>
    </property>
    <property>
        <name>dfs.datanode.ipc.address</name>
        <value>0.0.0.0:50022</value>
    </property>
    <property>
        <name>dfs.data.dir</name>
        <value>/Users/XXXX/code/hdfs/datanode2/</value>
    </property>
</configuration>
`


问:
Google Sign In with the OAuth 2.0
I'm trying to do a normal registration with the OAuth 2.0, but the console gives out this error:
Everything is tested on the local server[My code(https://i.stack.imgur.com/49qMj.png)(https://i.stack.imgur.com/NJGl6.png)

Authorized JavaScript origins

Title: Google Sign In with the OAuth 2.0


问:
Svelte Carousel - Flowbite bug?
my code copied from example:
example:https://flowbite-svelte.com/components/carousel

`

```<code>
<script>
    import { Carousel } from 'flowbite-svelte';
    let imageList = [
        {
            id: 0,
            name: 'Cosmic timetraveler',
            imgurl: '/images/carousel/cosmic-timetraveler-pYyOZ8q7AII-unsplash.webp',
            attribution: 'cosmic-timetraveler-pYyOZ8q7AII-unsplash.com'
        },
        {
            id: 1,
            name: 'Cristina Gottardi',
            imgurl: '/images/carousel/cristina-gottardi-CSpjU6hYo_0-unsplash.webp',
            attribution: 'cristina-gottardi-CSpjU6hYo_0-unsplash.com'
        },
        {
            id: 2,
            name: 'Johannes Plenio',
            imgurl: '/images/carousel/johannes-plenio-RwHv7LgeC7s-unsplash.webp',
            attribution: 'johannes-plenio-RwHv7LgeC7s-unsplash.com'
        },
        {
            id: 3,
            name: 'Jonatan Pie',
            imgurl: '/images/carousel/jonatan-pie-3l3RwQdHRHg-unsplash.webp',
            attribution: 'jonatan-pie-3l3RwQdHRHg-unsplash.com'
        },
        {
            id: 4,
            name: 'Mark Harpur',
            imgurl: '/images/carousel/mark-harpur-K2s_YE031CA-unsplash.webp',
            attribution: 'mark-harpur-K2s_YE031CA-unsplash'
        },
        {
            id: 5,
            name: 'Pietro De Grandi',
            imgurl: '/images/carousel/pietro-de-grandi-T7K4aEPoGGk-unsplash.webp',
            attribution: 'pietro-de-grandi-T7K4aEPoGGk-unsplash'
        },
        {
            id: 6,
            name: 'Sergey Pesterev',
            imgurl: '/images/carousel/sergey-pesterev-tMvuB9se2uQ-unsplash.webp',
            attribution: 'sergey-pesterev-tMvuB9se2uQ-unsplash'
        },
        {
            id: 7,
            name: 'Solo travel goals',
            imgurl: '/images/carousel/solotravelgoals-7kLufxYoqWk-unsplash.webp',
            attribution: 'solotravelgoals-7kLufxYoqWk-unsplash'
            }
    ];
</script>

<div class="max-w-4xl">
    <Carousel {imageList} />
</div>

error:

Cannot read properties of undefined (reading 'length')
TypeError: Cannot read properties of undefined (reading 'length')
    at eval (/node_modules/flowbite-svelte/carousels/Carousel.svelte:50:32)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at eval (/src/routes/+page.svelte:62:125)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at Object.default (root.svelte:41:38)
    at eval (/src/routes/+layout.svelte:26:67)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at root.svelte:40:37
    at $$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at Object.render (/node_modules/svelte/internal/index.mjs:1884:26)
</code>```

`

i chceck with console.log imageList is array and has property leght
i think this is some kind of bug in svelte
when i randomly reload my website sometime code work propertly
how i can debug this?
i also tried

```<code>{#await promise}
</code>```

but the same error

Title: Svelte Carousel - Flowbite bug?

Body:
my code copied from example:
example:https://flowbite-svelte.com/components/carousel

`

    <Carousel {imageList} />

error:

Cannot read properties of undefined (reading 'length')
TypeError: Cannot read properties of undefined (reading 'length')
    at eval (/node_modules/flowbite-svelte/carousels/Carousel.svelte:50:32)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at eval (/src/routes/+page.svelte:62:125)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at Object.default (root.svelte:41:38)
    at eval (/src/routes/+layout.svelte:26:67)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at root.svelte:40:37
    at $$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at Object.render (/node_modules/svelte/internal/index.mjs:1884:26)

`

i chceck with console.log imageList is array and has property leght
i think this is some kind of bug in svelte
when i randomly reload my website sometime code work propertly
how i can debug this?
i also tried

{#await promise}

but the same error


问:
Moving average in Grafana with Flux
I want to show 2 variables in a time series panel, one just the _value and for the other the moving average lets say over 6hrs. I cannot figure out the syntax to do it just for one of those 2 measurements

```<code>from(bucket: "ns")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "openaps")
  |> filter(fn: (r) => r["_field"] == "tdd" or r["_field"] == "isf")
  |> filter(fn: (r) => r._value > 0)
  |> timedMovingAverage(every: 5m, period: 300m)
</code>```

I only got that far, all if statements failed

Title: Moving average in Grafana with Flux

Body:
I want to show 2 variables in a time series panel, one just the _value and for the other the moving average lets say over 6hrs. I cannot figure out the syntax to do it just for one of those 2 measurements

from(bucket: "ns")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "openaps")
  |> filter(fn: (r) => r["_field"] == "tdd" or r["_field"] == "isf")
  |> filter(fn: (r) => r._value > 0)
  |> timedMovingAverage(every: 5m, period: 300m)

I only got that far, all if statements failed


问:
Using Lambda/Node js how do I make http GET/POST request with username/password and certificates authentication
I need to make HTTP Requests on lambda but it include me using some files known as certificates and also username/password. How can i add this.
I have the files

CRT file

aleezah-mtls.pem

KEY file

aleezah-mtls.key

PEM file

ca.pem

A simple get request script that works perfectly is

```<code>function getRequest() {
  const url = 'https://reqres.in/api/users';

  return new Promise((resolve, reject) => {
    const req = https.get(url, res => {
      let rawData = '';

      res.on('data', chunk => {
        rawData += chunk;
      });

      res.on('end', () => {
        try {
          resolve(JSON.parse(rawData));
        } catch (err) {
          reject(new Error(err));
        }
      });
    });

    req.on('error', err => {
      reject(new Error(err));
    });
  });
}
</code>```

How to I make the above function accommodate those certificates and credentials(username/password)

I was able to do this on postman

How do I add these in a script?

Body:
I need to make HTTP Requests on lambda but it include me using some files known as certificates and also username/password. How can i add this.
I have the files

CRT file

aleezah-mtls.pem

KEY file

aleezah-mtls.key

PEM file

ca.pem

A simple get request script that works perfectly is

function getRequest() {
  const url = 'https://reqres.in/api/users';

  return new Promise((resolve, reject) => {
    const req = https.get(url, res => {
      let rawData = '';

      res.on('data', chunk => {
        rawData += chunk;
      });

      res.on('end', () => {
        try {
          resolve(JSON.parse(rawData));
        } catch (err) {
          reject(new Error(err));
        }
      });
    });

    req.on('error', err => {
      reject(new Error(err));
    });
  });
}

How to I make the above function accommodate those certificates and credentials(username/password)

I was able to do this on postman

How do I add these in a script?


问:
CCS811 Gas sensor With raspberry pi and a relay
dears stackoverflow community, I need an instructions guide with python script to make a project to measure the co2 concentration in room and when the concentration is high the relay should switch a light on, so can anyone be kindful and help me to find the instructions guide, thank you in advance.</p>


问:
Upload image error -> blob:http://localhost:3000/48c7da66-42c0-4ed3-8691-2dedd5ce4984:1 Failed to load resource: net::ERR_FILE_NOT_FOUND
After uploading image, the image shows up for the profile picture even after refresh, however does not persist when logged out then logged back in.
Here is the code:
profileForm.js

```<code>import React, { useState } from 'react';
import { useMutation } from '@apollo/client';

import { ADD_PROFILE } from '../../utils/mutations';
import { QUERY_PROFILES, QUERY_ME } from '../../utils/queries';

import './profileForm.css';

const ProfileForm = () => {
    const styles = {
        add__image__button: {
            border: '1px solid black'
        },
        container: {
            background: 'linear-gradient(90deg, rgba(93, 12, 255, 1) 0%, rgba(155, 0, 250, 1) 100%)',
            borderRadius: '2.5rem',
            boxShadow: '15px 15px 15px rgba(46, 54, 68, 0.4)',
            display: 'flex',
            alignItems: 'center',
            padding: '5rem 3rem',
            marginTop: '20px',
            marginBottom: '20px',
            float: 'right',
            width: 'calc(100% - 240px)',
            marginRight: '10px',
        },
    }

    const [image, setImage] = useState('');

    const [addProfile] = useMutation(ADD_PROFILE, {
        update(cache, { data: { addProfile } }) {
            try {
                const { profiles } = cache.readQuery({ query: QUERY_PROFILES });

                cache.writeQuery({
                    query: QUERY_PROFILES,
                    data: { profiles: [addProfile, ...profiles] },
                });
            } catch (error) {
                throw error;
            }

            // update me object's cache
            try {
                const { me } = cache.readQuery({ query: QUERY_ME });

                cache.writeQuery({
                    query: QUERY_ME,
                    data: { me: { ...me, profiles: [...me.profiles, addProfile] } },
                });
            } catch (error) {
                throw error;
            }
        },
    });

    const handleFormSubmit = async (event) => {
        event.preventDefault();

        try {
            const { data } = await addProfile({
                variables: {
                    image,
                },
            });
            setImage('');
        } catch (error) {
            throw error;
        }
    };

    const handlePhoto = (event) => {
        console.log(event.target.files);
        setImage(URL.createObjectURL(event.target.files[0]));
    };

    return (
        <div className="container flex-column justify-center" style={styles.container}>
            <form
                className="avatar-upload"
                onSubmit={handleFormSubmit}
            >
                <div className="avatar-edit">
                    <input id="imageUpload" type="file" className="imageUpload" onChange={handlePhoto} accept=".png, .jpg, .jpeg" />
                    <label className="label" for="imageUpload"></label>
                </div>
                <div className="avatar-preview">
                    <img className="imagePreview" alt="" src={image}
                        style={{ backgroundImage: `url("https://www.pngfind.com/pngs/m/610-6104451_image-placeholder-png-user-profile-placeholder-image-png.png")` }} />
                </div>
                <button className="uploadImage" type="submit" style={styles.add__image__button}>
                    Upload
                </button>
            </form >
        </div >
    );
};

export default ProfileForm;

</code>```

profileList.js

```<code>import React from 'react';

const PostList = ({
    profiles,
}) => {

    let lastElement = profiles.slice(-1);
    console.log(lastElement);
    return (
        <div>
            {profiles &&
                profiles.slice(-1).map((profile) => (
                    <div key={profile._id}>
                        <div>
                            <img className="profile__image" src={profile.image} alt="profileimage" width={80} height={80}></img>
                        </div>
                    </div>
                ))}
        </div>
    );
};

export default PostList;

</code>```

sidebar.js

```<code>import React, { useState } from "react";
import { useQuery } from '@apollo/client';
import { Link } from 'react-router-dom';
import { ProSidebar, Menu, MenuItem, SidebarHeader, SidebarContent } from "react-pro-sidebar";
import { FiHome, FiLogOut } from "react-icons/fi";
import "react-pro-sidebar/dist/css/styles.css";
import './sidebar.css';
import Auth from "../../utils/auth";
import ProfileList from './profileList';
import { FiEdit } from "react-icons/fi";

import { QUERY_PROFILES } from '../../utils/queries';

function Sidebar() {
    const [activeIndex, setActiveIndex] = useState(() => {
        const initialIndex =
            window.location.pathname === '/' ? 0
                : window.location.pathname === '/login' ? 1
                    : window.location.pathname === '/signup' ? 2
                        : 0;
        return initialIndex;
    });

    const logout = (event) => {
        event.preventDefault();
        Auth.logout();
    };

    const { loading, data } = useQuery(QUERY_PROFILES);
    const profiles = data?.profiles || [];

    return (
        <>
            <div className="sidebar" id="header">
                {/* collapsed props to change menu size using menucollapse state */}
                <ProSidebar>
                    <SidebarHeader>
                        <div className="logotext">
                            Green Dough
                        </div>
                    </SidebarHeader>
                    {Auth.loggedIn() ? (
                        <>
                            <div className="profile">
                                {loading ? (
                                    <div>Loading...</div>
                                ) : (
                                    <ProfileList
                                        profiles={profiles}
                                    />
                                )}
                                <Link
                                    to="/profile"
                                >
                                    <FiEdit className='icons' />
                                </Link>
                            </div>
                            <SidebarContent>
                                <Menu iconShape="square">
                                    <MenuItem icon={<FiLogOut />}>
                                        Logout
                                        <Link id="MenuItemLogout" onClick={logout} />
                                    </MenuItem>
                                </Menu>
                            </SidebarContent>
                        </>
                    ) : (
                        <>
                            <SidebarContent>
                                <Menu iconShape="square">
                                    <MenuItem active={activeIndex === 0} icon={<FiHome />} >
                                        Home
                                        <Link id="MenuItemHome" to="/" onClick={() => setActiveIndex(0)} />
                                    </MenuItem>
                                    <MenuItem active={activeIndex === 1} icon={<FiHome />} >
                                        Login
                                        <Link id="MenuItemLogin" to="/login" onClick={() => setActiveIndex(1)} />
                                    </MenuItem>
                                    <MenuItem active={activeIndex === 2} icon={<FiHome />}>
                                        Signup
                                        <Link id="MenuItemSignup" to="/signup" onClick={() => setActiveIndex(2)} />
                                    </MenuItem>
                                </Menu>
                            </SidebarContent>
                        </>
                    )}
                </ProSidebar>
            </div>
        </>
    );
}

export default Sidebar;
</code>```

I've tried using axios, however when uploaded to Heroku, it only shows on localhost and does not work on Heroku.

Body:
After uploading image, the image shows up for the profile picture even after refresh, however does not persist when logged out then logged back in.
Here is the code:
profileForm.js

import React, { useState } from 'react';
import { useMutation } from '@apollo/client';

import { ADD_PROFILE } from '../../utils/mutations';
import { QUERY_PROFILES, QUERY_ME } from '../../utils/queries';

import './profileForm.css';

const ProfileForm = () => {
    const styles = {
        add__image__button: {
            border: '1px solid black'
        },
        container: {
            background: 'linear-gradient(90deg, rgba(93, 12, 255, 1) 0%, rgba(155, 0, 250, 1) 100%)',
            borderRadius: '2.5rem',
            boxShadow: '15px 15px 15px rgba(46, 54, 68, 0.4)',
            display: 'flex',
            alignItems: 'center',
            padding: '5rem 3rem',
            marginTop: '20px',
            marginBottom: '20px',
            float: 'right',
            width: 'calc(100% - 240px)',
            marginRight: '10px',
        },
    }

    const [image, setImage] = useState('');

    const [addProfile] = useMutation(ADD_PROFILE, {
        update(cache, { data: { addProfile } }) {
            try {
                const { profiles } = cache.readQuery({ query: QUERY_PROFILES });

                cache.writeQuery({
                    query: QUERY_PROFILES,
                    data: { profiles: [addProfile, ...profiles] },
                });
            } catch (error) {
                throw error;
            }

            // update me object's cache
            try {
                const { me } = cache.readQuery({ query: QUERY_ME });

                cache.writeQuery({
                    query: QUERY_ME,
                    data: { me: { ...me, profiles: [...me.profiles, addProfile] } },
                });
            } catch (error) {
                throw error;
            }
        },
    });

    const handleFormSubmit = async (event) => {
        event.preventDefault();

        try {
            const { data } = await addProfile({
                variables: {
                    image,
                },
            });
            setImage('');
        } catch (error) {
            throw error;
        }
    };

    const handlePhoto = (event) => {
        console.log(event.target.files);
        setImage(URL.createObjectURL(event.target.files[0]));
    };

    return (

            <form
                className="avatar-upload"
                onSubmit={handleFormSubmit}
            >

                    <input id="imageUpload" type="file" className="imageUpload" onChange={handlePhoto} accept=".png, .jpg, .jpeg" />

                    <img className="imagePreview" alt="" src={image}
                        style={{ backgroundImage: `url("https://www.pngfind.com/pngs/m/610-6104451_image-placeholder-png-user-profile-placeholder-image-png.png")` }} />

                <button className="uploadImage" type="submit" style={styles.add__image__button}>
                    Upload
                </button>
            </form >

    );
};

export default ProfileForm;

profileList.js

import React from 'react';

const PostList = ({
    profiles,
}) => {

    let lastElement = profiles.slice(-1);
    console.log(lastElement);
    return (

            {profiles &&
                profiles.slice(-1).map((profile) => (

                ))}

    );
};

export default PostList;

sidebar.js

import React, { useState } from "react";
import { useQuery } from '@apollo/client';
import { Link } from 'react-router-dom';
import { ProSidebar, Menu, MenuItem, SidebarHeader, SidebarContent } from "react-pro-sidebar";
import { FiHome, FiLogOut } from "react-icons/fi";
import "react-pro-sidebar/dist/css/styles.css";
import './sidebar.css';
import Auth from "../../utils/auth";
import ProfileList from './profileList';
import { FiEdit } from "react-icons/fi";

import { QUERY_PROFILES } from '../../utils/queries';

function Sidebar() {
    const [activeIndex, setActiveIndex] = useState(() => {
        const initialIndex =
            window.location.pathname === '/' ? 0
                : window.location.pathname === '/login' ? 1
                    : window.location.pathname === '/signup' ? 2
                        : 0;
        return initialIndex;
    });

    const logout = (event) => {
        event.preventDefault();
        Auth.logout();
    };

    const { loading, data } = useQuery(QUERY_PROFILES);
    const profiles = data?.profiles || [];

    return (
        <>

                {/* collapsed props to change menu size using menucollapse state */}
                <ProSidebar>
                    <SidebarHeader>

                            Green Dough

                    </SidebarHeader>
                    {Auth.loggedIn() ? (
                        <>

                                {loading ? (

Loading...

                                ) : (
                                    <ProfileList
                                        profiles={profiles}
                                    />
                                )}
                                <Link
                                    to="/profile"
                                >
                                    <FiEdit className='icons' />
                                </Link>

                            <SidebarContent>
                                <Menu iconShape="square">
                                    <MenuItem icon={<FiLogOut />}>
                                        Logout
                                        <Link id="MenuItemLogout" onClick={logout} />
                                    </MenuItem>
                                </Menu>
                            </SidebarContent>
                        </>
                    ) : (
                        <>
                            <SidebarContent>
                                <Menu iconShape="square">
                                    <MenuItem active={activeIndex === 0} icon={<FiHome />} >
                                        Home
                                        <Link id="MenuItemHome" to="/" onClick={() => setActiveIndex(0)} />
                                    </MenuItem>
                                    <MenuItem active={activeIndex === 1} icon={<FiHome />} >
                                        Login
                                        <Link id="MenuItemLogin" to="/login" onClick={() => setActiveIndex(1)} />
                                    </MenuItem>
                                    <MenuItem active={activeIndex === 2} icon={<FiHome />}>
                                        Signup
                                        <Link id="MenuItemSignup" to="/signup" onClick={() => setActiveIndex(2)} />
                                    </MenuItem>
                                </Menu>
                            </SidebarContent>
                        </>
                    )}
                </ProSidebar>

        </>
    );
}

export default Sidebar;

I've tried using axios, however when uploaded to Heroku, it only shows on localhost and does not work on Heroku.


问:
How to trigger a job in Concourse pipeline when feature branch is deleted?
I am looking for an option to trigger a job automatically whenever a feature branch is deleted in git.

For e.g I have two feature branches and if one is deleted, should trigger a Job and Job should know which feature branch is deleted.

Reference - https://www.concoursetutorial.com/basics/triggers.html

As per the above URL, job gets triggered whenever there is a new commit to the branch (master/feature).
So when we merge our feature branch using 'Squash and Merge' and delete the feature branch, it will be a new commit to Dev/Master branch and job will get triggered, but how we would know which feature branch is deleted?

Thanks in Advance!


问:
Styled Components Injects wrong classes on wrong elements
I'm witnessing a weird behavior when in styled-components with SSR in remix.run

I have a ProductCard Component that renders a normal product card with styled-components

ProductCard.tsx

import Button from "../Button";

function ProductCard({ product }: props) {
  return (
    <>
      <Wrapper>
        ....
        <ButtonsWrapper>
          <Cart
            onClick={addToCart}
            mode={addedToCart ? "secondary" : "primary"}
            disabled={loading}
            key="cart-button"
          >
            {addedToCart ? "Added!" : "Add to cart"}
            {loading && <LoadingSpinner src="/images/responses/loader.svg" />}
          </Cart>
          <ShareButton mode="secondary" aria-label="share">
            <Icon id="share" />
          </ShareButton>
        </ButtonsWrapper>
      </Wrapper>
    </>
  );
}

const Cart = styled(Button)`
  flex: 1.1;
  display: flex;
  justify-content: center;
  gap: 10px;
`;
const ShareButton = styled(Button)`
  padding: 0.9rem;
`;
const Wrapper = styled.div`
  --border-radius: ${clamp(15, 20)};
  --columnGap: ${clamp(20, 30)};
  display: flex;
  flex-direction: column;
  gap: var(--columnGap);
  justify-content: space-between;
  width: 100%;
  height: 100%;
  margin: auto;
  background-color: var(--azure-15);
  padding: 1.9rem 1.5rem;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow-lg);
  border: var(--border-lg);
`;
const ButtonsWrapper = styled.div`
  display: flex;
  justify-content: space-between;
  gap: 0.625rem;
`;
export default ProductCard;
```
<p>Button.tsx</p>
<pre class="lang-js prettyprint-override"><code>const Button = styled.button<{ mode: "primary" | "secondary" | "dark" }>`
  display: grid;
  /* justify-content: center; */
  align-items: center;
  text-align: center;
  color: var(--mintCream);
  padding: ${clamp(9, 10)} ${clamp(20, 30)}; // this clamp function just generates the css clamp func with calculating the values with some equations
  box-shadow: var(--box-shadow-md);
  border: var(--border-md);
  border-radius: 12px;
  text-decoration: none;
  cursor: pointer;
  transition: all 500ms ease;
  font-size: ${clamp(13, 16)};
  &:disabled {
    cursor: not-allowed;
    opacity: 0.7;
  }
  @media (hover: hover) and (pointer: fine) {
    &:hover:enabled {
      transform: translateY(-2px);    }
  }
  width: fit-content;
`;
</code>```

The normal render of this Component is as follows

But when navigating to another path and returning to it on / , it renders like this

This problem only happens in production and works fine on local server...

when inspecting elements, I find that the class name of the Cart Component is also injected into the ShareButton Element

I can't find an explanation for this problem and it gets weirder... When I swap the order of the variables Cart and ShareButton or swap them with the Wrapper Element, some other weird behaviors happen like the one below

In this case, the class name of the Cart Component got injected on the parent elemnt of the parent element of the ProductCard Component

I've probably hit on 4 of these rendering issues but all of them share the same problem, the class name of the Cart Components gets injected on a wrong dom element, whether it's a parent or a sibiling

You can view the first weird behaviour here https://store.ieeenu.com
You will find the product component on the root path, navigate to some path like categories/circuits-1-ecen101 and return to the root and you will see the issue

also, you can review the second weird behavior in a previous build here
https://ieee-nu-store-r243eocii-omarkhled.vercel.app/
I just changed the initialization order of the Cart and ShareButton Components as I said earlier

I don't know whether this problem is from styled-components or from remix (this is the first time for me using remix), it's mentioned here https://github.com/remix-run/remix/issues/1032 that the lack of the babel-plugin-styled-components in remix.run introduces some problems in rehydration but I'm not sure that this is the issue I'm facing...

Thanks for reading this till the end and excuse my English, I'm not a native speaker :"

Body:
I'm witnessing a weird behavior when in styled-components with SSR in remix.run

I have a ProductCard Component that renders a normal product card with styled-components

ProductCard.tsx

import Button from "../Button";

function ProductCard({ product }: props) {
  return (
    <>
      <Wrapper>
        ....
        <ButtonsWrapper>
          <Cart
            onClick={addToCart}
            mode={addedToCart ? "secondary" : "primary"}
            disabled={loading}
            key="cart-button"
          >
            {addedToCart ? "Added!" : "Add to cart"}
            {loading && <LoadingSpinner src="/images/responses/loader.svg" />}
          </Cart>
          <ShareButton mode="secondary" aria-label="share">
            <Icon id="share" />
          </ShareButton>
        </ButtonsWrapper>
      </Wrapper>
    </>
  );
}

const Cart = styled(Button)`
  flex: 1.1;
  display: flex;
  justify-content: center;
  gap: 10px;
`;
const ShareButton = styled(Button)`
  padding: 0.9rem;
`;
const Wrapper = styled.div`
  --border-radius: ${clamp(15, 20)};
  --columnGap: ${clamp(20, 30)};
  display: flex;
  flex-direction: column;
  gap: var(--columnGap);
  justify-content: space-between;
  width: 100%;
  height: 100%;
  margin: auto;
  background-color: var(--azure-15);
  padding: 1.9rem 1.5rem;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow-lg);
  border: var(--border-lg);
`;
const ButtonsWrapper = styled.div`
  display: flex;
  justify-content: space-between;
  gap: 0.625rem;
`;
export default ProductCard;

Button.tsx

const Button = styled.button<{ mode: "primary" | "secondary" | "dark" }>`
  display: grid;
  /* justify-content: center; */
  align-items: center;
  text-align: center;
  color: var(--mintCream);
  padding: ${clamp(9, 10)} ${clamp(20, 30)}; // this clamp function just generates the css clamp func with calculating the values with some equations
  box-shadow: var(--box-shadow-md);
  border: var(--border-md);
  border-radius: 12px;
  text-decoration: none;
  cursor: pointer;
  transition: all 500ms ease;
  font-size: ${clamp(13, 16)};
  &:disabled {
    cursor: not-allowed;
    opacity: 0.7;
  }
  @media (hover: hover) and (pointer: fine) {
    &:hover:enabled {
      transform: translateY(-2px);    }
  }
  width: fit-content;
`;

The normal render of this Component is as follows

But when navigating to another path and returning to it on / , it renders like this

This problem only happens in production and works fine on local server...

when inspecting elements, I find that the class name of the Cart Component is also injected into the ShareButton Element

I can't find an explanation for this problem and it gets weirder... When I swap the order of the variables Cart and ShareButton or swap them with the Wrapper Element, some other weird behaviors happen like the one below

In this case, the class name of the Cart Component got injected on the parent elemnt of the parent element of the ProductCard Component

I've probably hit on 4 of these rendering issues but all of them share the same problem, the class name of the Cart Components gets injected on a wrong dom element, whether it's a parent or a sibiling

You can view the first weird behaviour here https://store.ieeenu.com
You will find the product component on the root path, navigate to some path like categories/circuits-1-ecen101 and return to the root and you will see the issue

also, you can review the second weird behavior in a previous build here
https://ieee-nu-store-r243eocii-omarkhled.vercel.app/
I just changed the initialization order of the Cart and ShareButton Components as I said earlier

I don't know whether this problem is from styled-components or from remix (this is the first time for me using remix), it's mentioned here https://github.com/remix-run/remix/issues/1032 that the lack of the babel-plugin-styled-components in remix.run introduces some problems in rehydration but I'm not sure that this is the issue I'm facing...

Thanks for reading this till the end and excuse my English, I'm not a native speaker :"


问:
How do I associate an Google Play Download App to a Website Google search for Android Apps?
So I have been trying to find wayx to associate My App to my website's google search, a couple of post are suggesting using App Indexing from the Google Play Store I tried that and nothing has happen so far...( Unless I have to create a deeplink in the App Mainfest?) And example of what I am trying to achieve is similar to the screenshot provided for such as Walgreens where they have a install button. And I want to achieve the same with my personal project. Are there any resources out there to achieve this feature?


问:
how to apply band pass filter using fast Fourier transform
I'm trying to make a band-pass filer using ftt in order to  build an audio  equalizer, I successfully  realize the low-pass and high-pass filter of a signal y with sample rate sr:

```<code>def lowpass(y,sr):
    S = librosa.stft(y)
    f = np.arange(S.shape[0])
    t = np.arange(S.shape[1])
    A = np.exp(-t[None, :]*f[:, None]/(100*S.shape[1]))
    SNew = S*A
    p_bas= librosa.istft(SNew)
</code>```
```<code>def higyhpass(y,sr):
    S = librosa.stft(y)
    f = np.arange(S.shape[0])
    t = np.arange(S.shape[1])
    A = np.exp(t[None, :]*f[:, None]/(100*S.shape[1]))
    SNew = S*A
    p_bas= librosa.istft(SNew)
</code>```

I get stuck on how to implement the low-cut and high-cut  frequency using the same algorithm of low-pass and high-pass

```<code>def band_pass(data, lowcut, highcut, fs, order=5):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='bandpass')
    filtered = lfilter(b, a, data)
    return filtered
</code>```

Body:
I'm trying to make a band-pass filer using ftt in order to  build an audio  equalizer, I successfully  realize the low-pass and high-pass filter of a signal y with sample rate sr:

def lowpass(y,sr):
    S = librosa.stft(y)
    f = np.arange(S.shape[0])
    t = np.arange(S.shape[1])
    A = np.exp(-t[None, :]*f[:, None]/(100*S.shape[1]))
    SNew = S*A
    p_bas= librosa.istft(SNew)

def higyhpass(y,sr):
    S = librosa.stft(y)
    f = np.arange(S.shape[0])
    t = np.arange(S.shape[1])
    A = np.exp(t[None, :]*f[:, None]/(100*S.shape[1]))
    SNew = S*A
    p_bas= librosa.istft(SNew)

I get stuck on how to implement the low-cut and high-cut  frequency using the same algorithm of low-pass and high-pass

def band_pass(data, lowcut, highcut, fs, order=5):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='bandpass')
    filtered = lfilter(b, a, data)
    return filtered