问:
@EnableDiscoveryClient but not show in http://localhost:8761
I am using Spring Boot 3.0.0 for all 2 microservices.
First services for authorization:

File pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
        <relativePath/>
    </parent>
    <groupId>org.sid</groupId>
    <artifactId>security-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>security-service</name>
    <description>security-service</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-eureka-client</artifactId>
            <version>3.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-commons</artifactId>
            <version>3.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcpkix-jdk18on</artifactId>
            <version>1.72</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-commons</artifactId>
            <version>3.1.2</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
```
<p>File <code>application.yml</code></p>
<pre class="lang-yaml prettyprint-override"><code>spring:
  application:
      name: vy_auth
</code>```

File application.properties

```<code>server.port=9898
rsa.public-key=classpath:certs/public.pem
rsa.private-key=classpath:certs/private.pem
</code>```

package org.sid.securityservice;

import org.sid.securityservice.config.RsakeysConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@SpringBootApplication
@EnableConfigurationProperties(RsakeysConfig.class)
@EnableDiscoveryClient
public class SecurityServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityServiceApplication.class, args);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
```
<p>Eureka server has <code>pom.xml</code></p>
<pre class="lang-xml prettyprint-override"><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>com.example</groupId>
        <artifactId>vy_microservices</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>vy_discovery</artifactId>
    <name>vy_discovery</name>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-client</artifactId>
        </dependency>

        <!-- https://stackoverflow.com/a/31993406/3728901 -->

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>

        <!--<dependency>-->
        <!--    <groupId>org.springframework.cloud</groupId>-->
        <!--    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>-->
        <!--</dependency>-->

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
        <!--<dependency>-->
        <!--    <groupId>org.springframework.cloud</groupId>-->
        <!--    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>-->
        <!--    <version>2.2.10.RELEASE</version>-->
        <!--</dependency>-->

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

and

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

// @EnableEurekaServer must stand before @SpringBootApplication
// https://stackoverflow.com/a/50591790/3728901
@EnableEurekaServer
@SpringBootApplication
public class VyDiscovery {

    public static void main(String[] args) {
        SpringApplication.run(VyDiscovery.class);
    }

}
```
<p>File <code>application.yml</code></p>
<pre class="lang-yaml prettyprint-override"><code>spring:
    application:
        name: vy_discovery
server:
    port: 8761

eureka:
    client:
        register-with-eureka: false
        fetch-registry: false
</code>```

It does not show in Eureka

How to make service vy_auth can discoveried by Eureka success?

Body:
I am using Spring Boot 3.0.0 for all 2 microservices.
First services for authorization:

File pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
        <relativePath/>
    </parent>
    <groupId>org.sid</groupId>
    <artifactId>security-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>security-service</name>
    <description>security-service</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-eureka-client</artifactId>
            <version>3.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-commons</artifactId>
            <version>3.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcpkix-jdk18on</artifactId>
            <version>1.72</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-commons</artifactId>
            <version>3.1.2</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

File application.yml

spring:
  application:
      name: vy_auth

File application.properties

server.port=9898
rsa.public-key=classpath:certs/public.pem
rsa.private-key=classpath:certs/private.pem

package org.sid.securityservice;

import org.sid.securityservice.config.RsakeysConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@SpringBootApplication
@EnableConfigurationProperties(RsakeysConfig.class)
@EnableDiscoveryClient
public class SecurityServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityServiceApplication.class, args);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

Eureka server has pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>com.example</groupId>
        <artifactId>vy_microservices</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>vy_discovery</artifactId>
    <name>vy_discovery</name>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

and

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

// @EnableEurekaServer must stand before @SpringBootApplication
// https://stackoverflow.com/a/50591790/3728901
@EnableEurekaServer
@SpringBootApplication
public class VyDiscovery {

    public static void main(String[] args) {
        SpringApplication.run(VyDiscovery.class);
    }

}

File application.yml

spring:
    application:
        name: vy_discovery
server:
    port: 8761

eureka:
    client:
        register-with-eureka: false
        fetch-registry: false

It does not show in Eureka

How to make service vy_auth can discoveried by Eureka success?


来源: stackexchange

问:
CRISPR genome wide screen analysis using MAGeCK-- Loss of reads/sgRNA using MAGeCK count function?
I am trying to run the MAGeCK pipeline to analyze CRISPR knockout screen data produced by someone in my lab around 5 years ago. I was given the data as BAM files and also have the sequencing sample statistics from when the samples were run including the number of total reads, aligned reads, and unaligned reads. I converted the BAM files back to FASTQ files using

samtools view -h -F 2048 filename.bam > tmp.bam

bedtools bamtofastq -i tmp.bam -fq filename.fastq
```

After this, I ran the MAGeCK count function. I saw that none of the total reads matched between the MAGeCK count summary output file and the original sequencing statistics.

More problematically, a few samples had significantly fewer total reads (like 50,000) shown on the MAGeCK count summary output files relative to the original sequencing statistics (~44 million). As a result, many of the sgRNAs are not represented at all in the sample (there are ~61,000 zero counts relative to the total 77441 sgRNAs) which is impacting my analysis.

Can anyone help me understand why I might be losing sgRNAs using MAGeCK? Is it a problem with my source files? I would appreciate any help! Thanks!

I have tried re-downloading the bam files from the server and re-converting them to fastq-- I get the same result.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run the MAGeCK pipeline to analyze CRISPR knockout screen data produced by someone in my lab around 5 years ago. I was given the data as BAM files and also have the sequencing sample statistics from when the samples were run including the number of total reads, aligned reads, and unaligned reads. I converted the BAM files back to FASTQ files using

samtools view -h -F 2048 filename.bam > tmp.bam

bedtools bamtofastq -i tmp.bam -fq filename.fastq

After this, I ran the MAGeCK count function. I saw that none of the total reads matched between the MAGeCK count summary output file and the original sequencing statistics.

More problematically, a few samples had significantly fewer total reads (like 50,000) shown on the MAGeCK count summary output files relative to the original sequencing statistics (~44 million). As a result, many of the sgRNAs are not represented at all in the sample (there are ~61,000 zero counts relative to the total 77441 sgRNAs) which is impacting my analysis.

Can anyone help me understand why I might be losing sgRNAs using MAGeCK? Is it a problem with my source files? I would appreciate any help! Thanks!

I have tried re-downloading the bam files from the server and re-converting them to fastq-- I get the same result.


问:
ISOMAP with python (without libraries)
I want to calculate the eps and knn graphs for the ISOMAP problem.
I calculate the symmetric distance matrix D. But i don't know if there is a
I do not want to use any libraries. Only basic functionality from numpy etc.
For the distance matrix of the points i did not use floyd warshall, i just compare each point to another.
I don't understand the all-pairs-shortest-paths problem. It is the direct connection anyway, or do I miss anything?
I have no idea how to do the MDS transform (Gram matrix, EVD, data matrix)

My code:

```<code>import math
import numpy as np
#import sklearn as skl
from sklearn import manifold, datasets
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as po

swroll_points, swroll_color = datasets.make_swiss_roll(n_samples=800, random_state=np.random.seed(1234))

# ... works fine as it seems. Returns a symmetric distance matrix of 800x800
def distance(list):
  dist = 0
    D = np.empty((800, 800)) # empty array (800x800 matrix filled with zeros)
  for i in range(0, len(list)):
        pnt_this = list[i]

        for j in range(0, len(list)):
            pnt_other = list[j]
            dist = math.sqrt(
                (pnt_this[0] - pnt_other[0]) ** 2
                + (pnt_this[1] - pnt_other[1]) ** 2
                + (pnt_this[2] - pnt_other[2]) ** 2)

            D[i][j] = dist
  return D

def isomap_algo(data, type_, param_):
    #dist_matrix_sorted = sort_matrix(distance_matrix)
    D = distance(data) # step 1 in slides 13 page 16 (algo 13.4). D is distance_matrix

    if type_=="knn":
        W = isomap_knn(data, param_)
    elif type_=="eps":
        W = isomap_eps(data, param_)
    return W # 2d weights matrix W. contains all neighbors

def isomap_eps(D, eps): # D is distance_matrix
    for i in range(0, len(D)):
        for j in range(0, len(D)):
            if D[i][j] > eps:
                D[i][j] = np.inf
    W = D # renaming
    return W # weights matrix W

# TODO
#def isomap_knn(data, k): # D is distance_matrix
    #return W # weights matrix W
</code>```

I know. it is not finished, but is there a way to calculate
I got the error in the line D = distance(data) in the def of the function isomap_algo(data, type_, param_).

```<code>distance() missing 1 required positional argument: 'pnt_other'
</code>```

Should I use a list or dictionary for the epsilon neighborhood in the function isomap_eps(D, eps)
The function isomap_knn(data, k) has not been implemented at all.

Thanks!

Title: ISOMAP with python (without libraries)

Body:
I want to calculate the eps and knn graphs for the ISOMAP problem.
I calculate the symmetric distance matrix D. But i don't know if there is a
I do not want to use any libraries. Only basic functionality from numpy etc.
For the distance matrix of the points i did not use floyd warshall, i just compare each point to another.
I don't understand the all-pairs-shortest-paths problem. It is the direct connection anyway, or do I miss anything?
I have no idea how to do the MDS transform (Gram matrix, EVD, data matrix)

My code:

import math
import numpy as np
#import sklearn as skl
from sklearn import manifold, datasets
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as po

swroll_points, swroll_color = datasets.make_swiss_roll(n_samples=800, random_state=np.random.seed(1234))

# ... works fine as it seems. Returns a symmetric distance matrix of 800x800
def distance(list):
  dist = 0
    D = np.empty((800, 800)) # empty array (800x800 matrix filled with zeros)
  for i in range(0, len(list)):
        pnt_this = list[i]

        for j in range(0, len(list)):
            pnt_other = list[j]
            dist = math.sqrt(
                (pnt_this[0] - pnt_other[0]) ** 2
                + (pnt_this[1] - pnt_other[1]) ** 2
                + (pnt_this[2] - pnt_other[2]) ** 2)

            D[i][j] = dist
  return D

def isomap_algo(data, type_, param_):
    #dist_matrix_sorted = sort_matrix(distance_matrix)
    D = distance(data) # step 1 in slides 13 page 16 (algo 13.4). D is distance_matrix

    if type_=="knn":
        W = isomap_knn(data, param_)
    elif type_=="eps":
        W = isomap_eps(data, param_)
    return W # 2d weights matrix W. contains all neighbors

def isomap_eps(D, eps): # D is distance_matrix
    for i in range(0, len(D)):
        for j in range(0, len(D)):
            if D[i][j] > eps:
                D[i][j] = np.inf
    W = D # renaming
    return W # weights matrix W

# TODO
#def isomap_knn(data, k): # D is distance_matrix
    #return W # weights matrix W

I know. it is not finished, but is there a way to calculate
I got the error in the line D = distance(data) in the def of the function isomap_algo(data, type_, param_).

distance() missing 1 required positional argument: 'pnt_other'

Should I use a list or dictionary for the epsilon neighborhood in the function isomap_eps(D, eps)
The function isomap_knn(data, k) has not been implemented at all.

Thanks!


问:
Creating C++ shared libraries with class interfaces Windows vs. Posix
True class interfaces in C++ libraries on Windows are not exactly simple: either you restrict users of your library to a certain range of compilers (or rather: Visual-Studio suites) which happen to run the absolutely identical name-mangling, EABI and object layout (no idea how restrictive this is in reality) or you use COM (following this article) and pure virtual interface classes.

I tried to assess the situation on Linux/Posix where the range of available compilers is larger and I therefore also thought, the problem of creating shared libraries with stable interface, but to my surprise it is much harder to investigate if there is an issue or if Posix has defined a compatibility layer so that no one needs to care anymore.

Can someone give a short explanation of how the status of this problem really is, on both platforms?

Or point out where and why I am misinterpreting the whole affair?

EDIT: there is already a question with excellent answers detailing most of my issues: How do I safely pass objects, especially STL objects, to and from a DLL?


问:
Terminal not clearing
I am trying to clear the terminal but the terminal isn't clearing, instead a character of some sort is inserted into the terminal. What other methods can i use to clear the terminal?

OS: Windows 10

IDE: Pycharm latest version

```<code>import os

while True:
    date = input("\nEnter the date (dd/mm/yyyy): ")
    direction = input("\nEnter trade direction (buy, sell): ")
    lotsize = float(input("\nEnter lotsize: "))
    entry = float(input("\nEnter entry price: "))
    profit = float(input("\nEnter take profit price: "))
    loss = float(input("\nEnter stop loss price: "))
    outcome = input("\nEnter the result (loss/win): ")

    with open(file="data.csv", mode="a") as file:
        data = f"\n{date}, {direction}, {outcome}, {lotsize}, {entry}, {profit}, {loss}"
        file.write(data)
        os.system("cls")
</code>```

Title: Terminal not clearing

Body:
I am trying to clear the terminal but the terminal isn't clearing, instead a character of some sort is inserted into the terminal. What other methods can i use to clear the terminal?

OS: Windows 10

IDE: Pycharm latest version

import os

while True:
    date = input("\nEnter the date (dd/mm/yyyy): ")
    direction = input("\nEnter trade direction (buy, sell): ")
    lotsize = float(input("\nEnter lotsize: "))
    entry = float(input("\nEnter entry price: "))
    profit = float(input("\nEnter take profit price: "))
    loss = float(input("\nEnter stop loss price: "))
    outcome = input("\nEnter the result (loss/win): ")

    with open(file="data.csv", mode="a") as file:
        data = f"\n{date}, {direction}, {outcome}, {lotsize}, {entry}, {profit}, {loss}"
        file.write(data)
        os.system("cls")


问:
Get-ItemProperty with wildcard; results as array
Given a registry key of

```<code>registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey
</code>```

and text properties called TestString1, TestString2 & NotValid

I can use

```<code>Get-ItemProperty -path:"registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey" -name:"TestString*"
</code>```

and I will get back

```<code>TestString1  : One
TestString2  : Two
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE
PSChildName  : TestKey
PSProvider   : Microsoft.PowerShell.Core\Registry
</code>```

But what I want is an array of just the two properties who's names match the wildcard.

```<code>Get-ItemProperty -path:"registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey" -name:"TestString*" | Get-Member
</code>```

produces

```<code>Name         MemberType   Definition
----         ----------   ----------
Equals       Method       bool Equals(System.Object obj)
GetHashCode  Method       int GetHashCode()
GetType      Method       type GetType()
ToString     Method       string ToString()
PSChildName  NoteProperty string PSChildName=TestKey
PSParentPath NoteProperty string PSParentPath=Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE
PSPath       NoteProperty string PSPath=Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey
PSProvider   NoteProperty ProviderInfo PSProvider=Microsoft.PowerShell.Core\Registry
TestString1  NoteProperty string TestString1=One
TestString2  NoteProperty string TestString2=Two
</code>```

which makes me think

```<code>Get-ItemProperty -path:"registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey" -name:"TestString*" | Where-Object ({$_.Name -like "TestString*"})
</code>```

should do what I want, but it actually returns nothing. What am I missing here?

EDIT: OK, this is weird. And I guess typical Microsoft "thinking". If I actually have a property called TestString*, which is a perfectly valid name, because Microsoft is never consistent, the code above returns all three, plus the other stuff. But, if I change the -Path to -LiteralPath, then I only get the one -Name. Which is... crazy. I have never seen any documentation saying that -LiteralPath also makes -Name behave like -LiteralName.

Body:
Given a registry key of

registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey

and text properties called TestString1, TestString2 & NotValid

I can use

Get-ItemProperty -path:"registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey" -name:"TestString*"

and I will get back

TestString1  : One
TestString2  : Two
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE
PSChildName  : TestKey
PSProvider   : Microsoft.PowerShell.Core\Registry

But what I want is an array of just the two properties who's names match the wildcard.

Get-ItemProperty -path:"registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey" -name:"TestString*" | Get-Member

produces

Name         MemberType   Definition
----         ----------   ----------
Equals       Method       bool Equals(System.Object obj)
GetHashCode  Method       int GetHashCode()
GetType      Method       type GetType()
ToString     Method       string ToString()
PSChildName  NoteProperty string PSChildName=TestKey
PSParentPath NoteProperty string PSParentPath=Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE
PSPath       NoteProperty string PSPath=Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey
PSProvider   NoteProperty ProviderInfo PSProvider=Microsoft.PowerShell.Core\Registry
TestString1  NoteProperty string TestString1=One
TestString2  NoteProperty string TestString2=Two

which makes me think

Get-ItemProperty -path:"registry::HKEY_LOCAL_MACHINE\SOFTWARE\TestKey" -name:"TestString*" | Where-Object ({$_.Name -like "TestString*"})

should do what I want, but it actually returns nothing. What am I missing here?

EDIT: OK, this is weird. And I guess typical Microsoft "thinking". If I actually have a property called TestString*, which is a perfectly valid name, because Microsoft is never consistent, the code above returns all three, plus the other stuff. But, if I change the -Path to -LiteralPath, then I only get the one -Name. Which is... crazy. I have never seen any documentation saying that -LiteralPath also makes -Name behave like -LiteralName.


问:
change comma to dot in c string
I want to change the ',' of the string and put a '.' at the place

```<code>unsigned long GetStringLength(const char* InString){
    if(InString[0] == 0) return 1;
    return 1 + GetStringLength(InString + 1);
}
</code>```
```<code>int main(){
    char text[] = "11,573";
    int size = GetStringLength(text);
    char *new_String = calloc(GetStringLength(text), sizeof(char));

    for(int i = 0; i < size; i++){
        if(text[i] == ','){ // 46 = .
            new_String[i] == '.';
        }else{
            new_String[i] = text[i]; // 44 = ,
        }
    }

    for(int i = 0; i<size; i++){
        printf("%c", new_String[i]);
    }

    return 0;
}
</code>```

but I get 11573 instead of 11.573

I want to do this, because I want to take decimal numbers from a string to add them and the atof function I couldn't get it to work with strings with ','

Title: change comma to dot in c string

Body:
I want to change the ',' of the string and put a '.' at the place

unsigned long GetStringLength(const char* InString){
    if(InString[0] == 0) return 1;
    return 1 + GetStringLength(InString + 1);
}

int main(){
    char text[] = "11,573";
    int size = GetStringLength(text);
    char *new_String = calloc(GetStringLength(text), sizeof(char));

    for(int i = 0; i < size; i++){
        if(text[i] == ','){ // 46 = .
            new_String[i] == '.';
        }else{
            new_String[i] = text[i]; // 44 = ,
        }
    }

    for(int i = 0; i<size; i++){
        printf("%c", new_String[i]);
    }

    return 0;
}

but I get 11573 instead of 11.573

I want to do this, because I want to take decimal numbers from a string to add them and the atof function I couldn't get it to work with strings with ','


问:
Nginx does not host other pages than index.html
I've set up Nginx and I'm able to host the index page, the index page contains links to other pages in the same directory, but when you go through the links you get a 404 not found error, in the address bar it has the correct path.

Is the something else in the Nginx sites-enabled default file I'm supposed to change?


问:
What type should I assign to a function that takes text from an input and writes it to a variable through a useState?
I have the following function in App.tsx:

```<code>  const [myTxt, setMyTxt] = useState<string>('');

  const getTxt: React.MouseEventHandler | React.KeyboardEventHandler = (e: any): void => {
    e.preventDefault();
    const target = e.target;
    setMyTxt(target.city.value.trim());

  };
</code>```

It takes the value from the input form (component SearchPanel.tsx, created with MUI):

```<code>const SearchPanel: React.FC<SearchPanelProps> = ({ getTxt }) => {

        <Box
            component="form"
            onSubmit={getTxt}
        >
            <TextField
                size='small'
                type="text"
                name='city'
                placeholder='Enter city'
            />
            <Button

                type="submit"
            >
                Press here to search
            </Button>
        </Box>

}
</code>```

I create a props type in which I describe a function:

```<code>export type SearchPanelProps = {
  getTxt: React.MouseEventHandler | React.KeyboardEventHandler
}
</code>```

Then I pass the function as a props to another component:

```<code>      <SearchPanel
        getTxt={getTxt}
      />
</code>```

And I see error: "No overload matches this call".

So I have questions, one dependent on the other.

What type should I assign to a function that takes text from an input and writes it to a variable through a useState, and how pass the function as a props?

What type should I assign to the event? I don't want use 'any', it's a bad practice.

Is there an easier way to take the value of a text field to pass to the function than mine?

Body:
I have the following function in App.tsx:

  const [myTxt, setMyTxt] = useState<string>('');

  const getTxt: React.MouseEventHandler | React.KeyboardEventHandler = (e: any): void => {
    e.preventDefault();
    const target = e.target;
    setMyTxt(target.city.value.trim());

  };

It takes the value from the input form (component SearchPanel.tsx, created with MUI):

const SearchPanel: React.FC<SearchPanelProps> = ({ getTxt }) => {

        <Box
            component="form"
            onSubmit={getTxt}
        >
            <TextField
                size='small'
                type="text"
                name='city'
                placeholder='Enter city'
            />
            <Button

                type="submit"
            >
                Press here to search
            </Button>
        </Box>

}

I create a props type in which I describe a function:

export type SearchPanelProps = {
  getTxt: React.MouseEventHandler | React.KeyboardEventHandler
}

Then I pass the function as a props to another component:

      <SearchPanel
        getTxt={getTxt}
      />

And I see error: "No overload matches this call".

So I have questions, one dependent on the other.

What type should I assign to a function that takes text from an input and writes it to a variable through a useState, and how pass the function as a props?

What type should I assign to the event? I don't want use 'any', it's a bad practice.

Is there an easier way to take the value of a text field to pass to the function than mine?


问:
Power BI Embed Token obtained using Profile causing Angular component to not display report properly
I have built a simple angular app to demonstrate Power BI Embedded, using the "embed for your customers" model, and Microsoft's powerbi-client-angular module.

I have a backend project which authenticates against Azure Active Directory using Service Principal credentials to get an access token, and then uses the Microsoft.PowerBI.Api libraries to generate an embed token.  It gives the embedding details (report id, embed url and embed token) to the front-end angular app which uses Microsoft's angular module to embed the report.

It works just fine if I get it to embed a report uploaded into my own Power BI Workspace.

However, if I get it to embed a report which is owned by a Service Principal Profile (we are using the Power BI Embedded multi-tenancy solution approach) I can obtain a token just fine, but the angular module fails to display the report properly.  The embedding iframe renders, and there's a spinning "Loading data ..." graphic and the expected "This is a free trial version, to remove this label a capacity must be purchased" banner at the top, but the report visuals do not appear.

In the browser developer tools I can see that one of the Power BI Rest API calls that the angular compenent is making is failing with a 403 (Forbidden) error ...

Dev tools screenshot showing 403 response

Given the 403 error I wonder if there's a problem with the way I'm obtaining the embed token.  The code for that is as follows:

`

```<code>/*
* Sign into AAD with Service Principal cred to get access token
* Obviously in real product the service principal details wil need to come from
* Key Vault / Tenant Managment rather than app.settings
*/
var app = ConfidentialClientApplicationBuilder.Create(_config["ServicePrincipal:ClientId"])
    .WithClientSecret(_config["ServicePrincipal:ClientSecret"])
    .WithAuthority(new Uri(_config["ServicePrincipal:Authority"]))
    .Build();

var scopes = new string[] { _config["ServicePrincipal:Scope"] };
var authResponse = await app.AcquireTokenForClient(scopes).ExecuteAsync();

/*
* Get Report name, profile id, and workspace id from settings
* Again, in real product these will come from Tenant Management rather than app.settings
*/
var reportName = _config["PowerBI:EmbeddedReportName"];
var workspaceId = new Guid(_config["PowerBI:workspaceId"]);
var profileId = new Guid(_config["PowerBI:profileId"]);
Report powerBIReport = null;

/*
* Create a Power BI Client
*/
var tokenCredentials = new TokenCredentials(authResponse.AccessToken, "Bearer");
//var powerBIClient = new PowerBIClient(new Uri(_config["PowerBI:ApiUrl"]), tokenCredentials);
var powerBIClient = new PowerBIClient(new Uri(_config["PowerBI:ApiUrl"]), tokenCredentials, profileObjectId: profileId);

/*
* Get the reports in Workspace
*/
var reports = powerBIClient.Reports.GetReportsInGroup(workspaceId);

/*
* Find the report matching the name we want to embed
*/
foreach (var report in reports.Value) {
    if (report.Name == reportName)
    {
        powerBIReport = report;
        break;
    }
}

/*
* Get embed token for the report
*/
var tokenRequest = new GenerateTokenRequest(accessLevel: TokenAccessLevel.View, datasetId: powerBIReport.DatasetId.ToString(), allowSaveAs: false);
var embedToken = powerBIClient.Reports.GenerateTokenInGroup(workspaceId, powerBIReport.Id, tokenRequestV1);

/*
* Return the details the Angular component needs to do the embedding
*/
return new ReportConfig
{
    Id = powerBIReport.Id.ToString(),
    EmbedToken = new EmbedToken(embedToken),
    EmbedUrl = powerBIReport.EmbedUrl
};
</code>```

`

The report rendering looks like this - you can see that the Power BI Filters box on the right has rendered, and that can be shown/hidden using the chevron icon, and there are Filter/Focus Mode icons in the report body matching where they ought to be for the visuals that ought to be in the report.  There should be three visualisations, and as you mouse-over the report, three sets of Filter/Focus Mode icons show and hide for the appropriate part of the report that the mouse pointer is over.

So something is being rendered, just not properly.

Broken Embedded report

Body:
I have built a simple angular app to demonstrate Power BI Embedded, using the "embed for your customers" model, and Microsoft's powerbi-client-angular module.

I have a backend project which authenticates against Azure Active Directory using Service Principal credentials to get an access token, and then uses the Microsoft.PowerBI.Api libraries to generate an embed token.  It gives the embedding details (report id, embed url and embed token) to the front-end angular app which uses Microsoft's angular module to embed the report.

It works just fine if I get it to embed a report uploaded into my own Power BI Workspace.

However, if I get it to embed a report which is owned by a Service Principal Profile (we are using the Power BI Embedded multi-tenancy solution approach) I can obtain a token just fine, but the angular module fails to display the report properly.  The embedding iframe renders, and there's a spinning "Loading data ..." graphic and the expected "This is a free trial version, to remove this label a capacity must be purchased" banner at the top, but the report visuals do not appear.

In the browser developer tools I can see that one of the Power BI Rest API calls that the angular compenent is making is failing with a 403 (Forbidden) error ...

Dev tools screenshot showing 403 response

Given the 403 error I wonder if there's a problem with the way I'm obtaining the embed token.  The code for that is as follows:

`

/*
* Sign into AAD with Service Principal cred to get access token
* Obviously in real product the service principal details wil need to come from
* Key Vault / Tenant Managment rather than app.settings
*/
var app = ConfidentialClientApplicationBuilder.Create(_config["ServicePrincipal:ClientId"])
    .WithClientSecret(_config["ServicePrincipal:ClientSecret"])
    .WithAuthority(new Uri(_config["ServicePrincipal:Authority"]))
    .Build();

var scopes = new string[] { _config["ServicePrincipal:Scope"] };
var authResponse = await app.AcquireTokenForClient(scopes).ExecuteAsync();

/*
* Get Report name, profile id, and workspace id from settings
* Again, in real product these will come from Tenant Management rather than app.settings
*/
var reportName = _config["PowerBI:EmbeddedReportName"];
var workspaceId = new Guid(_config["PowerBI:workspaceId"]);
var profileId = new Guid(_config["PowerBI:profileId"]);
Report powerBIReport = null;

/*
* Create a Power BI Client
*/
var tokenCredentials = new TokenCredentials(authResponse.AccessToken, "Bearer");
//var powerBIClient = new PowerBIClient(new Uri(_config["PowerBI:ApiUrl"]), tokenCredentials);
var powerBIClient = new PowerBIClient(new Uri(_config["PowerBI:ApiUrl"]), tokenCredentials, profileObjectId: profileId);

/*
* Get the reports in Workspace
*/
var reports = powerBIClient.Reports.GetReportsInGroup(workspaceId);

/*
* Find the report matching the name we want to embed
*/
foreach (var report in reports.Value) {
    if (report.Name == reportName)
    {
        powerBIReport = report;
        break;
    }
}

/*
* Get embed token for the report
*/
var tokenRequest = new GenerateTokenRequest(accessLevel: TokenAccessLevel.View, datasetId: powerBIReport.DatasetId.ToString(), allowSaveAs: false);
var embedToken = powerBIClient.Reports.GenerateTokenInGroup(workspaceId, powerBIReport.Id, tokenRequestV1);

/*
* Return the details the Angular component needs to do the embedding
*/
return new ReportConfig
{
    Id = powerBIReport.Id.ToString(),
    EmbedToken = new EmbedToken(embedToken),
    EmbedUrl = powerBIReport.EmbedUrl
};

`

The report rendering looks like this - you can see that the Power BI Filters box on the right has rendered, and that can be shown/hidden using the chevron icon, and there are Filter/Focus Mode icons in the report body matching where they ought to be for the visuals that ought to be in the report.  There should be three visualisations, and as you mouse-over the report, three sets of Filter/Focus Mode icons show and hide for the appropriate part of the report that the mouse pointer is over.

So something is being rendered, just not properly.

Broken Embedded report


问:
Why are my GA4 UI total users not adding up with the ones in the BigQuery export?
I am trying to recreate the Google analytics 4 data in BigQuery for reporting. I’m trying to count total users by using the following query

```<code>SELECT
count(distinct user_pseudo_id) as total_users
FROM `project.dataset.events_*`
WHERE _table_suffix = “20221201”
</code>```

Problem is that for any given day, I get around 10-15% LESS total users than I see in the GA4 interface. Why can this be?

I tried Googleing but it didn’t make me any wiser. Anyone has had the same problem?

Body:
I am trying to recreate the Google analytics 4 data in BigQuery for reporting. I’m trying to count total users by using the following query

SELECT
count(distinct user_pseudo_id) as total_users
FROM `project.dataset.events_*`
WHERE _table_suffix = “20221201”

Problem is that for any given day, I get around 10-15% LESS total users than I see in the GA4 interface. Why can this be?

I tried Googleing but it didn’t make me any wiser. Anyone has had the same problem?


问:
Android dokka multi project documentation
I just start using Dokka for Android app documentation. This is the issue I'm facing:

I tried dokkaHtml and dokkaHtml multi. which both are great for single module and multi module documentation, BUT we would like to generate a main dokka "website" which will refer to multi application so centralize the documentation of all application repository into a single one (using ci/cd) or something like that, so I will have the multi-module UI of dokka but for multiple application.

Is there any possibility to do this?


问:
Subtotal plus limiting data set
I'm brand-spakin' new to SQL and was asked to help write a query for a report. I need to limit the data to the last 10 services done by a clinician, and then subtotal the difference between the two times (time in and out) for each clinician.
I'm guessing I need to do a "LIMIT" clause to limit the data, but I'm not sure how or where to put that information. I am also thinking I need to use "GROUP BY", but not positive on that either. Any help would be appreciated.

I tried simplifying the existing query that my boss started but I'm getting error messages about the GROUP BY clause because I don't have an aggregate.

```<code>Select CV.emp_name,
  CV.Visittype,
  CVt.clientvisit_id,
  CV.client_id,
  CV.rev_timein,
  CV.rev_timeout,
  Convert(varchar(25),Cast(CV.rev_timein As Time),8) As Start_Time,
  CV.program_id,
  CV.cptcode
From ClientVisit CV
Where CV.visittype = 'Mobile Therapy' And CV.program_id = 31
  And CV.cptcode <> 'NB' And CV.rev_timein <=
  Convert(datetime,IsNull(@param2, GetDate())) And CV.rev_timein >=
  Convert(datetime,IsNull(@param1, GetDate())) And
  Cast(CV.rev_timein As time) > '15:59'
Group By CV.emp_name,
  CV.rev_timein
</code>```

Title: Subtotal plus limiting data set

Body:
I'm brand-spakin' new to SQL and was asked to help write a query for a report. I need to limit the data to the last 10 services done by a clinician, and then subtotal the difference between the two times (time in and out) for each clinician.
I'm guessing I need to do a "LIMIT" clause to limit the data, but I'm not sure how or where to put that information. I am also thinking I need to use "GROUP BY", but not positive on that either. Any help would be appreciated.

I tried simplifying the existing query that my boss started but I'm getting error messages about the GROUP BY clause because I don't have an aggregate.

Select CV.emp_name,
  CV.Visittype,
  CVt.clientvisit_id,
  CV.client_id,
  CV.rev_timein,
  CV.rev_timeout,
  Convert(varchar(25),Cast(CV.rev_timein As Time),8) As Start_Time,
  CV.program_id,
  CV.cptcode
From ClientVisit CV
Where CV.visittype = 'Mobile Therapy' And CV.program_id = 31
  And CV.cptcode <> 'NB' And CV.rev_timein <=
  Convert(datetime,IsNull(@param2, GetDate())) And CV.rev_timein >=
  Convert(datetime,IsNull(@param1, GetDate())) And
  Cast(CV.rev_timein As time) > '15:59'
Group By CV.emp_name,
  CV.rev_timein


问:
Error message in MySQL Workbench: 'local instance 3306 - warning - not supported' what does this mean?
I am very new to using MySQL Workbench. I have just noticed the error message as stated above. I have inserted a screenshot of it.

error message screenshot

Honestly I am not too sure what to try - as like I said I have not used this before so am very new to the application. However, looking at XAMPP manager, it does say that MySQL is running, and using port 3306.

screenshot of servers


问:
Make Pycharm use double quotation marks and not one in the console
I am trying to figure out how to configure Pycharm to use " and not ' when printing to console.

I've checked it, and it doesn't matter what I am using in the code itself, even if it is:

print({"Hello World": "Great!"})
```
<p>It shows up like:</p>
```{'Hello World': 'Great!'}
```
<p>and not</p>
```{"Hello World": "Great!"}
```

As desired, I need this because when I want to format a long dictionary and view it as a nice indented JSON (and not a long line), it doesn't work as it is not a valid JSON as it uses the single quotation mark.

Any ideas? Thanks!

Body:
I am trying to figure out how to configure Pycharm to use " and not ' when printing to console.

I've checked it, and it doesn't matter what I am using in the code itself, even if it is:

print({"Hello World": "Great!"})

It shows up like:

{'Hello World': 'Great!'}

and not

{"Hello World": "Great!"}

As desired, I need this because when I want to format a long dictionary and view it as a nice indented JSON (and not a long line), it doesn't work as it is not a valid JSON as it uses the single quotation mark.

Any ideas? Thanks!


问:
Counterfeiting and protection of high-value products using secure cryptoprocessors of smart cards
I need advice on basic approach, technologies, standards, libraries if any (private interest, no professional development project).

Suppose I have high value items (rare bottles of old single malt whisky, luxury watches ...) with a unique number, but without further physical protection against counterfeiting (no data matrix code on a watch!). I want to strengthen anti-counterfeiting by using - together with each item - a smartcard that cannot be fully copied or counterfeited.

Use case

The item is manufactured. The data for the item include a unique number and a production time stamp (plus further data like production site ...). At / after completion, a) the unique number is printed on the item, b) appropriate data is stored in a central IT / database, and c) some data is stored on a smart card.

In case of purchase / sale, the smartcard i.e. the stored data is used to determine whether the card matches the item. If the card is counterfeited-proof, this also ensures the counterfeited-proofness of the pair "item + card".

Solution sketch

Production and baptism of item and card: The IT backbone implements a cryptographic hash function

```<code>h1 = Hash1(ts, pk)
</code>```

From the timestamp ts and a private key pk this function generates a hash value h1 which is stored in a database. The card also implements a cryptographic hash function

```<code>h2 = Hash2(h1, _i)
</code>```

This function returns a hash value h2 which is stored on the card; it uses the card-internal, non-copyable and non-modifiable unique ID _i, .

Authentication: During an authentication check, a serial number sx is read from the item or from the card (they must match). The IT supplies the hash value hx1 associated with the serial number sx (that must not fail)

```<code>hx1 = GetHash(sx)
</code>```

to the card which generates the second hash and compares it with the stored hash value h2

```<code>return (h2 == Hash2(hx1, _i))
</code>```

If the two hashes match, the pair "item + card" is considered not counterfeited.

Notes:
The card can only be accessed via dedicated functions; direct access to the data is impossible; the unique ID _i of each smartcard cannot be read or changed; the original data sn, ts cannot be reconstructed from the data exchanged between the card and IT, i.e. from  the hash values; any private key pk that may be required never leaves the IT.

Questions

Are these ideas basically going in the right direction?
Are there standards for hash functions, protocols, cryptoprocessors on smartcards and their services or interfaces?

Body:
I need advice on basic approach, technologies, standards, libraries if any (private interest, no professional development project).

Suppose I have high value items (rare bottles of old single malt whisky, luxury watches ...) with a unique number, but without further physical protection against counterfeiting (no data matrix code on a watch!). I want to strengthen anti-counterfeiting by using - together with each item - a smartcard that cannot be fully copied or counterfeited.

Use case

The item is manufactured. The data for the item include a unique number and a production time stamp (plus further data like production site ...). At / after completion, a) the unique number is printed on the item, b) appropriate data is stored in a central IT / database, and c) some data is stored on a smart card.

In case of purchase / sale, the smartcard i.e. the stored data is used to determine whether the card matches the item. If the card is counterfeited-proof, this also ensures the counterfeited-proofness of the pair "item + card".

Solution sketch

Production and baptism of item and card: The IT backbone implements a cryptographic hash function

h1 = Hash1(ts, pk)

From the timestamp ts and a private key pk this function generates a hash value h1 which is stored in a database. The card also implements a cryptographic hash function

h2 = Hash2(h1, _i)

This function returns a hash value h2 which is stored on the card; it uses the card-internal, non-copyable and non-modifiable unique ID _i, .

Authentication: During an authentication check, a serial number sx is read from the item or from the card (they must match). The IT supplies the hash value hx1 associated with the serial number sx (that must not fail)

hx1 = GetHash(sx)

to the card which generates the second hash and compares it with the stored hash value h2

return (h2 == Hash2(hx1, _i))

If the two hashes match, the pair "item + card" is considered not counterfeited.

Notes:
The card can only be accessed via dedicated functions; direct access to the data is impossible; the unique ID _i of each smartcard cannot be read or changed; the original data sn, ts cannot be reconstructed from the data exchanged between the card and IT, i.e. from  the hash values; any private key pk that may be required never leaves the IT.

Questions

Are these ideas basically going in the right direction?
Are there standards for hash functions, protocols, cryptoprocessors on smartcards and their services or interfaces?


问:
Typescript - Create Type for dynamic keys
I have written a ts type for typechecking my code and Im facing few issues. Here is my type and sample data..

TYPE:

```<code>type TObjectsFieldsMap = {
  [objectName: string]: {
    _chosen: boolean; // ERROR 1
    [fieldName: string]?: { // ERROR 2 when fieldName is made optional
       _chosen: boolean; // ERROR 3
    };
  };
};
</code>```

Errors of above ts type:

```<code>1. '_chosen' of type 'boolean' is not assignable to 'string' index type '{ chosen: boolean; }'

2. Property or signature expected. (this is occurring when adding "[fieldname: string]" as optional(?:)

3. 'boolean' only refers to a type, but is being used as a value here.
</code>```

sample data:

```<code>{
  dynamicObj1: {
    _chosen: true,
    dyanmicField11: {
       _chosen: false
    },
    dyanmicField12: {
       _chosen: true
    }
  },
  dynamicObj2: {
    _chosen: false,
    dyanmicField21: {
       _chosen: false
    }
  },
  dynamicObj3: {
    _chosen: false,
  }
}
</code>```

It would be grateful, if someone points the error and its reasons and it will a good learning curve for me.. TIA !

Body:
I have written a ts type for typechecking my code and Im facing few issues. Here is my type and sample data..

TYPE:

type TObjectsFieldsMap = {
  [objectName: string]: {
    _chosen: boolean; // ERROR 1
    [fieldName: string]?: { // ERROR 2 when fieldName is made optional
       _chosen: boolean; // ERROR 3
    };
  };
};

Errors of above ts type:

1. '_chosen' of type 'boolean' is not assignable to 'string' index type '{ chosen: boolean; }'

2. Property or signature expected. (this is occurring when adding "[fieldname: string]" as optional(?:)

3. 'boolean' only refers to a type, but is being used as a value here.

sample data:

{
  dynamicObj1: {
    _chosen: true,
    dyanmicField11: {
       _chosen: false
    },
    dyanmicField12: {
       _chosen: true
    }
  },
  dynamicObj2: {
    _chosen: false,
    dyanmicField21: {
       _chosen: false
    }
  },
  dynamicObj3: {
    _chosen: false,
  }
}

It would be grateful, if someone points the error and its reasons and it will a good learning curve for me.. TIA !


问:
How to change position of shapes in kivy
i need to move the position of my shapes. In images or box/float layouts, I use pos_hint: {"center_x":number, "center_y":number}, and it's very useful because it's responsive, but in Rectangle or Ellipse I use pos: (number,number). This is not responsive and my app doesn't work well on other mobiles. How can I move them correctly?</p>


问:
i write a jquery code but it doesnt work as i expected
I want when I click on add to add an elements in the .items and then when I click "remove" remove it but it doesn't work

$('.add').on('click', function () {
      $('.items').append('remove');
});
$('.rmv').on('click', function() {
       $(this).remove();
});
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="items"></div>
<div>
   <span class="add">add</span>
</div></code>```

Body:
I want when I click on add to add an elements in the .items and then when I click "remove" remove it but it doesn't work

$('.add').on('click', function () {
      $('.items').append('remove');
});
$('.rmv').on('click', function() {
       $(this).remove();
});

   add


问:
Job trigger not pushing at set time
Created a script to set a desktop background at 4pm but the scheduled job isn't running at 4pm. The end result I'll need it to run on a monthly basis to change the background but currently cannot get the conditions to run whilst testing</p>
```<code>$Trigger = New-JobTrigger -Daily -At "4:00pm"
Register-ScheduledJob -Trigger $Trigger -RunAs32 -ScriptBlock {

Invoke-WebRequest -Uri "templink" -UseBasicParsing -OutFile "C:/Users/Public/Wallpaper.jpg"

$MyWallpaper="C:\Users\Public\Wallpaper.jpg"
$code = @'
using System.Runtime.InteropServices;
namespace Win32{

     public class Wallpaper{
        [DllImport("user32.dll", CharSet=CharSet.Auto)]
         static extern int SystemParametersInfo (int uAction , int uParam , string lpvParam , int fuWinIni) ;

         public static void SetWallpaper(string thePath){
            SystemParametersInfo(20,0,thePath,3);
         }
    }
 }
'@

add-type $code
[Win32.Wallpaper]::SetWallpaper($MyWallpaper)
} -Name Wallpaper

</code>```

Title: Job trigger not pushing at set time

Body:
Created a script to set a desktop background at 4pm but the scheduled job isn't running at 4pm. The end result I'll need it to run on a monthly basis to change the background but currently cannot get the conditions to run whilst testing

$Trigger = New-JobTrigger -Daily -At "4:00pm"
Register-ScheduledJob -Trigger $Trigger -RunAs32 -ScriptBlock {

Invoke-WebRequest -Uri "templink" -UseBasicParsing -OutFile "C:/Users/Public/Wallpaper.jpg"

$MyWallpaper="C:\Users\Public\Wallpaper.jpg"
$code = @'
using System.Runtime.InteropServices;
namespace Win32{

     public class Wallpaper{
        [DllImport("user32.dll", CharSet=CharSet.Auto)]
         static extern int SystemParametersInfo (int uAction , int uParam , string lpvParam , int fuWinIni) ;

         public static void SetWallpaper(string thePath){
            SystemParametersInfo(20,0,thePath,3);
         }
    }
 }
'@

add-type $code
[Win32.Wallpaper]::SetWallpaper($MyWallpaper)
} -Name Wallpaper


问:
selecting files from directory using rsync
I want to download some files from a server using rsync. I am able to download (e.g. "00/")a complete directory using the code: `

```<code>rsync -rlptzv --include '00' --exclude '*/' --delete --port=33444 rsync.wwpdb.org::ftp/data/biounit/PDB/divided/ /scratch/
</code>```

I am getting stuck when I try to download a file (e.g. 100d.pdb1.gz) from the "00" folder. I have tried adding the file name as full to the path on the server but that did not work:

```<code>rsync -rlptzv --include '00/100d.pdb1.gz' --exclude '*/' --delete --port=33444 rsync.wwpdb.org::ftp/data/biounit/PDB/divided/ /scratch/pdb_download/datasets/pdb/rcsb/
</code>```

Body:
I want to download some files from a server using rsync. I am able to download (e.g. "00/")a complete directory using the code: `

rsync -rlptzv --include '00' --exclude '*/' --delete --port=33444 rsync.wwpdb.org::ftp/data/biounit/PDB/divided/ /scratch/

I am getting stuck when I try to download a file (e.g. 100d.pdb1.gz) from the "00" folder. I have tried adding the file name as full to the path on the server but that did not work:

rsync -rlptzv --include '00/100d.pdb1.gz' --exclude '*/' --delete --port=33444 rsync.wwpdb.org::ftp/data/biounit/PDB/divided/ /scratch/pdb_download/datasets/pdb/rcsb/


问:
Improving my clustering for my dataset and changing my clusters to better reflect my data
Image of clusters

So I think this is somewhat self-explanatory but my clusters don't really make sense. I am new to clustering and just want these datapoints to be grouped together. The problem I keep seeing is the black is being clustered over 2 distinct lines and I want them to be seperate. I am plotting weather radar over the united states and just want to have lines of storms a unique cluster and eventually remove any random super small groups, not near the lines. I tried to just add more clusters and adjust the algorithm, but nothing has been working.

Here is my code:

```<code>nc = 8
kmeans = KMeans(n_clusters = nc, init ='k-means++',n_init=1,algorithm='full')
kmeans.fit(X[X.columns[1:nc]]) # Compute k-means clustering.
X['cluster_label'] = kmeans.fit_predict(X[X.columns[1:nc]])
centers = kmeans.cluster_centers_ # Coordinates of cluster centers.
labels = kmeans.predict(X[X.columns[1:3]]) # Labels of each point
maxcluster = X['cluster_label'].max()
</code>```

Body:
Image of clusters

So I think this is somewhat self-explanatory but my clusters don't really make sense. I am new to clustering and just want these datapoints to be grouped together. The problem I keep seeing is the black is being clustered over 2 distinct lines and I want them to be seperate. I am plotting weather radar over the united states and just want to have lines of storms a unique cluster and eventually remove any random super small groups, not near the lines. I tried to just add more clusters and adjust the algorithm, but nothing has been working.

Here is my code:

nc = 8
kmeans = KMeans(n_clusters = nc, init ='k-means++',n_init=1,algorithm='full')
kmeans.fit(X[X.columns[1:nc]]) # Compute k-means clustering.
X['cluster_label'] = kmeans.fit_predict(X[X.columns[1:nc]])
centers = kmeans.cluster_centers_ # Coordinates of cluster centers.
labels = kmeans.predict(X[X.columns[1:3]]) # Labels of each point
maxcluster = X['cluster_label'].max()


问:
Gradle's bundleRelease differs from assembleRelease?
It appears apk generated from bundle in universal mode is different from apk generated by assembleRelease. Specifically, application crashes with raw Lottie resource (if that matters) com.airbnb.lottie.parser.moshi.JsonUtf8Reader.nextNonWhitespace :

This came as big surprise - anyone faced something similar, anyone knows why the difference?


问:
any tips for shuffle the quiz?
This resource I got from Google, I have tried how to make the quiz random but I didn't find a good way to randomize the quiz.

Is there an easy way to randomize the quiz? I tried using shuffle but it failed, maybe because I'm still a beginner so I still lack knowledge.

html css

```<code><!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Picture Quiz</title>
<style>
body {
background-color: #eeeeee;
}
.grid {
width: 68%;
height: 520px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}

.buttons img
{
width:200px;
}
.grid h1 {
font-family: "sans-serif";
background-color: #ffc107;
font-size: 35px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
hr
{
margin-top: 50px;
    color: red;
    background-color: #ffc107;
    height: 2px;
    border: none;
}
#score {
color: #ffc107;
text-align: center;
font-size: 30px;
}

.grid #question {
font-family: "monospace";
font-size: 30px;
color: #ffc107;
}

.buttons {
margin-top: 30px;
}

#btn0,
#btn1,
#btn2,
#btn3 {

    padding: 0px;
font-size: 20px;
color: #fff;
    border: none;
margin: 10px 20px 10px 0px;

}

#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #ffc107;
}

#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}

#progress {
color: #2b2b2b;
font-size: 18px;
}
</style>
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Picture Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
<button id="btn3"><span id="choice3"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
</body>
<script src="index.js" type="text/javascript"></script>
</html>
</code>```

javascript

```<code>var images = {
"dog"  : "dog.jpg",
"cow" : "cow.jpg",
"cat" : "cat.jpg",
"goat"   : "goat.jpg",
"deer"   : "deer.jpg",
"hen"   : "hen.jpg",
"lion"   : "lion.jpg",
"parrot"   : "parrot.jpg",
"tiger"   : "tiger.jpg"

}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;

// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = images[choices[i]]? '<img src="'+images[choices[i]]+'"/>':choices[i];
guess("btn" + i, choices[i]);
}

showProgress();
}
};

function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};

function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};

function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};

// create questions
var questions = [
new Question("Which one is dog?", ["cow", "goat", "cat", "dog"], "dog"),
new Question("select tiger below", ["parrot", "deer", "tiger", "lion"], "tiger"),
new Question("choose parrot pls?", ["hen", "parrot", "goat",  "dog"], "parrot"),
new Question("Find cat below?", ["parrot", "goat", "cat", "tiger"], "cat"),
new Question("choose lion pls?", ["lion", "goat", "tiger", "dog"], "lion")
];

function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}

Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}

function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}

Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}

Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}

this.questionIndex++;
}

Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}

// create quiz
var quiz = new Quiz(questions);

// display quiz
populate();
</code>```

I tried if it was refreshed or answered on it would bring up a random quiz

Title: any tips for shuffle the quiz?

Body:
This resource I got from Google, I have tried how to make the quiz random but I didn't find a good way to randomize the quiz.

Is there an easy way to randomize the quiz? I tried using shuffle but it failed, maybe because I'm still a beginner so I still lack knowledge.

html css

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Picture Quiz</title>

Picture Quiz

<button id="btn0"></button>
<button id="btn1"></button>
<button id="btn2"></button>
<button id="btn3"></button>

Question x of y

javascript

var images = {
"dog"  : "dog.jpg",
"cow" : "cow.jpg",
"cat" : "cat.jpg",
"goat"   : "goat.jpg",
"deer"   : "deer.jpg",
"hen"   : "hen.jpg",
"lion"   : "lion.jpg",
"parrot"   : "parrot.jpg",
"tiger"   : "tiger.jpg"

}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;

// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = images[choices[i]]? '':choices[i];
guess("btn" + i, choices[i]);
}

showProgress();
}
};

function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};

function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};

function showScores() {
var gameOverHTML = "
Result
";
gameOverHTML += "
 Your scores: " + quiz.score + "
";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};

// create questions
var questions = [
new Question("Which one is dog?", ["cow", "goat", "cat", "dog"], "dog"),
new Question("select tiger below", ["parrot", "deer", "tiger", "lion"], "tiger"),
new Question("choose parrot pls?", ["hen", "parrot", "goat",  "dog"], "parrot"),
new Question("Find cat below?", ["parrot", "goat", "cat", "tiger"], "cat"),
new Question("choose lion pls?", ["lion", "goat", "tiger", "dog"], "lion")
];

function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}

Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}

function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}

Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}

Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}

this.questionIndex++;
}

Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}

// create quiz
var quiz = new Quiz(questions);

// display quiz
populate();

I tried if it was refreshed or answered on it would bring up a random quiz


问:
iOS : Universal links are not working when set default browser is Chrome/brave(other then safari)
In our iOS universal links for our app is not opening our application when we tap on the link. This is happening only when the default browser in iPhone is set to Chrome or brave (other than safari).

It works perfectly when default browser is safari.

By the way we have all the set-up for both iOS app and web server configured properly.

Please help me to solve the problem.

Expected behaviour would be launch the app when default iPhone browser is Chrome or brave.

We tried these below options, none of them worked
iOS 14 Universal Links broken on default browser other than Safari


问:
Get configuration values in any class without dependency injection
I'm trying to access a configuration value declared in appsettings.json in any class of the project.
I found various ways to do this using 'dependency injection' but that doesn't help me out.
So what I have so far is to validate a boolean from appsettings.json to be true in a validator.
This is used as backend for a React Typescript project

This is what I have on Startup.cs

```<code>services.Configure<RequestLocalizationOptions>(options => {
    options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("ro-RO");
    options.SupportedCultures = new []{ new CultureInfo("ro-RO"), new CultureInfo("en") };
    options.SupportedUICultures = new []{ new CultureInfo("ro-RO"), new CultureInfo("en") };
});
</code>```

...

```<code>services.AddCore(Configuration);
services.AddDataAccess(Configuration);
</code>```

And this is on Programs.cs

```<code>public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
    .Build();

</code>```
```<code>public static void Main(string[] args) {

    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(Configuration)
        .Enrich.FromLogContext()
        .CreateLogger();

    try {
        CreateWebHostBuilder(args).Build().Run();
    } catch (Exception ex) {
        Log.Fatal(ex, "Host terminated unexpectedly");
    } finally {
        Log.CloseAndFlush();
    }
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseConfiguration(Configuration)
        .UseSerilog();
</code>```

Tried declaring configuration file into my other class but with no success.
Also tried creating a new instance of configuration in my class, also a failure.

Body:
I'm trying to access a configuration value declared in appsettings.json in any class of the project.
I found various ways to do this using 'dependency injection' but that doesn't help me out.
So what I have so far is to validate a boolean from appsettings.json to be true in a validator.
This is used as backend for a React Typescript project

This is what I have on Startup.cs

services.Configure<RequestLocalizationOptions>(options => {
    options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("ro-RO");
    options.SupportedCultures = new []{ new CultureInfo("ro-RO"), new CultureInfo("en") };
    options.SupportedUICultures = new []{ new CultureInfo("ro-RO"), new CultureInfo("en") };
});

...

services.AddCore(Configuration);
services.AddDataAccess(Configuration);

And this is on Programs.cs

public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
    .Build();

public static void Main(string[] args) {

    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(Configuration)
        .Enrich.FromLogContext()
        .CreateLogger();

    try {
        CreateWebHostBuilder(args).Build().Run();
    } catch (Exception ex) {
        Log.Fatal(ex, "Host terminated unexpectedly");
    } finally {
        Log.CloseAndFlush();
    }
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseConfiguration(Configuration)
        .UseSerilog();

Tried declaring configuration file into my other class but with no success.
Also tried creating a new instance of configuration in my class, also a failure.


问:
OutputStream does not save file with the input path
I'm trying to create a file with the file path of non-english characters to be encoded on Android:

From:

[THAISUB] SpinEL â???? --- --- (Why Didn't You Say)_7th Level Civil
Servant OST_Instrumental.mp3

To:

%5BTHAISUB%5D%20SpinEL%20a%CC%82%3F%3F%3F%3F%20---%20---%20(Why%20Didn't%20You%20Say)_7th%20Level%20Civil%20Servant%20OST_Instrumental.mp3

â is the one not english

with the code below:

```<code>    try {
      OutputStream outputStream = getOutputStream(encodedPath, false);
      outputStream.write(bytes);
      outputStream.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
</code>```

The result is it keeps saving to the original path ([THAISUB] SpinEL â???? --- --- (Why Didn't You Say)_7th Level Civil Servant OST_Instrumental.mp3)

Body:
I'm trying to create a file with the file path of non-english characters to be encoded on Android:

From:

[THAISUB] SpinEL â???? --- --- (Why Didn't You Say)_7th Level Civil
Servant OST_Instrumental.mp3

To:

%5BTHAISUB%5D%20SpinEL%20a%CC%82%3F%3F%3F%3F%20---%20---%20(Why%20Didn't%20You%20Say)_7th%20Level%20Civil%20Servant%20OST_Instrumental.mp3

â is the one not english

with the code below:

    try {
      OutputStream outputStream = getOutputStream(encodedPath, false);
      outputStream.write(bytes);
      outputStream.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

The result is it keeps saving to the original path ([THAISUB] SpinEL â???? --- --- (Why Didn't You Say)_7th Level Civil Servant OST_Instrumental.mp3)


问:
OpenModelica with Python (OMPython)
I am new to OpenModelica.

I have developed a system of 10 discretized equations (time and space) with 10 unknowns to describe the behavior of a phase change material storage enter image description here. I coded them on Python. Would it be possible to transpose them to OpenModelica using OMPython? (in order to use the OpenModelica simulator/optimizer to solve this system). I can't find anything about this on the forums...

Eventually, I would like to create a storage module, including this system of equations to form a new module (component) on OpenModelica and to link it to other modules to make my system more complex.

Title: OpenModelica with Python (OMPython)


问:
How to check if rectangles overlap?
I have an array. e.g.:

```<code>import numpy as np

arr = []

arr.append(
([0.195, 0.229], [0.673, 0.754])
)

arr.append(
([1.0, 1.903], [0.161, 0.303])
)

arr.append(
([0.052, 0.321], [1.0, 1.929])
)
</code>```

Each tuple in arr represents the min_X, max_X, min_Y, max_Y of a rectangle in an image (example resolution: 1280x1080):

```<code>return np.array([min_X, max_X]), np.array([min_Y, max_Y])
</code>```

How can I check to see if any of the ROI's overlap?

Title: How to check if rectangles overlap?

Body:
I have an array. e.g.:

import numpy as np

arr = []

arr.append(
([0.195, 0.229], [0.673, 0.754])
)

arr.append(
([1.0, 1.903], [0.161, 0.303])
)

arr.append(
([0.052, 0.321], [1.0, 1.929])
)

Each tuple in arr represents the min_X, max_X, min_Y, max_Y of a rectangle in an image (example resolution: 1280x1080):

return np.array([min_X, max_X]), np.array([min_Y, max_Y])

How can I check to see if any of the ROI's overlap?


问:
comboBox.SelectedValue to fetch id on sql server
Im having trouble fetching ID of selected value from combobox, cna i get some help? the program should get the id of the selected string in the combobox from database.</p>
```<code> private void GetValues_Click(object sender, RoutedEventArgs e)
        {
                ReportesAsistenciaTableAdapter ada = new ReportesAsistenciaTableAdapter();
            DataTable dt = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);

                if (dt.Rows.Count > 0)
                {
                DataTable dtNew = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);
                    EstudiantesList.ItemsSource = dtNew.ToString();
                }
                else
                {
                    Estudiantes1TableAdapter studentsAdapter = new Estudiantes1TableAdapter();
                    DataTable dtStudents = studentsAdapter.GetDataByClaseID((int)selectClass.SelectedItem);
                    foreach (DataRow row in dtStudents.Rows)
                    {
                        ada.InsertQuery((int)row[0], (int)selectClass.SelectedItem, dateBox.Text, "", row[1].ToString(), selectClass.Text) ;
                    }
                    DataTable dtNew = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);
                    EstudiantesList.ItemsSource = dtNew.ToString();

                }
</code>```

Body:
Im having trouble fetching ID of selected value from combobox, cna i get some help? the program should get the id of the selected string in the combobox from database.

 private void GetValues_Click(object sender, RoutedEventArgs e)
        {
                ReportesAsistenciaTableAdapter ada = new ReportesAsistenciaTableAdapter();
            DataTable dt = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);

                if (dt.Rows.Count > 0)
                {
                DataTable dtNew = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);
                    EstudiantesList.ItemsSource = dtNew.ToString();
                }
                else
                {
                    Estudiantes1TableAdapter studentsAdapter = new Estudiantes1TableAdapter();
                    DataTable dtStudents = studentsAdapter.GetDataByClaseID((int)selectClass.SelectedItem);
                    foreach (DataRow row in dtStudents.Rows)
                    {
                        ada.InsertQuery((int)row[0], (int)selectClass.SelectedItem, dateBox.Text, "", row[1].ToString(), selectClass.Text) ;
                    }
                    DataTable dtNew = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);
                    EstudiantesList.ItemsSource = dtNew.ToString();

                }


问:
Two different transitions in a ZStack
I am new to SwiftUI and trying to play around with some stuff.

I want to have a ZStack so I can have a background color with a see through black color that should animate on the opacity. On top of that I want to animate a "card view" in from the bottom. This is not possible currently with the code I have managed to use. Both background color and the card view is animating on the opacity - from invisible to visible.

How do I animate these two items inside the ZStack with a different transition?

Here is what I have done so far but without the correct result:

```<code>ZStack {

                    Color.black
                        .ignoresSafeArea()
                        .opacity(animateSmileys ? 0.3 : 0)
                        .animation(.easeInOut)
                        .zIndex(0)

                    VStack {
                        Spacer()

                        VStack(spacing: 30) {
                            Text("Hvordan har du det i dag?")
                                .font(.title2)
                                .fontWeight(.heavy)
                                .foregroundColor(Color("playerTopView"))

                            HStack {
                                ForEach(Array(moods.enumerated()), id: \.offset) { index, mood in
                                    SmileyView(bgColor: mood.bgColor, smileyName: mood.smileyName)
                                        .aspectRatio(contentMode: .fit)
                                        .scaleEffect(CGFloat(animateSmileys ? 1 : 0), anchor: .center)
                                        .rotationEffect(.degrees(animateSmileys ? 0 : 180), anchor: .center)
                                        .animation(.interpolatingSpring(stiffness: 150, damping: 10).speed(2).delay(Double(index) * 0.2), value: animateSmileys)
                                }
                            }

                            HStack {
                                Spacer()
                            }
                        }
                        .padding()
                        .padding(.top, 20)
                        .background(Color("backgroundColor"))
                        .clipShape(RoundedRectangle(cornerRadius: 30, style: .continuous))
                        .shadow(radius: 20)
                    }
                    .padding()
                    .transition(.move(edge: .bottom))
                    .animation(.spring())
                    .onAppear {
                        animateSmileys = true
                    }
                    .zIndex(1)

                }
</code>```

Hope you guys can help me!

I tried the above code and moving the .transition(.move(edge: .bottom)) and .animation(.spring()) from the VStack holding the "card view" to the VStack inside the VStack.

Title: Two different transitions in a ZStack

Body:
I am new to SwiftUI and trying to play around with some stuff.

I want to have a ZStack so I can have a background color with a see through black color that should animate on the opacity. On top of that I want to animate a "card view" in from the bottom. This is not possible currently with the code I have managed to use. Both background color and the card view is animating on the opacity - from invisible to visible.

How do I animate these two items inside the ZStack with a different transition?

Here is what I have done so far but without the correct result:

ZStack {

                    Color.black
                        .ignoresSafeArea()
                        .opacity(animateSmileys ? 0.3 : 0)
                        .animation(.easeInOut)
                        .zIndex(0)

                    VStack {
                        Spacer()

                        VStack(spacing: 30) {
                            Text("Hvordan har du det i dag?")
                                .font(.title2)
                                .fontWeight(.heavy)
                                .foregroundColor(Color("playerTopView"))

                            HStack {
                                ForEach(Array(moods.enumerated()), id: \.offset) { index, mood in
                                    SmileyView(bgColor: mood.bgColor, smileyName: mood.smileyName)
                                        .aspectRatio(contentMode: .fit)
                                        .scaleEffect(CGFloat(animateSmileys ? 1 : 0), anchor: .center)
                                        .rotationEffect(.degrees(animateSmileys ? 0 : 180), anchor: .center)
                                        .animation(.interpolatingSpring(stiffness: 150, damping: 10).speed(2).delay(Double(index) * 0.2), value: animateSmileys)
                                }
                            }

                            HStack {
                                Spacer()
                            }
                        }
                        .padding()
                        .padding(.top, 20)
                        .background(Color("backgroundColor"))
                        .clipShape(RoundedRectangle(cornerRadius: 30, style: .continuous))
                        .shadow(radius: 20)
                    }
                    .padding()
                    .transition(.move(edge: .bottom))
                    .animation(.spring())
                    .onAppear {
                        animateSmileys = true
                    }
                    .zIndex(1)

                }

Hope you guys can help me!

I tried the above code and moving the .transition(.move(edge: .bottom)) and .animation(.spring()) from the VStack holding the "card view" to the VStack inside the VStack.


问:
Rstudio displays "Error in output$plot = renderPlot({ : object 'output' not found" Rshiny Webpage displays no points and an empty plot
I'm making a Rshiny app that overlays two scatterplots on top of each other with the ability to select data to overlay but my Rshiny code is broken due to "object 'output' not found" and a general lack of coding ability.

I'm self-taught and have been trying to fix this problem for the better part of a week, so any help would be greatly appreciated.

The error's within Rstudio I receive when running line
'output$info = renderPrint({'

Error in output$info = renderPrint({ : object 'output' not found

and when I run the line 'output$plot = renderPlot({'

Error in output$plot = renderPlot({ : object 'output' not found

The error's within Rshiny app when running the entire app are:

Empty plot. No points at all. No ability to select regions from the multiInput dropdown menu
Rshiny appearance

Here's my library setup just in case

```<code>library(rsconnect)
library(tidyr)
library(pheatmap)
library(readr)
library(tibble)
library(ggplot2)
library(ggforce)
library(plotly)
library(reshape2)
library(shiny)
library(dendextend)
library(RColorBrewer)
library(shinyWidgets)
library(dplyr)

</code>```
```<code>region1 = as.factor(c("r001[Hypothalamus - Intermediate Zone]","r001[Hypothalamus - Intermediate Zone]", "r001[Hypothalamus - Intermediate Zone]","r003[Optic tectum - neuropil]","r003[Optic tectum - neuropil]",  "r003[Optic tectum - neuropil]"))
region2 = as.factor(c("r001[Hypothalamus - Intermediate Zone]", "r003[Optic tectum - neuropil]", "r004[Rhombomere 5 - Ventromedial]",  "r001[Hypothalamus - Intermediate Zone]", "r003[Optic tectum - neuropil]", " r004[Rhombomere 5 - Ventromedial]"))
corvalue = as.numeric(c("1.000000000", "0.347262124", "-0.217184495", "0.347262124", "1.000000000", "-0.279342601"))
distvalue = as.numeric(c("0.0", "42.6","88.7", " 42.6", "0.0", "82.9"))
complete_vectp = data.frame(region1, region2, corvalue, distvalue)

p_names = levels(as.factor(complete_vectp$region2))

# - Forloop that is supposed to generate the separate plots

for (i in 1:length(p_names)) {

  strpattern <- substr(p_names[i], 1, 4)
  regionx = complete_vectp %>% #Section off by region name
    filter(grepl(strpattern, region2))

  #gives all the regions without the selected region
  comparison_region <- complete_vectp[which(complete_vectp$region1 == p_names[i]), ]

  #gives the selected region without the rest of the regions
  other_regions <- complete_vectp[-c(which(complete_vectp$region1 == p_names[i])), ]

  subplot = ggplot(other_regions, aes(x = distvalue, y = corvalue))

}
as.character(other_regions$region2)

ui = fluidPage(

  titlePanel("something"),
  sidebarLayout(
    sidebarPanel(
      multiInput("name", "Select Region",
                 choices = unique(other_regions$region1)
      ),
    ),
    mainPanel(
      verbatimTextOutput("info"),
      plotOutput("plot")
    )
  )
)

server = function(input, output) {

  other_regions_reactive = reactive({
    other_regions %>%
      dplyr::filter(unique(region1) == input$name)

  })

  output$info = renderPrint({
    nearPoints(complete_vectp, input$plot_click, input$plot_brush, threshold = 2, maxpoints = 5)
  })

  output$plot = renderPlot({
    ggplot(other_regions_reactive(), aes(x = distvalue, y = corvalue))

  })
}

shinyApp(ui = ui, server = server)

</code>```

Body:
I'm making a Rshiny app that overlays two scatterplots on top of each other with the ability to select data to overlay but my Rshiny code is broken due to "object 'output' not found" and a general lack of coding ability.

I'm self-taught and have been trying to fix this problem for the better part of a week, so any help would be greatly appreciated.

The error's within Rstudio I receive when running line
'output$info = renderPrint({'

Error in output$info = renderPrint({ : object 'output' not found

and when I run the line 'output$plot = renderPlot({'

Error in output$plot = renderPlot({ : object 'output' not found

The error's within Rshiny app when running the entire app are:

Empty plot. No points at all. No ability to select regions from the multiInput dropdown menu
Rshiny appearance

Here's my library setup just in case

library(rsconnect)
library(tidyr)
library(pheatmap)
library(readr)
library(tibble)
library(ggplot2)
library(ggforce)
library(plotly)
library(reshape2)
library(shiny)
library(dendextend)
library(RColorBrewer)
library(shinyWidgets)
library(dplyr)

region1 = as.factor(c("r001[Hypothalamus - Intermediate Zone]","r001[Hypothalamus - Intermediate Zone]", "r001[Hypothalamus - Intermediate Zone]","r003[Optic tectum - neuropil]","r003[Optic tectum - neuropil]",  "r003[Optic tectum - neuropil]"))
region2 = as.factor(c("r001[Hypothalamus - Intermediate Zone]", "r003[Optic tectum - neuropil]", "r004[Rhombomere 5 - Ventromedial]",  "r001[Hypothalamus - Intermediate Zone]", "r003[Optic tectum - neuropil]", " r004[Rhombomere 5 - Ventromedial]"))
corvalue = as.numeric(c("1.000000000", "0.347262124", "-0.217184495", "0.347262124", "1.000000000", "-0.279342601"))
distvalue = as.numeric(c("0.0", "42.6","88.7", " 42.6", "0.0", "82.9"))
complete_vectp = data.frame(region1, region2, corvalue, distvalue)

p_names = levels(as.factor(complete_vectp$region2))

# - Forloop that is supposed to generate the separate plots

for (i in 1:length(p_names)) {

  strpattern <- substr(p_names[i], 1, 4)
  regionx = complete_vectp %>% #Section off by region name
    filter(grepl(strpattern, region2))

  #gives all the regions without the selected region
  comparison_region <- complete_vectp[which(complete_vectp$region1 == p_names[i]), ]

  #gives the selected region without the rest of the regions
  other_regions <- complete_vectp[-c(which(complete_vectp$region1 == p_names[i])), ]

  subplot = ggplot(other_regions, aes(x = distvalue, y = corvalue))

}
as.character(other_regions$region2)

ui = fluidPage(

  titlePanel("something"),
  sidebarLayout(
    sidebarPanel(
      multiInput("name", "Select Region",
                 choices = unique(other_regions$region1)
      ),
    ),
    mainPanel(
      verbatimTextOutput("info"),
      plotOutput("plot")
    )
  )
)

server = function(input, output) {

  other_regions_reactive = reactive({
    other_regions %>%
      dplyr::filter(unique(region1) == input$name)

  })

  output$info = renderPrint({
    nearPoints(complete_vectp, input$plot_click, input$plot_brush, threshold = 2, maxpoints = 5)
  })

  output$plot = renderPlot({
    ggplot(other_regions_reactive(), aes(x = distvalue, y = corvalue))

  })
}

shinyApp(ui = ui, server = server)


问:
useformik and yup error message is displayed only once
I am using useformik hook on my page along with yup to display validations. I have a custom component using formik values and has a validation definition on yup validationSchema. the error message is displaying only once either on Tab or submit.

```<code> const validationSchema = yup.object().shape({
        message: yup
      .string()
      .when(["category"], {
        is: (category) =>
          category !== CATEGORY_CANDIDATE_EMAIL.toString(),
        then: yup
          .string()
          .matches(/RELATED.LINK/, "the RELATED.LINK text is required" ),
      })
      .required("error message required message")
      .nullable()
      .trim(),
    category: yup
      .string()
      .required("error message required category")
      .nullable()
      .trim(),
  });
</code>```
```<code><CustomInput
            id="message"
            name="message"
            value={formik.values.message}
            bodyText={messageTextLocalized}
            readonly={false}
            previewModeError={false}
            placeHolderText={msgEnterEmailTemplatemessageTextLocalized}
            onChange={(e) => {
              handleChange({ target: { name: "message", value: e } });
              setCustomValidation({
                ...customValidation,
                message:
                  e.indexOf("RELATED.LINK") === -1 &&
                  formik.values.category !==
                    `${CATEGORY_CANDIDATE_EMAIL}`,
              });
            }}
            hasError={
              customValidation.message ||
              ((formik.errors.message && formik.touched.message) as boolean)
            }
            errorMessage={formik.errors.message || ""}
          />
</code>```

I tried to add another <ErrorMessage /> field to display but it is now displaying same error message twice. can anyone please help me identify what can be done here.

Body:
I am using useformik hook on my page along with yup to display validations. I have a custom component using formik values and has a validation definition on yup validationSchema. the error message is displaying only once either on Tab or submit.

 const validationSchema = yup.object().shape({
        message: yup
      .string()
      .when(["category"], {
        is: (category) =>
          category !== CATEGORY_CANDIDATE_EMAIL.toString(),
        then: yup
          .string()
          .matches(/RELATED.LINK/, "the RELATED.LINK text is required" ),
      })
      .required("error message required message")
      .nullable()
      .trim(),
    category: yup
      .string()
      .required("error message required category")
      .nullable()
      .trim(),
  });

<CustomInput
            id="message"
            name="message"
            value={formik.values.message}
            bodyText={messageTextLocalized}
            readonly={false}
            previewModeError={false}
            placeHolderText={msgEnterEmailTemplatemessageTextLocalized}
            onChange={(e) => {
              handleChange({ target: { name: "message", value: e } });
              setCustomValidation({
                ...customValidation,
                message:
                  e.indexOf("RELATED.LINK") === -1 &&
                  formik.values.category !==
                    `${CATEGORY_CANDIDATE_EMAIL}`,
              });
            }}
            hasError={
              customValidation.message ||
              ((formik.errors.message && formik.touched.message) as boolean)
            }
            errorMessage={formik.errors.message || ""}
          />

I tried to add another <ErrorMessage /> field to display but it is now displaying same error message twice. can anyone please help me identify what can be done here.