问:
Kafka Connect with Redis - Sink never work
I am trying to setup the data flow as:

Source: PostgreSQL, using io.debezium.connector.postgresql.PostgresConnector

Sink: Redis, using com.github.jcustenborder.kafka.connect.redis.RedisSinkConnector

Here is my docker-compose to start services.

```<code>version: "3.8"
services:
  content_sql:
    container_name: content_sql
    image: postgres:13-alpine
    environment:
      POSTGRES_USER: content_admin
      POSTGRES_PASSWORD: 123456xyz
      POSTGRES_DB: madison_content
    command:
      - "postgres"
      - "-c"
      - "wal_level=logical"
    ports:
      - 5432:5432
    restart: always

  redis:
    container_name: redis
    image: redis:7-alpine
    ports:
      - 6379:6379

  zookeeper:
    container_name: zookeeper
    image: zookeeper:3.8-temurin
    environment:
      JVMFLAGS: -XX:+UseG1GC -XX:+DisableExplicitGC
    ports:
      - 2181:2181
      - 2888:2888
      - 3888:3888
    restart: always

  kafka:
    container_name: kafka
    image: ubuntu/kafka:edge
    environment:
      TZ: UTC
      ZOOKEEPER_HOST: host.docker.internal
      ZOOKEEPER_PORT: 2181
    ports:
      - 9092:9092
    depends_on:
      - zookeeper
    restart: always

  kafka_connector:
    container_name: kafka_connector
    image: debezium/connect-base:latest
    environment:
      GROUP_ID: 1
      CONFIG_STORAGE_TOPIC: content_configs
      OFFSET_STORAGE_TOPIC: cache_content
      STATUS_STORAGE_TOPIC: connect_statuses
      BOOTSTRAP_SERVERS: kafka:9092
      KEY_CONVERTER: org.apache.kafka.connect.storage.StringConverter
      VALUE_CONVERTER: org.apache.kafka.connect.storage.StringConverter
      KAFKA_CONNECT_PLUGINS_DIR: /usr/share/local-connectors
    volumes:
      - ~/Documents/kafka-plugins:/usr/share/local-connectors
    ports:
      - 8083:8083
    depends_on:
      - content_sql
      - kafka
      - redis
      - zookeeper
    restart: always
</code>```

The docker-compose can start successfully and plugins are loaded correctly.

Here is my REST request to register the connector.

PostgreSQL Source

```<code>{
    "name": "postgres-source",
    "config": {
        "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
        "task.max": "3",
        "database.hostname": "content_sql",
        "database.port": "5432",
        "database.user": "content_admin",
        "database.password": "123456xyz",
        "database.dbname": "madison_content",
        "database.whitelist": "madison_content",
        "table.include.list": "public.thread",
        "topic.prefix": "cache",
        "schema.history.internal.kafka.bootstrap.servers": "kafka:9092",
        "plugin.name": "pgoutput"
    }
}
</code>```

Redis Sink

```<code>{
    "name": "redis-sink",
    "config": {
        "connector.class": "com.github.jcustenborder.kafka.connect.redis.RedisSinkConnector",
        "redis.hosts": "redis:6379",
        "redis.database": "1",
        "redis.client.mode": "Standalone",
        "task.max": "3",
        "key.converter": "org.apache.kafka.connect.storage.StringConverter",
        "internal.key.converter": "org.apache.kafka.connect.storage.StringConverter",
        "value.converter": "org.apache.kafka.connect.storage.StringConverter",
        "internal.value.converter": "org.apache.kafka.connect.storage.StringConverter",
        "plugin.path": "/usr/share/local-connectors",
        "topics.regex": "cache.(.*)"
    }
}
</code>```

When I inserted data to PostgreSQL, I noticed that INFO log showed "N records ..." , I also double-checked manually the Kafka topic and message. The topic was created successfully, message was there. But somehow, the sink never work.

I checked the Redis data by using redis-cli with command KEYS *. Is it the correct way?

May you please help to have a look? Thanks.

Body:
I am trying to setup the data flow as:

Source: PostgreSQL, using io.debezium.connector.postgresql.PostgresConnector

Sink: Redis, using com.github.jcustenborder.kafka.connect.redis.RedisSinkConnector

Here is my docker-compose to start services.

version: "3.8"
services:
  content_sql:
    container_name: content_sql
    image: postgres:13-alpine
    environment:
      POSTGRES_USER: content_admin
      POSTGRES_PASSWORD: 123456xyz
      POSTGRES_DB: madison_content
    command:
      - "postgres"
      - "-c"
      - "wal_level=logical"
    ports:
      - 5432:5432
    restart: always

  redis:
    container_name: redis
    image: redis:7-alpine
    ports:
      - 6379:6379

  zookeeper:
    container_name: zookeeper
    image: zookeeper:3.8-temurin
    environment:
      JVMFLAGS: -XX:+UseG1GC -XX:+DisableExplicitGC
    ports:
      - 2181:2181
      - 2888:2888
      - 3888:3888
    restart: always

  kafka:
    container_name: kafka
    image: ubuntu/kafka:edge
    environment:
      TZ: UTC
      ZOOKEEPER_HOST: host.docker.internal
      ZOOKEEPER_PORT: 2181
    ports:
      - 9092:9092
    depends_on:
      - zookeeper
    restart: always

  kafka_connector:
    container_name: kafka_connector
    image: debezium/connect-base:latest
    environment:
      GROUP_ID: 1
      CONFIG_STORAGE_TOPIC: content_configs
      OFFSET_STORAGE_TOPIC: cache_content
      STATUS_STORAGE_TOPIC: connect_statuses
      BOOTSTRAP_SERVERS: kafka:9092
      KEY_CONVERTER: org.apache.kafka.connect.storage.StringConverter
      VALUE_CONVERTER: org.apache.kafka.connect.storage.StringConverter
      KAFKA_CONNECT_PLUGINS_DIR: /usr/share/local-connectors
    volumes:
      - ~/Documents/kafka-plugins:/usr/share/local-connectors
    ports:
      - 8083:8083
    depends_on:
      - content_sql
      - kafka
      - redis
      - zookeeper
    restart: always

The docker-compose can start successfully and plugins are loaded correctly.

Here is my REST request to register the connector.

PostgreSQL Source

{
    "name": "postgres-source",
    "config": {
        "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
        "task.max": "3",
        "database.hostname": "content_sql",
        "database.port": "5432",
        "database.user": "content_admin",
        "database.password": "123456xyz",
        "database.dbname": "madison_content",
        "database.whitelist": "madison_content",
        "table.include.list": "public.thread",
        "topic.prefix": "cache",
        "schema.history.internal.kafka.bootstrap.servers": "kafka:9092",
        "plugin.name": "pgoutput"
    }
}

Redis Sink

{
    "name": "redis-sink",
    "config": {
        "connector.class": "com.github.jcustenborder.kafka.connect.redis.RedisSinkConnector",
        "redis.hosts": "redis:6379",
        "redis.database": "1",
        "redis.client.mode": "Standalone",
        "task.max": "3",
        "key.converter": "org.apache.kafka.connect.storage.StringConverter",
        "internal.key.converter": "org.apache.kafka.connect.storage.StringConverter",
        "value.converter": "org.apache.kafka.connect.storage.StringConverter",
        "internal.value.converter": "org.apache.kafka.connect.storage.StringConverter",
        "plugin.path": "/usr/share/local-connectors",
        "topics.regex": "cache.(.*)"
    }
}

When I inserted data to PostgreSQL, I noticed that INFO log showed "N records ..." , I also double-checked manually the Kafka topic and message. The topic was created successfully, message was there. But somehow, the sink never work.

I checked the Redis data by using redis-cli with command KEYS *. Is it the correct way?

May you please help to have a look? Thanks.


来源: stackexchange

问:
Apollo-Client: Why does a refetch not update the data?
I can't understand why apollo refetch doesn't update data? we subscribed on clearStore of apollo, and when it happens our refetch returns new data (null) but the component doesn't see that current user now is null.</p>
```<code>const { loading, data, client, refetch } = useQuery(CURRENT_USER, { fetchPolicy: 'network-only' });

useEffect(() => {
  const unsubscribe = client.onClearStore(() =>
    Promise.resolve().then(() => {
      console.log('tes')
      refetch().catch(() => void 0)
    })
  );

  return () => {
    unsubscribe();
  };
}, [])

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can't understand why apollo refetch doesn't update data? we subscribed on clearStore of apollo, and when it happens our refetch returns new data (null) but the component doesn't see that current user now is null.

const { loading, data, client, refetch } = useQuery(CURRENT_USER, { fetchPolicy: 'network-only' });

useEffect(() => {
  const unsubscribe = client.onClearStore(() =>
    Promise.resolve().then(() => {
      console.log('tes')
      refetch().catch(() => void 0)
    })
  );

  return () => {
    unsubscribe();
  };
}, [])


问:
Download File using flutter_webview_pro with Laravel
From webview, and download BLOB file

This is from my Laravel source code (web-based), BLOB file

```<code>public function downloadDocuments(){
  try{
   $id = 1;
   $files = Documents::find($id);
     return response()->streamDownload(function () use($files){
       echo $files->data;
     }, $getFilename->document_name);

     } catch (\Throwable $th) {
        DB::rollback();
       $this->reportError($th->getMessage());
     }
   }
</code>```

This is my flutter WebView

```<code>WebView(
            initialUrl:
                '${widget.url}/webView?type=${widget.type}&role=${widget.role}&profile=${widget.profile}&username=${widget.username}&password=${widget.password}',
            zoomEnabled: false,
            onWebViewCreated: (WebViewController webViewController) {
              controller.complete(webViewController);
            },
            onPageStarted: (url) {
              setState(() {
                loadingPercentage = 0;
              });
            },
            onProgress: (progress) {
              setState(() {
                loadingPercentage = progress;
              });
            },
            onPageFinished: (url) {
              setState(() {
                loadingPercentage = 100;
              });
            },
            javascriptMode: JavascriptMode.unrestricted,
            javascriptChannels: _createJavascriptChannels(context),
          ),
          if (loadingPercentage < 100)
            LinearProgressIndicator(
              value: loadingPercentage / 100.0,
            ),
</code>```

How to get Downloaded file store in android local storage

Body:
From webview, and download BLOB file

This is from my Laravel source code (web-based), BLOB file

public function downloadDocuments(){
  try{
   $id = 1;
   $files = Documents::find($id);
     return response()->streamDownload(function () use($files){
       echo $files->data;
     }, $getFilename->document_name);

     } catch (\Throwable $th) {
        DB::rollback();
       $this->reportError($th->getMessage());
     }
   }

This is my flutter WebView

WebView(
            initialUrl:
                '${widget.url}/webView?type=${widget.type}&role=${widget.role}&profile=${widget.profile}&username=${widget.username}&password=${widget.password}',
            zoomEnabled: false,
            onWebViewCreated: (WebViewController webViewController) {
              controller.complete(webViewController);
            },
            onPageStarted: (url) {
              setState(() {
                loadingPercentage = 0;
              });
            },
            onProgress: (progress) {
              setState(() {
                loadingPercentage = progress;
              });
            },
            onPageFinished: (url) {
              setState(() {
                loadingPercentage = 100;
              });
            },
            javascriptMode: JavascriptMode.unrestricted,
            javascriptChannels: _createJavascriptChannels(context),
          ),
          if (loadingPercentage < 100)
            LinearProgressIndicator(
              value: loadingPercentage / 100.0,
            ),

How to get Downloaded file store in android local storage


问:
Is there a method to parallel the following pytorch code?
I have the following pytorch code that define a new matrix operation on two matrix points and primitives

```<code>def operations(points, primitives):
    """
    points shape: (batch size, number_of_points, 3)
    primitives shape: (batch_size, number_of_primitives,7)
    """
    gradient = torch.zeros(batch_size,number_of_points,number_of_primitives)
    for i in range(batch_size):

        temp_points = points[i,:,:]

        temp_primitives= primitives[i,:,:]
        temp = torch.zeros(number_of_points,number_of_primitives)
        for k in range(number_of_points):
            for j in range(number_of_primitives):
                temp[k,j] = torch.norm(temp_points[k,:]*temp_primitives[j,:3]+temp_primitives[j,3:6])
        gradient[i,:,:] = temp
    return gradient
</code>```

Is there any method to parallelize such code to speed up?Thanks!

The above serialized code is implemented by myself, which is utilized in a deep-learning work. Is there any method to parallelize it? I have the following try:

```<code>def sstp(points,primitives):
    batch_size,number_of_points,_ = points.shape
    _,_,number_of_primitives = primitives.shape
    gradient = torch.zeros(batch_size,number_of_points,number_of_primitives)

    def level3(i,k,j):
        print("level 3 {} {}".format(k,j))
        temp_points = points[i,:,:]
        temp_primitives = primitives[i,:,:].transpose(1,0)
        gradient_ijk = torch.norm(temp_points[k,:]*temp_primitives[j,:3]+temp_primitives[j,3:6])
        gradient[i,k,j] = torch.norm(temp_points[k,:]*temp_primitives[j,:3]+temp_primitives[j,3:6])
    def level2(i):
        global pool
        pool.map(level3,[(i,k,j) for k in range(number_of_points) for j in range(number_of_primitives)])
    #level 1
    global pool
    pool = multiprocessing.pool.ThreadPool(100)
    pool.map(level2, range(batch_size))
    pool.close()
    return gradient
</code>```

but it throw an error  bus error. Could you help me with it? Thanks!

Body:
I have the following pytorch code that define a new matrix operation on two matrix points and primitives

def operations(points, primitives):
    """
    points shape: (batch size, number_of_points, 3)
    primitives shape: (batch_size, number_of_primitives,7)
    """
    gradient = torch.zeros(batch_size,number_of_points,number_of_primitives)
    for i in range(batch_size):

        temp_points = points[i,:,:]

        temp_primitives= primitives[i,:,:]
        temp = torch.zeros(number_of_points,number_of_primitives)
        for k in range(number_of_points):
            for j in range(number_of_primitives):
                temp[k,j] = torch.norm(temp_points[k,:]*temp_primitives[j,:3]+temp_primitives[j,3:6])
        gradient[i,:,:] = temp
    return gradient

Is there any method to parallelize such code to speed up?Thanks!

The above serialized code is implemented by myself, which is utilized in a deep-learning work. Is there any method to parallelize it? I have the following try:

def sstp(points,primitives):
    batch_size,number_of_points,_ = points.shape
    _,_,number_of_primitives = primitives.shape
    gradient = torch.zeros(batch_size,number_of_points,number_of_primitives)

    def level3(i,k,j):
        print("level 3 {} {}".format(k,j))
        temp_points = points[i,:,:]
        temp_primitives = primitives[i,:,:].transpose(1,0)
        gradient_ijk = torch.norm(temp_points[k,:]*temp_primitives[j,:3]+temp_primitives[j,3:6])
        gradient[i,k,j] = torch.norm(temp_points[k,:]*temp_primitives[j,:3]+temp_primitives[j,3:6])
    def level2(i):
        global pool
        pool.map(level3,[(i,k,j) for k in range(number_of_points) for j in range(number_of_primitives)])
    #level 1
    global pool
    pool = multiprocessing.pool.ThreadPool(100)
    pool.map(level2, range(batch_size))
    pool.close()
    return gradient

but it throw an error  bus error. Could you help me with it? Thanks!


问:
Installing php-zmq extension on PHP 8.1 in a docker container
What is wrong with this Dockerfile?

```<code>FROM php:8.1-apache

RUN apt-get update && apt-get install -y libzmq5

# Install the ZeroMQ extension
RUN pecl install zmq-beta

# Enable the ZeroMQ extension
RUN docker-php-ext-enable zmq

</code>```

It seems that I cannot install php-zmq extension in PHP 8.1. Any tips on how can I proceed with the installation?

Body:
What is wrong with this Dockerfile?

FROM php:8.1-apache

RUN apt-get update && apt-get install -y libzmq5

# Install the ZeroMQ extension
RUN pecl install zmq-beta

# Enable the ZeroMQ extension
RUN docker-php-ext-enable zmq

It seems that I cannot install php-zmq extension in PHP 8.1. Any tips on how can I proceed with the installation?


Title: How to filter longitude and latitude that are not within a area

Body:
I have a boundary with polygon object that is consisted of longitudes and latitudes.

That looks like the below:

POLYGON((35.82879102266901 128.7076346641539,35.82707300496909 128.7067790195541,35.82583849984275 128.70867790735832,35.824475124668446 128.70759751110955,35.823661363692246 128.7058871623279,35.82330557322746 128.70555866952947,35.82331389280524 128.70497241578087,35.82526251082479 128.70418422540567,35.82744337671204 128.7041755355518,35.827607540680496 128.70530771172315,35.82939029995311 128.70541225682194,35.83034001648074 128.70262188794626,35.83078056043854 128.69951074704943,35.83193366058302 128.69379210686643,35.828047660143625 128.693941879719,35.827966675973194 128.69201477525812,35.82756567015862 128.691054639399,35.82742778802447 128.68932551896413,35.82650612209906 128.6882215894989,35.82623275962891 128.6871535405911,35.82647878660091 128.68631779206828,35.82589756010733 128.6853538910315,35.82655549313656 128.68470389060354,35.82708326990368 128.6843388272404,35.82758369093474 128.68335351964126,35.82889524063444 128.68364679883342,35.82890639831895 128.68285031370743,35.828906097221974 128.67981280809806,35.82888304950931 128.67888281424953,35.82896109865986 128.67781109698095,35.82914226525198 128.6749987130506,35.829530458483134 128.66911993413487,35.82983133640095 128.66821884727412,35.83362553735145 128.67013528497822,35.834399059357544 128.67024003096986,35.840482024092296 128.6695707366228,35.84159664755783 128.66977117810666,35.842905155774766 128.67028558214335,35.84594503638666 128.67200953129984,35.84644751771214 128.67086900635903,35.84705457008395 128.6712801954765,35.8434163977168 128.67886262656154,35.84314479314578 128.67975890696695,35.84173465446248 128.6852185741404,35.84220901183875 128.68737568860865,35.842691108354394 128.68897961865747,35.84312006520884 128.69051603468242,35.84319021489896 128.6919341686762,35.843845826650806 128.69193149502144,35.84458126183942 128.69217954131344,35.8450944094251 128.6928545128021,35.845537407773186 128.6949889588373,35.84594458681003 128.69774246767017,35.84595753555761 128.69873885574475,35.845592497537034 128.69906310486897,35.8455682983552 128.69949976886403,35.8456150311943 128.70001818866905,35.845563157388696 128.70065901677296,35.84537908872975 128.70140769814486,35.84555437110258 128.70286963195795,35.84587322292093 128.70357926102878,35.84594642214659 128.70381878675977,35.846971713667784 128.70522976267594,35.847545984299884 128.70540254780536,35.84770419707187 128.70647677872364,35.846993881550205 128.70668291781934,35.84665150163529 128.70699655180104,35.84651270074719 128.70756911108555,35.84664594398947 128.708338426456,35.846370809343775 128.70867563064274,35.84552164493595 128.70882342843882,35.84555869274497 128.7100195496374,35.844390635774545 128.70946322074195,35.84409546436334 128.71057471572104,35.84279576302751 128.7119855691835,35.84233078727481 128.71173209213836,35.84162880715499 128.71356524195375,35.84170215924991 128.71473995285587,35.8416923687089 128.7160567492122,35.84125948431006 128.71671145609938,35.84060185802347 128.717328108808,35.83969799283258 128.71814971377495,35.840034447448154 128.71919727395152,35.83991953670813 128.71967067618365,35.84008465778431 128.72072561124943,35.841207493858356 128.72223287429418,35.8400990619929 128.72349268565964,35.84077048506402 128.72505661382988,35.84092818918439 128.72536990992046,35.84112033710699 128.7257946253903,35.84131958422449 128.7263523033404,35.84147458147238 128.72685368846388,35.83911513549549 128.7286285758717,35.839407843897376 128.72926574390837,35.833677521275426 128.73295917806223,35.82998596835267 128.73274610143017,35.82643232778233 128.73109204987105,35.82124747076703 128.73101263135672,35.81720051067774 128.73357454481362,35.81238647159309 128.73589823930334,35.808559429329115 128.73695438018242,35.80941040679152 128.73325029582915,35.81056065279409 128.72909350975036,35.81459078638608 128.72518698632229,35.81992126286518 128.71793355529508,35.82191863521933 128.71689227991428,35.82393401644843 128.71585134191892,35.82522489120707 128.71379891405198,35.82756633550083 128.71010918623398,35.82879102266901 128.7076346641539))

I also have a list of sets of longitudes and latitudes.

df = pd.DataFrame({'name':['a', 'b', 'c', 'd'] ,'lat': [37.6647124, 37.90052166666667, 36.807616, 37.24141], 'long': [126.7686911, 127.203435, 127.107547, 127.059358]})

I want to filter out names that are not within the polygon.

I can't come up with an idea that works.

[Edited]
For the POLYGON, if you need to convert that to a list of pairs, then you can use the following code.

def get_lat_lng_pair(boundary_str):
    lat_lng_list = []
    for lat_lng_str in boundary_str.split(','):
        lat, lng = lat_lng_str.split()
        lat_lng_list.append((float(lat), float(lng)))
    return lat_lng_list

# Extracting All Polygon points
all_area_ids = [27]
all_polygon_pts = get_all_polygon_pts(area_df, all_area_ids)
all_polygon_pts


问:
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component
Versions I am using:

Java 1.8

Spring Boot v2.7.5

There seems to be [Tomcat] and [Apache Tomcat/9.0.68] trying to start at once, causing an exception, I can't figure out how to solve this.

mvn install from pom.xml is successful. Just that there is a runtime exception.

When I run the program:

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.5)

Dec 29, 2022 12:15:41 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["https-jsse-nio-8443"]
Dec 29, 2022 12:15:41 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Tomcat]
Dec 29, 2022 12:15:41 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.68]
Dec 29, 2022 12:15:41 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]]
    at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440)

Dec 29, 2022 12:15:41 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: A child container failed during start
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    ... 21 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]]

    ... 29 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]]

    ... 29 more
Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;

    ... 39 more

Dec 29, 2022 12:15:41 PM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["https-jsse-nio-8443"]
Dec 29, 2022 12:15:41 PM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service [Tomcat]
Dec 29, 2022 12:15:41 PM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["https-jsse-nio-8443"]

Process finished with exit code 1

</code>```

Body:
Versions I am using:

Java 1.8

Spring Boot v2.7.5

There seems to be [Tomcat] and [Apache Tomcat/9.0.68] trying to start at once, causing an exception, I can't figure out how to solve this.

mvn install from pom.xml is successful. Just that there is a runtime exception.

When I run the program:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.5)

Dec 29, 2022 12:15:41 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["https-jsse-nio-8443"]
Dec 29, 2022 12:15:41 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Tomcat]
Dec 29, 2022 12:15:41 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.68]
Dec 29, 2022 12:15:41 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]]
    at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440)

Dec 29, 2022 12:15:41 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: A child container failed during start
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    ... 21 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]]

    ... 29 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]]

    ... 29 more
Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;

    ... 39 more

Dec 29, 2022 12:15:41 PM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["https-jsse-nio-8443"]
Dec 29, 2022 12:15:41 PM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service [Tomcat]
Dec 29, 2022 12:15:41 PM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["https-jsse-nio-8443"]

Process finished with exit code 1


问:
Using MathQuill library in a TypeScript project
I'm working on calculator-keyboard and using the mathquill library. Since my project is based on Vue 3 with TypeScript + Quasar, it is my understanding that I need the @types/mathquill library. However, I could not find this library in the npm registry.

I tried to create a declaration for mathquill in index.d.ts but this causes problem to my corresponding page.

Here's the index.d.ts file:

```<code>declare module "mathquill" {
  export interface MathQuill {
    MathField: (element: HTMLElement | string, config?: MathFieldConfig) => MathField;
    getInterface: (version: number) => MathQuillInterface;
  }

  export interface MathFieldConfig {
    handlers?: {
      edit?: (mathField: MathField) => void;
    }
    restrictMismatchedBrackets?: boolean;
    spaceBehavesLikeTab?: boolean;
  }

  export interface MathField {
    el(): HTMLElement;
    focus(): void;
    blur(): void;
    write(latex: string): void;
    cmd(latex: string): void;
    config(options: MathFieldConfig): void;
    html(): string;
    latex(): string;
    latex(latex: string): void;
  }

  export interface MathQuillInterface {}

  export default MathQuill;
}
</code>```

How can I work around this problem?

Body:
I'm working on calculator-keyboard and using the mathquill library. Since my project is based on Vue 3 with TypeScript + Quasar, it is my understanding that I need the @types/mathquill library. However, I could not find this library in the npm registry.

I tried to create a declaration for mathquill in index.d.ts but this causes problem to my corresponding page.

Here's the index.d.ts file:

declare module "mathquill" {
  export interface MathQuill {
    MathField: (element: HTMLElement | string, config?: MathFieldConfig) => MathField;
    getInterface: (version: number) => MathQuillInterface;
  }

  export interface MathFieldConfig {
    handlers?: {
      edit?: (mathField: MathField) => void;
    }
    restrictMismatchedBrackets?: boolean;
    spaceBehavesLikeTab?: boolean;
  }

  export interface MathField {
    el(): HTMLElement;
    focus(): void;
    blur(): void;
    write(latex: string): void;
    cmd(latex: string): void;
    config(options: MathFieldConfig): void;
    html(): string;
    latex(): string;
    latex(latex: string): void;
  }

  export interface MathQuillInterface {}

  export default MathQuill;
}

How can I work around this problem?


问:
How to call Api in react before component render
I want to call API from the server before the react component render. Generally, useEffect hook call Api after the component mount but I want to call API before the component mount.</p>


问:
How to combine mp3 and TextToSpeech?
I need to combine mp3Player and TextToSpeech for the below:
"Customers with card number"(use mp3) + "149AW" (use TextToSpeech) + "please go to counter 6" (use mp3).

```<code>package com.example.test;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    public static MediaPlayer mpVoice1, mpVoice2;
    Button          btnSp;
    TextToSpeech    t;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t = new TextToSpeech(this, i -> {
            if(i != TextToSpeech.ERROR){
                t.setLanguage(Locale.US);
            }
        });
        // mpVoice1 = "Customers with card number"
        String myText = "149AW";
        // mpVoice2 = "please go to counter 6"
        mpVoice1 = MediaPlayer.create(this,R.raw.voice1);
        mpVoice2 = MediaPlayer.create(this,R.raw.voice2);

        btnSp = findViewById(R.id.button1);
        btnSp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mpVoice1.start();
                t.speak(myText, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        });
    }
}
</code>```

The below code played all sound in the same time, even though I use if for the second voice. How can we connect it successfully?

Title: How to combine mp3 and TextToSpeech?

Body:
I need to combine mp3Player and TextToSpeech for the below:
"Customers with card number"(use mp3) + "149AW" (use TextToSpeech) + "please go to counter 6" (use mp3).

package com.example.test;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    public static MediaPlayer mpVoice1, mpVoice2;
    Button          btnSp;
    TextToSpeech    t;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t = new TextToSpeech(this, i -> {
            if(i != TextToSpeech.ERROR){
                t.setLanguage(Locale.US);
            }
        });
        // mpVoice1 = "Customers with card number"
        String myText = "149AW";
        // mpVoice2 = "please go to counter 6"
        mpVoice1 = MediaPlayer.create(this,R.raw.voice1);
        mpVoice2 = MediaPlayer.create(this,R.raw.voice2);

        btnSp = findViewById(R.id.button1);
        btnSp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mpVoice1.start();
                t.speak(myText, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        });
    }
}

The below code played all sound in the same time, even though I use if for the second voice. How can we connect it successfully?


问:
Failed to enable query frontend using Loki simple scalable deployment mode
I am currently using simple scalable deployment mode ( 3 reads, 6 writes, Helm Chart version: 3.7.0 ) for my logging system. As I have to ingest around 2TB data per day in Loki, the search performance is not sufficient (Summary.BytesProcessedPerSecond 409 MB) for production.

I’ve read blog posts “How to improve Loki Performance”(https://community.grafana.com/t/how-to-improve-loki-performance/42800) and was tried to follow the step in the doc (https://grafana.com/docs/loki/latest/configuration/query-frontend/), I can successfully run a query-frontend pod, but failed in connecting to the Loki read pods.

Besides, according to the Architecture from the doc (https://grafana.com/docs/loki/latest/fundamentals/architecture/deployment-modes/), query frontend seems to be part of the read pods.

So, my questions are, how to enable the query frontend in my case? Or only distributed deployment mode achieves the goal?

Here’s my config.yaml

```<code>auth_enabled: false
common:
  path_prefix: /var/loki
  replication_factor: 1
  storage:
    s3:
      access_key_id: access_key_id
      bucketnames: bucketnames
      endpoint: s3.region.amazonaws.com
      http_config:
        idle_conn_timeout: 1800s
      insecure: false
      region: region
      s3forcepathstyle: false
      secret_access_key: secret_access_key
ingester:
  autoforget_unhealthy: true
  chunk_encoding: snappy
  chunk_idle_period: 30m
  chunk_retain_period: 0s
  chunk_target_size: 1572864
  flush_check_period: 15s
  max_transfer_retries: 0
limits_config:
  enforce_metric_name: false
  ingestion_burst_size_mb: 100
  ingestion_rate_mb: 25
  max_cache_freshness_per_query: 10m
  max_query_parallelism: 16
  per_stream_rate_limit: 15mb
  per_stream_rate_limit_burst: 30mb
  reject_old_samples: true
  reject_old_samples_max_age: 720h
  retention_period: 720h
  split_queries_by_interval: 15m
memberlist:
  join_members:
  - loki-memberlist
querier:
  engine:
    max_look_back_period: 30m
    timeout: 30m
query_range:
  align_queries_with_step: true
query_scheduler:
  scheduler_ring:
    instance_interface_names:
    - lo
ruler:
  storage:
    s3:
      access_key_id:  access_key_id
      bucketnames: bucketnames
      endpoint: s3.region.amazonaws.com
      insecure: false
      region: region
      s3forcepathstyle: false
      Secret_access_key: secret_access_key
    type: s3
schema_config:
  configs:
  - from: "2022-12-11"
    index:
      period: 24h
      prefix: loki_index_
    object_store: s3
    schema: v12
    store: boltdb-shipper
server:
  grpc_listen_port: 9098
  grpc_server_max_recv_msg_size: 83386080
  grpc_server_max_send_msg_size: 83386080
  http_listen_port: 3100
  http_server_idle_timeout: 1800s
  http_server_read_timeout: 1800s
  http_server_write_timeout: 1800s
storage_config:
  hedging:
    at: 250ms
    max_per_second: 20
    up_to: 3

# config for query frontend
  frontend:
    max_outstanding_per_tenant: 10240
    log_queries_longer_than: 15s
    compress_responses: true
    downstream_url: querier.log-server-prod.svc.cluster.local:3100
  frontend_worker:
    frontend_address: querier.log-server-prod.svc.cluster.local:3100
    grpc_client_config:
        max_send_msg_size: 10485760
    parallelism: 1
  query_range:
    split_queries_by_interval: 15m
    align_queries_with_step: true
    max_retries: 5
</code>```

Thanks!

Body:
I am currently using simple scalable deployment mode ( 3 reads, 6 writes, Helm Chart version: 3.7.0 ) for my logging system. As I have to ingest around 2TB data per day in Loki, the search performance is not sufficient (Summary.BytesProcessedPerSecond 409 MB) for production.

I’ve read blog posts “How to improve Loki Performance”(https://community.grafana.com/t/how-to-improve-loki-performance/42800) and was tried to follow the step in the doc (https://grafana.com/docs/loki/latest/configuration/query-frontend/), I can successfully run a query-frontend pod, but failed in connecting to the Loki read pods.

Besides, according to the Architecture from the doc (https://grafana.com/docs/loki/latest/fundamentals/architecture/deployment-modes/), query frontend seems to be part of the read pods.

So, my questions are, how to enable the query frontend in my case? Or only distributed deployment mode achieves the goal?

Here’s my config.yaml

auth_enabled: false
common:
  path_prefix: /var/loki
  replication_factor: 1
  storage:
    s3:
      access_key_id: access_key_id
      bucketnames: bucketnames
      endpoint: s3.region.amazonaws.com
      http_config:
        idle_conn_timeout: 1800s
      insecure: false
      region: region
      s3forcepathstyle: false
      secret_access_key: secret_access_key
ingester:
  autoforget_unhealthy: true
  chunk_encoding: snappy
  chunk_idle_period: 30m
  chunk_retain_period: 0s
  chunk_target_size: 1572864
  flush_check_period: 15s
  max_transfer_retries: 0
limits_config:
  enforce_metric_name: false
  ingestion_burst_size_mb: 100
  ingestion_rate_mb: 25
  max_cache_freshness_per_query: 10m
  max_query_parallelism: 16
  per_stream_rate_limit: 15mb
  per_stream_rate_limit_burst: 30mb
  reject_old_samples: true
  reject_old_samples_max_age: 720h
  retention_period: 720h
  split_queries_by_interval: 15m
memberlist:
  join_members:
  - loki-memberlist
querier:
  engine:
    max_look_back_period: 30m
    timeout: 30m
query_range:
  align_queries_with_step: true
query_scheduler:
  scheduler_ring:
    instance_interface_names:
    - lo
ruler:
  storage:
    s3:
      access_key_id:  access_key_id
      bucketnames: bucketnames
      endpoint: s3.region.amazonaws.com
      insecure: false
      region: region
      s3forcepathstyle: false
      Secret_access_key: secret_access_key
    type: s3
schema_config:
  configs:
  - from: "2022-12-11"
    index:
      period: 24h
      prefix: loki_index_
    object_store: s3
    schema: v12
    store: boltdb-shipper
server:
  grpc_listen_port: 9098
  grpc_server_max_recv_msg_size: 83386080
  grpc_server_max_send_msg_size: 83386080
  http_listen_port: 3100
  http_server_idle_timeout: 1800s
  http_server_read_timeout: 1800s
  http_server_write_timeout: 1800s
storage_config:
  hedging:
    at: 250ms
    max_per_second: 20
    up_to: 3

# config for query frontend
  frontend:
    max_outstanding_per_tenant: 10240
    log_queries_longer_than: 15s
    compress_responses: true
    downstream_url: querier.log-server-prod.svc.cluster.local:3100
  frontend_worker:
    frontend_address: querier.log-server-prod.svc.cluster.local:3100
    grpc_client_config:
        max_send_msg_size: 10485760
    parallelism: 1
  query_range:
    split_queries_by_interval: 15m
    align_queries_with_step: true
    max_retries: 5

Thanks!


问:
Routing problem with Angular13 and Node 16
UPDATE: So, I'm putting this here because it's more relevant.

I used another example from BobbyHadz and it's much better.  https://www.digitalocean.com/community/tutorials/build-a-restful-api-using-node-and-express-4

So, the ONLY thing I've done is this.

I made a connection to the DB for getting PhoneTypes and it's working.
I have the ROUTES for CRUD in another file and the REQUIRE for the DB in the routes file and that works, but, what is not working or is out of place, is the data file which contains the RECORDSET (and it's retrieving) is TOO EARLY.

This is in the phoneTypeRoutes.js

```<code>const PhoneTypes = require("../../model/phone_types");
const phonetypesdata = require("../../database/phone-types-data");
console.log("PHONE TYPES DATA inside PTROUTE: ", phonetypesdata);
</code>```

phone-types-data.js is the DATABASE connection.

Then, in index.js, I'm pulling (requiring) the router for phone types like so.

```<code>const phonetyperoute = require("./node-backend/routes/phoneTypes/phoneTypeRoutes");
</code>```

What's happening is this in the console for NODEJS.

```<code>[nodemon] starting `node index.js`
PHONE TYPES DATA inside PTROUTE:  { phonetypesDataArray: [] } <<-- TOO EARLY
DB CONNECT is:  {} <<-- TOO EARLY
Listening on port number: 8000
connected for phonetypes
connected branches of service
connected db-conn
ALL PHONE TYPES RETRIEVED:  {
  recordsets: [ [ [Object], [Object], [Object] ] ],
  recordset: [
    { phone_types_id: 1, phone_type_name: 'CELL', rowCnt: 3 },
    { phone_types_id: 2, phone_type_name: 'HOME', rowCnt: 3 },
    { phone_types_id: 3, phone_type_name: 'WORK', rowCnt: 3 }
  ],
  output: {},
  rowsAffected: []
}
RECORDSET PHONETYPES:  [
  [
    { phone_types_id: 1, phone_type_name: 'CELL', rowCnt: 3 },
    { phone_types_id: 2, phone_type_name: 'HOME', rowCnt: 3 },
    { phone_types_id: 3, phone_type_name: 'WORK', rowCnt: 3 }
  ]
]
// Those first two lines need to be DOWN here... AFTER the data comes back
</code>```

Unless I'm missing something...

Here's the DB call which is working phone-types-data.js

```<code>const sql = require("mssql");
const env = require("../../environment.js");
require("msnodesqlv8");
// ConnStr using ODBC
const config = {
  connectionString:
    "Dsn=" +
    env.FORMS.DSN.ACCRED +
    ";Driver=" +
    env.FORMS.DRIVER +
    ";Host=" +
    env.FORMS.HOST.LOCAL +
    ";Database=" +
    env.FORMS.DBNAME.ACCRED +
    ";trusted_connection=" +
    env.FORMS.OPTIONS.trustedConnection +
    ";",
};
const dbConn = new sql.ConnectionPool(config);
let phonetypesDataArray = [];

let query;
query = env.STOREDPROCS.GET.PHONETYPES;

sql
  .connect(config)
  .then((dbConn) => {
    console.log("connected for phonetypes");

    dbConn.query(query, (err, data) => {
      if (err) {
        console.log("Error getting PhoneTypes from Stored Proc: ", err);
        sql.close();
      }
      if (data) {
        console.log("ALL PHONE TYPES RETRIEVED: ", data);
        phonetypesDataArray.push(data.recordset);
        console.log("RECORDSET PHONETYPES: ", phonetypesDataArray);
      } else {
        let errmsg =
          "NO RECORDS RETURNED for " + env.STOREDPROCS.GET.PHONETYPES;
        console.log(errmsg);
        phonetypesDataArray.push({ error: errmsg });
      }
      sql.close();
      // res.send(recordset);
    });
  })
  .catch((err) => {
    console.log("error", err);
    errmsg = `"Error Connecting to Database: ", ${err}`;
    phonetypesDataArray.push(errmsg);
  });

module.exports = { phonetypesDataArray };

</code>```

I've written a node server app for APIs. I'm calling it from Angular 13.
I got the idea from here... https://medium.com/bb-tutorials-and-thoughts/how-to-make-api-calls-in-angular-applications-ab5364cf9533 but my solution is more complicated and I'm getting NOT FOUND on Node when I ping the server URL or call from Angular.

Here's the dumbed down version of the code:

First NODE:

This is server.js

```<code>var Service = require('node-windows').Service;

var svc = new Service({
    name: 'Node Rest API',
    description: 'The nodejs.org example web server.',
    script: 'C:\\somedir\\subdir\\nameofsomething\\node-rest-api\\index.js'
});

// Listen for the "install" event, which indicates the
// process is available as a service.

svc.on('install', function () {
    svc.start();
});

svc.install();
</code>```

This is index.js

```<code>const express = require("express");
const path = require("path");
// const mongoose = require('mongoose');
const cors = require("cors");
const bodyParser = require("body-parser");
const sql = require("mssql");

// ROUTES
const noderoutes = require("./node-backend/routes/form21.routes");
const phonetyperoute = require("./node-backend/routes/phoneTypes/phoneTypeRoutes");
const branchesofservice = require("./node-backend/routes/branchesOfService/branchesRoutes");

const app = express();
const enviro = require("./environment");
const createError = require("http-errors");
const { env } = require("process");
const dbconfig = require("./node-backend/database/db-conn");
const phone_types = require("./node-backend/model/phone_types");

console.log('DB CONNECT is: ', dbconfig);

app.use(bodyParser.json());

app.use(
  bodyParser.urlencoded({
    extended: false,
  })
);

app.use(cors());
app.use(corsOptions);

// Static directory path
app.use(
  express.static(path.join(__dirname, "/"))
);

// API root
app.use("/api/forms", noderoutes);
app.use("/api/phonetypes", phonetyperoute);
app.use("/api/branchesofsvc", branchesofservice);

// PORT
const port = process.env.PORT || 8000;
app.listen(port, () => {
  console.log("Listening on port number: " + port);
});

// 404 Handler
app.use((req, res, next) => {
  next(createError(404));
});

// Base Route
app.get("/", (req, res) => {
  res.send("invaild endpoint");
});

app.get("*", (req, res) => {
  res.sendFile(
    path.join(__dirname, "index.html")
  );
});
// THIS IS WHAT I'm trying to call.
app.get('/allphonetypes', (req,res) => {
  res.json(phone_types);
});

// error handler
app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  res.status(err.statusCode).send(err.message);
});

</code>```

NEXT the DBConn.js is working and here's that.

This is dbconn.js

```<code>const sql = require("mssql");
const env = require("../../environment.js")
require("msnodesqlv8");
// ConnStr using ODBC
const config = {
    connectionString: "Dsn=" + env.VAFORMS.DSN.ACCRED + ";Driver=" + env.VAFORMS.DRIVER + ";Host=" + env.VAFORMS.HOST.LOCAL + ";Database=" + env.VAFORMS.DBNAME.ACCRED + ";trusted_connection=" + env.VAFORMS.OPTIONS.trustedConnection + ";"
};
const dbConn = new sql.ConnectionPool(config);

sql.connect(config).then((dbConn) => {
    console.log("connected db-conn");

    // THIS TEST to my stored proc WORKS FINE and produced 242 records
    let query = "exec " + env.STOREDPROCS.GET.ALLCOUNTRIES;
    dbConn.query(query, (err, recordset) => {
        if (err) {
            console.log("Error getting data from Stored Proc: ", err);
            sql.close();
        }
        if (recordset) {
            console.log("RESULTS: ", recordset);
        } else {
            console.log("NO RECORDS RETURNED for ", env.STOREDPROCS.GET.ALLCOUNTRIES);
        }
        sql.close();

    });
}).catch((err) => {
    console.log("error", err);
});
</code>```

This is phone_types.js (the MODEL)

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let PhoneTypes = new Schema({
    phonetypeid: {
        type: Number
    },
    phonetypename: {
        name: String
    }

}, {
    collection: 'phoneTypes'
})
module.exports = mongoose.model('PhoneTypes', PhoneTypes)
</code>```

All that should come back from the DB is ID (1 - 3), and HOME, CELL, WORK

And finally, phoneTypeRoutes.js

```<code>const express = require("express");
const app = express();
const phoneTypeRoute = express.Router();
const sql = require("mssql");
const PHONE_TYPES = require("../../model/phone_types");
const env = require("../../../environment")
require("msnodesqlv8");
// ConnStr using ODBC
const config = {
    connectionString: "Dsn=" + env.VAFORMS.DSN.ACCRED + ";Driver=" + env.VAFORMS.DRIVER + ";Host=" + env.VAFORMS.HOST.LOCAL + ";Database=" + env.VAFORMS.DBNAME.ACCRED + ";trusted_connection=" + env.VAFORMS.OPTIONS.trustedConnection + ";"
};
const dbConn = new sql.ConnectionPool(config);

let query;
query = env.STOREDPROCS.GET.PHONETYPES;

sql.connect(config).then((dbConn) => {
    console.log("connected for phonetypes");
}).catch((err) => {
    console.log("error", err);
});

// **Get all PhoneTypes NOTE: THIS IS ALL I'm trying for right now...**
phoneTypeRoute.route("/allphonetypes").get((req, res) => {
    PHONE_TYPES.find((error, data) => {
        dbConn.query(query, (err, recordset) => {
            if (data) {
                phonetypes.push(recordset);
                console.log("RESULTS: ", recordset);
                res.send(res.json(recordset));
            } else {
                console.log("NO RECORDS RETURNED for PHONE TYPES.", error);
                return next(err);
            }
            sql.close();
        });
    });
});

// Get A specific PHONETYPE
phoneTypeRoute.route("/read-phonetype/:id").get((req, res) => {
    PHONE_TYPES.findById(req.params.id, (error, data) => {
        if (error) {
            return next(error);
        } else {
            res.json(data);
        }
    });
});

// ADD PHONE TYPE
phoneTypeRoute.route("/add-phonetype").post((req, res, next) => {
    PHONE_TYPES.create(req.body, (error, data) => {
        if (error) {
            return next(error);
        } else {
            res.json(data);
        }
    });
});

// Update PHONETYPE
phoneTypeRoute.route("/update-phonetype/:id").put((req, res, next) => {
    PHONE_TYPES.findByIdAndUpdate(req.params.id, {
        $set: req.body
    }, (error, data) => {
        if (error) {
            console.log(error);
            return next(error);
        } else {
            res.json(data);
            console.log("PHONE TYPE updated successfully!");
        }
    });
});

// Delete PHONETYPE
phoneTypeRoute.route("/delete-phonetype/:id").delete((req, res, next) => {
    PHONE_TYPES.findByIdAndRemove(req.params.id, (error, data) => {
        if (error) {
            return next(error);
        } else {
            console.log("PHONE TYPE deleted successfully!");
            res.status(200).json({msg: data});
        }
    });
});

module.exports = phoneTypeRoute;

</code>```

Now the call from Angular

This is crud.service.ts

```<code>import { Injectable } from '@angular/core';
import { Form21 } from './forms';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import {
  HttpClient,
  HttpHeaders,
  HttpErrorResponse,
} from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Injectable({
  providedIn: 'root',
})
export class CrudService {
  // Node/Express API
  REST_API: string = 'localhost:8000/api';
  // Http Header
  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
  constructor(
    private httpClient: HttpClient
  ) { }
...
  // GET PHONE TYPES
  getPhoneTypes() {
    console.log('PHONETYPES: ', this.REST_API + '/allphonetypes');
    return this.httpClient.get(this.REST_API + '/allphonetypes');
  }
...
  // Error
  handleError(error: HttpErrorResponse): Observable<VAForm21> {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Handle client error
      errorMessage = error.error.message;
    } else {
      // Handle server error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(errorMessage);
    return throwError(() => {
      errorMessage;
    });
  }
}
</code>```

What I'm getting is NOT FOUND in the NODE terminal and in the browser. Angular is hitting NODE but I get nothing.

This is firing the URL by itself. It results in the same error in my app

```<code>const phonetyperoute = require("./node-backend/routes/phoneTypes/phoneTypeRoutes");
</code>```0

Finally, in PREVIEW and RESPONSE this is what I get
Not Found

It's a routing path problem but I can't seem to find out where.

Thank you

Body:
UPDATE: So, I'm putting this here because it's more relevant.

I used another example from BobbyHadz and it's much better.  https://www.digitalocean.com/community/tutorials/build-a-restful-api-using-node-and-express-4

So, the ONLY thing I've done is this.

I made a connection to the DB for getting PhoneTypes and it's working.
I have the ROUTES for CRUD in another file and the REQUIRE for the DB in the routes file and that works, but, what is not working or is out of place, is the data file which contains the RECORDSET (and it's retrieving) is TOO EARLY.

This is in the phoneTypeRoutes.js

const PhoneTypes = require("../../model/phone_types");
const phonetypesdata = require("../../database/phone-types-data");
console.log("PHONE TYPES DATA inside PTROUTE: ", phonetypesdata);

phone-types-data.js is the DATABASE connection.

Then, in index.js, I'm pulling (requiring) the router for phone types like so.

const phonetyperoute = require("./node-backend/routes/phoneTypes/phoneTypeRoutes");

What's happening is this in the console for NODEJS.

[nodemon] starting `node index.js`
PHONE TYPES DATA inside PTROUTE:  { phonetypesDataArray: [] } <<-- TOO EARLY
DB CONNECT is:  {} <<-- TOO EARLY
Listening on port number: 8000
connected for phonetypes
connected branches of service
connected db-conn
ALL PHONE TYPES RETRIEVED:  {
  recordsets: [ [ [Object], [Object], [Object] ] ],
  recordset: [
    { phone_types_id: 1, phone_type_name: 'CELL', rowCnt: 3 },
    { phone_types_id: 2, phone_type_name: 'HOME', rowCnt: 3 },
    { phone_types_id: 3, phone_type_name: 'WORK', rowCnt: 3 }
  ],
  output: {},
  rowsAffected: []
}
RECORDSET PHONETYPES:  [
  [
    { phone_types_id: 1, phone_type_name: 'CELL', rowCnt: 3 },
    { phone_types_id: 2, phone_type_name: 'HOME', rowCnt: 3 },
    { phone_types_id: 3, phone_type_name: 'WORK', rowCnt: 3 }
  ]
]
// Those first two lines need to be DOWN here... AFTER the data comes back

Unless I'm missing something...

Here's the DB call which is working phone-types-data.js

const sql = require("mssql");
const env = require("../../environment.js");
require("msnodesqlv8");
// ConnStr using ODBC
const config = {
  connectionString:
    "Dsn=" +
    env.FORMS.DSN.ACCRED +
    ";Driver=" +
    env.FORMS.DRIVER +
    ";Host=" +
    env.FORMS.HOST.LOCAL +
    ";Database=" +
    env.FORMS.DBNAME.ACCRED +
    ";trusted_connection=" +
    env.FORMS.OPTIONS.trustedConnection +
    ";",
};
const dbConn = new sql.ConnectionPool(config);
let phonetypesDataArray = [];

let query;
query = env.STOREDPROCS.GET.PHONETYPES;

sql
  .connect(config)
  .then((dbConn) => {
    console.log("connected for phonetypes");

    dbConn.query(query, (err, data) => {
      if (err) {
        console.log("Error getting PhoneTypes from Stored Proc: ", err);
        sql.close();
      }
      if (data) {
        console.log("ALL PHONE TYPES RETRIEVED: ", data);
        phonetypesDataArray.push(data.recordset);
        console.log("RECORDSET PHONETYPES: ", phonetypesDataArray);
      } else {
        let errmsg =
          "NO RECORDS RETURNED for " + env.STOREDPROCS.GET.PHONETYPES;
        console.log(errmsg);
        phonetypesDataArray.push({ error: errmsg });
      }
      sql.close();
      // res.send(recordset);
    });
  })
  .catch((err) => {
    console.log("error", err);
    errmsg = `"Error Connecting to Database: ", ${err}`;
    phonetypesDataArray.push(errmsg);
  });

module.exports = { phonetypesDataArray };

I've written a node server app for APIs. I'm calling it from Angular 13.
I got the idea from here... https://medium.com/bb-tutorials-and-thoughts/how-to-make-api-calls-in-angular-applications-ab5364cf9533 but my solution is more complicated and I'm getting NOT FOUND on Node when I ping the server URL or call from Angular.

Here's the dumbed down version of the code:

First NODE:

This is server.js

var Service = require('node-windows').Service;

var svc = new Service({
    name: 'Node Rest API',
    description: 'The nodejs.org example web server.',
    script: 'C:\\somedir\\subdir\\nameofsomething\\node-rest-api\\index.js'
});

// Listen for the "install" event, which indicates the
// process is available as a service.

svc.on('install', function () {
    svc.start();
});

svc.install();

This is index.js

const express = require("express");
const path = require("path");
// const mongoose = require('mongoose');
const cors = require("cors");
const bodyParser = require("body-parser");
const sql = require("mssql");

// ROUTES
const noderoutes = require("./node-backend/routes/form21.routes");
const phonetyperoute = require("./node-backend/routes/phoneTypes/phoneTypeRoutes");
const branchesofservice = require("./node-backend/routes/branchesOfService/branchesRoutes");

const app = express();
const enviro = require("./environment");
const createError = require("http-errors");
const { env } = require("process");
const dbconfig = require("./node-backend/database/db-conn");
const phone_types = require("./node-backend/model/phone_types");

console.log('DB CONNECT is: ', dbconfig);

app.use(bodyParser.json());

app.use(
  bodyParser.urlencoded({
    extended: false,
  })
);

app.use(cors());
app.use(corsOptions);

// Static directory path
app.use(
  express.static(path.join(__dirname, "/"))
);

// API root
app.use("/api/forms", noderoutes);
app.use("/api/phonetypes", phonetyperoute);
app.use("/api/branchesofsvc", branchesofservice);

// PORT
const port = process.env.PORT || 8000;
app.listen(port, () => {
  console.log("Listening on port number: " + port);
});

// 404 Handler
app.use((req, res, next) => {
  next(createError(404));
});

// Base Route
app.get("/", (req, res) => {
  res.send("invaild endpoint");
});

app.get("*", (req, res) => {
  res.sendFile(
    path.join(__dirname, "index.html")
  );
});
// THIS IS WHAT I'm trying to call.
app.get('/allphonetypes', (req,res) => {
  res.json(phone_types);
});

// error handler
app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  res.status(err.statusCode).send(err.message);
});

NEXT the DBConn.js is working and here's that.

This is dbconn.js

const sql = require("mssql");
const env = require("../../environment.js")
require("msnodesqlv8");
// ConnStr using ODBC
const config = {
    connectionString: "Dsn=" + env.VAFORMS.DSN.ACCRED + ";Driver=" + env.VAFORMS.DRIVER + ";Host=" + env.VAFORMS.HOST.LOCAL + ";Database=" + env.VAFORMS.DBNAME.ACCRED + ";trusted_connection=" + env.VAFORMS.OPTIONS.trustedConnection + ";"
};
const dbConn = new sql.ConnectionPool(config);

sql.connect(config).then((dbConn) => {
    console.log("connected db-conn");

    // THIS TEST to my stored proc WORKS FINE and produced 242 records
    let query = "exec " + env.STOREDPROCS.GET.ALLCOUNTRIES;
    dbConn.query(query, (err, recordset) => {
        if (err) {
            console.log("Error getting data from Stored Proc: ", err);
            sql.close();
        }
        if (recordset) {
            console.log("RESULTS: ", recordset);
        } else {
            console.log("NO RECORDS RETURNED for ", env.STOREDPROCS.GET.ALLCOUNTRIES);
        }
        sql.close();

    });
}).catch((err) => {
    console.log("error", err);
});

This is phone_types.js (the MODEL)

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let PhoneTypes = new Schema({
    phonetypeid: {
        type: Number
    },
    phonetypename: {
        name: String
    }

}, {
    collection: 'phoneTypes'
})
module.exports = mongoose.model('PhoneTypes', PhoneTypes)

All that should come back from the DB is ID (1 - 3), and HOME, CELL, WORK

And finally, phoneTypeRoutes.js

const express = require("express");
const app = express();
const phoneTypeRoute = express.Router();
const sql = require("mssql");
const PHONE_TYPES = require("../../model/phone_types");
const env = require("../../../environment")
require("msnodesqlv8");
// ConnStr using ODBC
const config = {
    connectionString: "Dsn=" + env.VAFORMS.DSN.ACCRED + ";Driver=" + env.VAFORMS.DRIVER + ";Host=" + env.VAFORMS.HOST.LOCAL + ";Database=" + env.VAFORMS.DBNAME.ACCRED + ";trusted_connection=" + env.VAFORMS.OPTIONS.trustedConnection + ";"
};
const dbConn = new sql.ConnectionPool(config);

let query;
query = env.STOREDPROCS.GET.PHONETYPES;

sql.connect(config).then((dbConn) => {
    console.log("connected for phonetypes");
}).catch((err) => {
    console.log("error", err);
});

// **Get all PhoneTypes NOTE: THIS IS ALL I'm trying for right now...**
phoneTypeRoute.route("/allphonetypes").get((req, res) => {
    PHONE_TYPES.find((error, data) => {
        dbConn.query(query, (err, recordset) => {
            if (data) {
                phonetypes.push(recordset);
                console.log("RESULTS: ", recordset);
                res.send(res.json(recordset));
            } else {
                console.log("NO RECORDS RETURNED for PHONE TYPES.", error);
                return next(err);
            }
            sql.close();
        });
    });
});

// Get A specific PHONETYPE
phoneTypeRoute.route("/read-phonetype/:id").get((req, res) => {
    PHONE_TYPES.findById(req.params.id, (error, data) => {
        if (error) {
            return next(error);
        } else {
            res.json(data);
        }
    });
});

// ADD PHONE TYPE
phoneTypeRoute.route("/add-phonetype").post((req, res, next) => {
    PHONE_TYPES.create(req.body, (error, data) => {
        if (error) {
            return next(error);
        } else {
            res.json(data);
        }
    });
});

// Update PHONETYPE
phoneTypeRoute.route("/update-phonetype/:id").put((req, res, next) => {
    PHONE_TYPES.findByIdAndUpdate(req.params.id, {
        $set: req.body
    }, (error, data) => {
        if (error) {
            console.log(error);
            return next(error);
        } else {
            res.json(data);
            console.log("PHONE TYPE updated successfully!");
        }
    });
});

// Delete PHONETYPE
phoneTypeRoute.route("/delete-phonetype/:id").delete((req, res, next) => {
    PHONE_TYPES.findByIdAndRemove(req.params.id, (error, data) => {
        if (error) {
            return next(error);
        } else {
            console.log("PHONE TYPE deleted successfully!");
            res.status(200).json({msg: data});
        }
    });
});

module.exports = phoneTypeRoute;

Now the call from Angular

This is crud.service.ts

import { Injectable } from '@angular/core';
import { Form21 } from './forms';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import {
  HttpClient,
  HttpHeaders,
  HttpErrorResponse,
} from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Injectable({
  providedIn: 'root',
})
export class CrudService {
  // Node/Express API
  REST_API: string = 'localhost:8000/api';
  // Http Header
  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
  constructor(
    private httpClient: HttpClient
  ) { }
...
  // GET PHONE TYPES
  getPhoneTypes() {
    console.log('PHONETYPES: ', this.REST_API + '/allphonetypes');
    return this.httpClient.get(this.REST_API + '/allphonetypes');
  }
...
  // Error
  handleError(error: HttpErrorResponse): Observable<VAForm21> {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Handle client error
      errorMessage = error.error.message;
    } else {
      // Handle server error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(errorMessage);
    return throwError(() => {
      errorMessage;
    });
  }
}

What I'm getting is NOT FOUND in the NODE terminal and in the browser. Angular is hitting NODE but I get nothing.

This is firing the URL by itself. It results in the same error in my app

Request URL: http://localhost:8000/api/allphonetypes
Request Method: GET
Status Code: 404 Not Found
Remote Address: [::1]:8000
Referrer Policy: strict-origin-when-cross-origin

Finally, in PREVIEW and RESPONSE this is what I get
Not Found

It's a routing path problem but I can't seem to find out where.

Thank you


问:
Can I use domain-specific wwwroot folders in my project?
So I've been studying the documentation of.net Core Middleware and I'm working on a minimal Web API with an additional wwwroot folder containing static HTML content with CSS and Javascript. This is basically a demo for the Web API in the same project. The JS in this folder calls some of the API methods in it to provide various content.

But I want to use this API with several different domain names so they all share the same API. But the domains would each need their own wwwroot with static pages. And my Web API will use app.UseWhen() combined with the domain name to have some domain-specific methods per domain. This would allow me to have one site supporting multiple domains.   This filtering based on domain names should be simple, but they would all share the same wwwroot. I want each domain to have it's own root.

Now, UseWebRoot() seems to solve this, except it gets called from the builder, not the app. This means I only get one where I want many.

It seems that app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "DomainName")) }) would work. (ContentRootPath, not WebRootPath, as I want the wwwroot folder to stay clean.)

Is this the proper approach to have custom static pages per domain?

These static files in the wwwroot will not be under control of the project itself, but are generated by another team member separately. They are front-end developers who just make things look more fancy per domain. (And in different languages where need be.) And while these sites could be different sites, I want to know if it can be contained inside one project.


问:
Global variable changed when reading other value from html
I have defined global variable of universitySelected and domain at the top of my code, however, the universitySelected value was overwritten after email := c.FormValue("email").

For example, the universitySelected was "Harvard University" but after email := c.FormValue("email"), the universitySelected became "ex@harvard.edusity"

Here is how I defined my global variable and where it get overwritten

```<code>var universitySelected string
var domain string

func HandleRegistration(c *fiber.Ctx) error {
    // Get the form values
    email := c.FormValue("email")
    password := c.FormValue("password")

    if !strings.Contains(email, ".edu") {

        return c.Render("signup", fiber.Map{
            "UniversityName": universitySelected
            "UniversityDomain": domain,
            "ErrorMessage":     "Email Domain Not Supported",
        })
    }
.
.
.

</code>```

Here is how I get universitySelected value

```<code>func HandleUniversitySelection(c *fiber.Ctx) error {
    universitySelected = c.FormValue("university")
    err := db.QueryRow("SELECT domain FROM universities WHERE name = $1", universitySelected).Scan(&domain)
    if err != nil {
        return err
    }

    return c.Render("signup", fiber.Map{
        "UniversityName": universitySelected,
        "UniversityDomain": domain,
    })

</code>```

Body:
I have defined global variable of universitySelected and domain at the top of my code, however, the universitySelected value was overwritten after email := c.FormValue("email").

For example, the universitySelected was "Harvard University" but after email := c.FormValue("email"), the universitySelected became "ex@harvard.edusity"

Here is how I defined my global variable and where it get overwritten

var universitySelected string
var domain string

func HandleRegistration(c *fiber.Ctx) error {
    // Get the form values
    email := c.FormValue("email")
    password := c.FormValue("password")

    if !strings.Contains(email, ".edu") {

        return c.Render("signup", fiber.Map{
            "UniversityName": universitySelected
            "UniversityDomain": domain,
            "ErrorMessage":     "Email Domain Not Supported",
        })
    }
.
.
.

Here is how I get universitySelected value

func HandleUniversitySelection(c *fiber.Ctx) error {
    universitySelected = c.FormValue("university")
    err := db.QueryRow("SELECT domain FROM universities WHERE name = $1", universitySelected).Scan(&domain)
    if err != nil {
        return err
    }

    return c.Render("signup", fiber.Map{
        "UniversityName": universitySelected,
        "UniversityDomain": domain,
    })


问:
CSS - Move from current position to new fixed position
I'm trying to put some buttons on my site, but I'm struggling with positioning some of the animated elements.  See the example:

https://codepen.io/dev_loop/pen/MWKYoGJ

```<code><div class="btn-container">
    <button>
        <span class="text">Hover1</span>
        <div class="icon-container">
            <div class="icon icon--left">
                <svg>
                    <use xlink:href="#arrow-right"></use>
                </svg>
            </div>
            <div class="icon icon--right">
                <svg>
                    <use xlink:href="#arrow-right"></use>
                </svg>
            </div>
        </div>
    </button>
</div>

<div class="btn-container">
    <button>
        <span class="text">Hover2Test</span>
        <div class="icon-container">
            <div class="icon icon--left">
                <svg>
                    <use xlink:href="#arrow-right"></use>
                </svg>
            </div>
            <div class="icon icon--right">
                <svg>
                    <use xlink:href="#arrow-right"></use>
                </svg>
            </div>
        </div>
    </button>
</div>

<svg style="display: none;">
    <symbol id="arrow-right" viewBox="0 0 20 10">
        <path d="M14.84 0l-1.08 1.06 3.3 3.2H0v1.49h17.05l-3.3 3.2L14.84 10 20 5l-5.16-5z"></path>
    </symbol>
</svg>

<div class="support">
    <a href="https://twitter.com/DevLoop01" target="_blank"><i class="fab fa-twitter-square"></i></a>
    <a href="https://dribbble.com/devloop01" target="_blank"><i class="fab fa-dribbble"></i></a>
</div>
</code>```
```<code>
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    width: 100%;
    height: 100vh;
    display: flex;
    overflow: hidden;
}

.btn-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: var(--bg);

    &:nth-child(1) {
        --btn-bg: #da0000;
        --bg: #f22c3a;
    }
    &:nth-child(2) {
        --btn-bg: #fac300;
        --bg: #fc6100;
    }
}

button {
    --width: 180px;
    --height: 60px;
    border: 0;
    position: relative;
    min-width: var(--width);
    min-height: var(--height);
    border-radius: var(--height);
    color: #fff;
    font-family: "Montserrat";
    font-weight: bold;
    background: rgba(0, 0, 0, 0.3);
    cursor: pointer;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 1rem;

    .text,
    .icon-container {
        position: relative;
        z-index: 2;
    }

    .icon-container {
        --icon-size: 25px;
        position: relative;
        width: var(--icon-size);
        height: var(--icon-size);
        margin-left: 15px;
        transition: transform 500ms ease;

        .icon {
            position: absolute;
            left: 0;
            top: 0;
            width: var(--icon-size);
            height: var(--icon-size);
            transition: transform 500ms ease, opacity 250ms ease;

            &--left {
                transform: translateX(-200%);
                opacity: 0;
            }

            svg {
                width: 100%;
                height: 100%;
                fill: #fff;
            }
        }
    }

    &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: var(--btn-bg);
        border-radius: var(--height);
        z-index: 1;
        transition: transform 500ms ease;
    }

    &:hover {
        &::after {
            transform: translateX(65%);
        }

        .icon-container {
            transform: translateX(125%);
            .icon {
                &--left {
                    transform: translateX(0);
                    opacity: 1;
                }
                &--right {
                    transform: translateX(200%);
                    opacity: 0;
                }
            }
        }
    }
}

.support{
    position: absolute;
    right: 10px;
    bottom: 10px;
    padding: 10px;
    display: flex;
    a{
        margin: 0 10px;
        color: #fff;
        font-size: 1.8rem;
        backface-visibility: hidden;
        transition: all 150ms ease;
        &:hover{
            transform: scale(1.1);
        }
    }

}
</code>```

In the above, everything works perfectly until you change the text contained within the button itself. Doing this throws off the "hover" positioning of the SVG arrow element, since its parent containers position is decided by the text on the button and its a percentage based translateX.

I want to use this code across multiple buttons with different text on each button and I'm looking to implement something on the transition effects like:

"Move the SVG from whatever its current position is, to right:0; or so when hovered, so the arrow is essentially right aligned"

What I've ended up doing in my code, is creating two different containers for the SVG; One positioned relatively in the "left" position, and another positioned absolute with a right:18px property to "stick" it to the right hand side of the button.  I've then animated the opacity and translateX to try and make it look like its following the wipe effect of the button, but it's not really working nicely and looks janky.

https://codepen.io/Delarado/pen/yLqOBRr

```<code>     <div class="btn-container">
            <button>
                <span class="text">Reset</span>
                <div class="icon-container icon-container--left">
                <div class="icon">
                    <svg>
                        <use xlink:href="#arrow-right"></use>
                    </svg>
                </div>
                </div>

                <div class="icon-container icon-container--right">
                <div class="icon">
                    <svg>
                        <use xlink:href="#arrow-right"></use>
                    </svg>
                </div>
                </div>
            </button>
            </div>

<svg style="display: none;">
                <symbol id="arrow-right" viewBox="0 0 20 10">
                    <path d="M14.84 0l-1.08 1.06 3.3 3.2H0v1.49h17.05l-3.3 3.2L14.84 10 20 5l-5.16-5z"></path>
                </symbol>
            </svg>
</code>```
```<code>.btn-container {
    width: 100%;
    height: 100%;
    margin: 1em 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background: var(--bg);
    --btn-bg: #ff9900;
}

button {
    --width: 13em;
    --height: 60px;
    border: 0;
    position: relative;
    min-width: var(--width);
    min-height: var(--height);
    border-radius: var(--height);
    color: #fff;
    font-weight: bold;
    font-size: 1.1rem;
    background: #ff990075;
    cursor: pointer;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 1rem;
    border-color: #00000050;
    border-width: 1px;
    border-style: solid;

    .text,
    .icon-container {
        position: relative;
        z-index: 2;
    }

    .icon-container {
        --icon-size: 25px;
        position: relative;
        width: var(--icon-size);
        height: var(--icon-size);
        margin-left: 10px;
        transition: transform 500ms ease;
        .icon {
            position: absolute;
            left: 0;
            top: 0;
            width: var(--icon-size);
            height: var(--icon-size);
            transition: transform 500ms ease, opacity 250ms ease;

            svg {
                width: 100%;
                height: 100%;
                fill: #fff;
            }
        }
        &--right {
            //transform: translateX(-200%);
            display:none;
        }
    }

    &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: var(--btn-bg);
        border-radius: var(--height);
        z-index: 1;
        transition: transform 500ms ease;
    }

    &:hover {
        //The color of the text upon hovering
        color: #000;
        &::after {
            //The position of the circle upon hovering
            transform: translateX(73%);
        }

        .icon-container {
            // //The position of the arrow upon hovering
            // //transform: translateX(25%);
            &--left {
                opacity: 0;
                animation: Arrowgo 500ms forwards;
            }
            &--right {
                position: absolute;
                right:18px;
                display:unset;
                animation: Arrowarrive 500ms forwards;
            }
        }
    }
}

@keyframes Arrowgo {
    from{
        opacity:1;
        transform: translateX(0);
    }
    to{
        opacity:0;
        transform:translateX(20px);
    }
}

@keyframes Arrowarrive {
    from{
        opacity:0;
        transform: translateX(-20px);
    }
    to{
        opacity:1;
        transform:translateX(0);
    }
}
</code>```

I also tried a single element with relative position, animated to absolute position on hover but that also looked awful. I can't figure out how to place it just to the right of the button text in a normal state, and then animate it from there over to the right hand side on hover.

I was wondering if anyone smarter than me had a nice elegant solution to this that avoids having a different class for each button to account for the different length text, whilst still maintaining a nice slick wipe effect on both the "secondary" button and the arrow SVG?

Thanks in advance!

Body:
I'm trying to put some buttons on my site, but I'm struggling with positioning some of the animated elements.  See the example:

https://codepen.io/dev_loop/pen/MWKYoGJ

    <button>
        Hover1

                <svg>
                    <use xlink:href="#arrow-right"></use>
                </svg>

                <svg>
                    <use xlink:href="#arrow-right"></use>
                </svg>

    </button>

    <button>
        Hover2Test

                <svg>
                    <use xlink:href="#arrow-right"></use>
                </svg>

                <svg>
                    <use xlink:href="#arrow-right"></use>
                </svg>

    </button>

<svg style="display: none;">
    <symbol id="arrow-right" viewBox="0 0 20 10">
        <path d="M14.84 0l-1.08 1.06 3.3 3.2H0v1.49h17.05l-3.3 3.2L14.84 10 20 5l-5.16-5z"></path>
    </symbol>
</svg>

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    width: 100%;
    height: 100vh;
    display: flex;
    overflow: hidden;
}

.btn-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: var(--bg);

    &:nth-child(1) {
        --btn-bg: #da0000;
        --bg: #f22c3a;
    }
    &:nth-child(2) {
        --btn-bg: #fac300;
        --bg: #fc6100;
    }
}

button {
    --width: 180px;
    --height: 60px;
    border: 0;
    position: relative;
    min-width: var(--width);
    min-height: var(--height);
    border-radius: var(--height);
    color: #fff;
    font-family: "Montserrat";
    font-weight: bold;
    background: rgba(0, 0, 0, 0.3);
    cursor: pointer;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 1rem;

    .text,
    .icon-container {
        position: relative;
        z-index: 2;
    }

    .icon-container {
        --icon-size: 25px;
        position: relative;
        width: var(--icon-size);
        height: var(--icon-size);
        margin-left: 15px;
        transition: transform 500ms ease;

        .icon {
            position: absolute;
            left: 0;
            top: 0;
            width: var(--icon-size);
            height: var(--icon-size);
            transition: transform 500ms ease, opacity 250ms ease;

            &--left {
                transform: translateX(-200%);
                opacity: 0;
            }

            svg {
                width: 100%;
                height: 100%;
                fill: #fff;
            }
        }
    }

    &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: var(--btn-bg);
        border-radius: var(--height);
        z-index: 1;
        transition: transform 500ms ease;
    }

    &:hover {
        &::after {
            transform: translateX(65%);
        }

        .icon-container {
            transform: translateX(125%);
            .icon {
                &--left {
                    transform: translateX(0);
                    opacity: 1;
                }
                &--right {
                    transform: translateX(200%);
                    opacity: 0;
                }
            }
        }
    }
}

.support{
    position: absolute;
    right: 10px;
    bottom: 10px;
    padding: 10px;
    display: flex;
    a{
        margin: 0 10px;
        color: #fff;
        font-size: 1.8rem;
        backface-visibility: hidden;
        transition: all 150ms ease;
        &:hover{
            transform: scale(1.1);
        }
    }

}

In the above, everything works perfectly until you change the text contained within the button itself. Doing this throws off the "hover" positioning of the SVG arrow element, since its parent containers position is decided by the text on the button and its a percentage based translateX.

I want to use this code across multiple buttons with different text on each button and I'm looking to implement something on the transition effects like:

"Move the SVG from whatever its current position is, to right:0; or so when hovered, so the arrow is essentially right aligned"

What I've ended up doing in my code, is creating two different containers for the SVG; One positioned relatively in the "left" position, and another positioned absolute with a right:18px property to "stick" it to the right hand side of the button.  I've then animated the opacity and translateX to try and make it look like its following the wipe effect of the button, but it's not really working nicely and looks janky.

https://codepen.io/Delarado/pen/yLqOBRr

            <button>
                Reset

                    <svg>
                        <use xlink:href="#arrow-right"></use>
                    </svg>

                    <svg>
                        <use xlink:href="#arrow-right"></use>
                    </svg>

            </button>

<svg style="display: none;">
                <symbol id="arrow-right" viewBox="0 0 20 10">
                    <path d="M14.84 0l-1.08 1.06 3.3 3.2H0v1.49h17.05l-3.3 3.2L14.84 10 20 5l-5.16-5z"></path>
                </symbol>
            </svg>

.btn-container {
    width: 100%;
    height: 100%;
    margin: 1em 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background: var(--bg);
    --btn-bg: #ff9900;
}

button {
    --width: 13em;
    --height: 60px;
    border: 0;
    position: relative;
    min-width: var(--width);
    min-height: var(--height);
    border-radius: var(--height);
    color: #fff;
    font-weight: bold;
    font-size: 1.1rem;
    background: #ff990075;
    cursor: pointer;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 1rem;
    border-color: #00000050;
    border-width: 1px;
    border-style: solid;

    .text,
    .icon-container {
        position: relative;
        z-index: 2;
    }

    .icon-container {
        --icon-size: 25px;
        position: relative;
        width: var(--icon-size);
        height: var(--icon-size);
        margin-left: 10px;
        transition: transform 500ms ease;
        .icon {
            position: absolute;
            left: 0;
            top: 0;
            width: var(--icon-size);
            height: var(--icon-size);
            transition: transform 500ms ease, opacity 250ms ease;

            svg {
                width: 100%;
                height: 100%;
                fill: #fff;
            }
        }
        &--right {
            //transform: translateX(-200%);
            display:none;
        }
    }

    &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: var(--btn-bg);
        border-radius: var(--height);
        z-index: 1;
        transition: transform 500ms ease;
    }

    &:hover {
        //The color of the text upon hovering
        color: #000;
        &::after {
            //The position of the circle upon hovering
            transform: translateX(73%);
        }

        .icon-container {
            // //The position of the arrow upon hovering
            // //transform: translateX(25%);
            &--left {
                opacity: 0;
                animation: Arrowgo 500ms forwards;
            }
            &--right {
                position: absolute;
                right:18px;
                display:unset;
                animation: Arrowarrive 500ms forwards;
            }
        }
    }
}

@keyframes Arrowgo {
    from{
        opacity:1;
        transform: translateX(0);
    }
    to{
        opacity:0;
        transform:translateX(20px);
    }
}

@keyframes Arrowarrive {
    from{
        opacity:0;
        transform: translateX(-20px);
    }
    to{
        opacity:1;
        transform:translateX(0);
    }
}

I also tried a single element with relative position, animated to absolute position on hover but that also looked awful. I can't figure out how to place it just to the right of the button text in a normal state, and then animate it from there over to the right hand side on hover.

I was wondering if anyone smarter than me had a nice elegant solution to this that avoids having a different class for each button to account for the different length text, whilst still maintaining a nice slick wipe effect on both the "secondary" button and the arrow SVG?

Thanks in advance!


问:
Migration of hazelcast from 3.x.x to 5.x.x using javaclient cause problem because of absence of EntryBackupProcessor.java
what i can used instead of the EntryBackupProcessor.java

```<code>import java.io.Serializable;
import java.util.Map;

public interface EntryBackupProcessor<K, V,R> extends Serializable {

    void processBackup(Map.Entry<K, V> entry);
}
</code>```

Body:
what i can used instead of the EntryBackupProcessor.java

import java.io.Serializable;
import java.util.Map;

public interface EntryBackupProcessor<K, V,R> extends Serializable {

    void processBackup(Map.Entry<K, V> entry);
}


问:
Android get Touch Position on a remote device and reflect the same position on server screen
Good wishes to all. I am having a situation where I have a streaming server,That runs a video (width = 1260, height = 690). I get this Url and play it in a WebView with random size (as of Android devices are with different resolution and densities.and I have used flexible layout to accommodate space available ). Now my question is if someone click on the video to track in object position, how can I reflect same pixel position on the server screen, Tracking logic as on the server, I need only to send the X,Y coordinates. Any help is much appreciated.

I have tried to get device resolution. matches it with server screen, but target not achieved.


问:
Display Image from folder while the path is in Database In RDLC Report ASP.Net MVC5
How to show pictures which are located in a folder and the path is in the database But I'm unable to Do it.

```<code>testingDataSet RTP = new testingDataSet();

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
         ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/RTPrpt.rdlc");
         FillRTP();

         ReportDataSource dataSource = new ReportDataSource("DataSetRTP", RTP.Tables["RTPView"]);
         ReportViewer1.LocalReport.DataSources.Clear();
         ReportViewer1.LocalReport.DataSources.Add(dataSource);
         ReportViewer1.LocalReport.Refresh();
     }

     private void FillRTP()
     {
         string connectionString = Properties.Settings.Default.ETHADAIMS;

         using (SqlConnection sqlConnection = new SqlConnection(connectionString))
         {
             string queryString = string.Empty;
             queryString = " select * from RTPView";
             SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(queryString, sqlConnection);
             sqlDataAdapter.Fill(RTP, RTP.Tables["RTPView"].TableName);
         }
     }
}
</code>```

enter image description here

Photos are not visible. How can I make them to be visible?

Body:
How to show pictures which are located in a folder and the path is in the database But I'm unable to Do it.

testingDataSet RTP = new testingDataSet();

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
         ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/RTPrpt.rdlc");
         FillRTP();

         ReportDataSource dataSource = new ReportDataSource("DataSetRTP", RTP.Tables["RTPView"]);
         ReportViewer1.LocalReport.DataSources.Clear();
         ReportViewer1.LocalReport.DataSources.Add(dataSource);
         ReportViewer1.LocalReport.Refresh();
     }

     private void FillRTP()
     {
         string connectionString = Properties.Settings.Default.ETHADAIMS;

         using (SqlConnection sqlConnection = new SqlConnection(connectionString))
         {
             string queryString = string.Empty;
             queryString = " select * from RTPView";
             SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(queryString, sqlConnection);
             sqlDataAdapter.Fill(RTP, RTP.Tables["RTPView"].TableName);
         }
     }
}

enter image description here

Photos are not visible. How can I make them to be visible?


问:
Executing script file in postgres database of keycloak
Can anyone help provide a script to import or run the sql exported script in the Keycloak PostgreSQL database?

I'm looking for a script to import database data.

I attempted it but was unsuccessful.

kubectl run psql-postgresql-client --rm --tty -i --restart='Never' --namespace ucp --image docker.io/bitnami/postgresql:11.7.0-debian-10-r37 --env="PGPASSWORD=$POSTGRES_PASSWORD"  --command -- psql --host postgresql -U kong -d keycloakdb -p 5432 --file \i keycloak.sql
psql: warning: extra command-line argument "keycloak.sql" ignored
i: No such file or directory
pod "psql-postgresql-client" deleted
pod ucp/psql-postgresql-client terminated (Error)


问:
Can't display Sport Event and Odds from 2 different text files
My name is Tiago and I'm a begginer trying to code a script to help me with arbitrage betting. Anyways, the script uses selenium to scrape the name of two teams (portuguese soccer teams) and also scrapes the odds of those games. Basically everything works fine, except for when I run the finder_of_surebets.py the output isn't quite what I want.

```<code>
</code>```

import itertools
from decimal import Decimal

with open ('sports_event_organizer','r') as namesFile,open('odds_organizer','r') as oddsFile:
name_list = [line for line in itertools.zip_longest(*[namesFile]2)]
odd_list = [line for line in itertools.zip_longest([oddsFile]*3)]
for team, odd in zip(name_list, odd_list):
print(team,odd)
print()

```<code>The namesFile contains the name of the teams that are going to play in that day. It's a list, and they are supposed to be grouped in pairs! (Example: team a, team b, team c,team d: the matches are supposed to be team a vs team b, team c vs team d)
The oddsFile contains the 3 odds for the 3 possible outcomes (win,draw, lost) , it's not really easy to understand, but take a look at the script and try to understand what I mean.

</code>```

namesFile

```<code>PORTIMONENSE
CASA PIA
GIL VICENTE
SANTA CLARA
ESTORIL
BOAVISTA FC
CHAVES
FAMALICÃO
SANTA CLARA
SPORTING BRAGA
FAMALICÃO
FC VIZELA
FC AROUCA
ESTORIL
CASA PIA
FC PORTO
MARITIMO
SPORTING CP
BOAVISTA FC
GIL VICENTE
</code>```

oddsFile

```<code>2.37
3.10
3.00
2.15
3.20
3.35
2.25
3.15
3.15
2.45
3.10
2.85
4.90
3.55
1.70
2.55
3.20
2.67
2.55
3.15
2.72
9.50
5.00
1.29
7.50
4.05
1.42
</code>```

Output: ('PORTIMONENSE\n', 'CASA PIA\n') ('2.37\n', '3.10\n', '3.00\n')
('GIL VICENTE\n', 'SANTA CLARA\n') ('2.15\n', '3.20\n', '3.35\n')
('ESTORIL\n', 'BOAVISTA FC\n') ('2.25\n', '3.15\n', '3.15\n')
('CHAVES\n', 'FAMALICÃO\n') ('2.45\n', '3.10\n', '2.85\n')
('SANTA CLARA\n', 'SPORTING BRAGA\n') ('4.90\n', '3.55\n', '1.70\n')
('FAMALICÃO\n', 'FC VIZELA\n') ('2.55\n', '3.20\n', '2.67\n')
('FC AROUCA\n', 'ESTORIL\n') ('2.55\n', '3.15\n', '2.72\n')
('CASA PIA\n', 'FC PORTO\n') ('9.50\n', '5.00\n', '1.29\n')
('MARITIMO\n', 'SPORTING CP\n') ('7.50\n', '4.05\n', '1.42\n')

is there any cleaner way of doing this? even though the odds are correct and are where they should be, I don't like the amount of \n and '' and ().
Desired Output: Team 1 - Team 2
Odd 1
Odd x (draw)
Odd 2

Team 3 - Team 4
Odd 1
Odd x
Odd 2

```<code>

</code>```

Body:
My name is Tiago and I'm a begginer trying to code a script to help me with arbitrage betting. Anyways, the script uses selenium to scrape the name of two teams (portuguese soccer teams) and also scrapes the odds of those games. Basically everything works fine, except for when I run the finder_of_surebets.py the output isn't quite what I want.

import itertools
from decimal import Decimal

with open ('sports_event_organizer','r') as namesFile,open('odds_organizer','r') as oddsFile:
name_list = [line for line in itertools.zip_longest(*[namesFile]2)]
odd_list = [line for line in itertools.zip_longest([oddsFile]*3)]
for team, odd in zip(name_list, odd_list):
print(team,odd)
print()

The namesFile contains the name of the teams that are going to play in that day. It's a list, and they are supposed to be grouped in pairs! (Example: team a, team b, team c,team d: the matches are supposed to be team a vs team b, team c vs team d)
The oddsFile contains the 3 odds for the 3 possible outcomes (win,draw, lost) , it's not really easy to understand, but take a look at the script and try to understand what I mean.

namesFile

PORTIMONENSE
CASA PIA
GIL VICENTE
SANTA CLARA
ESTORIL
BOAVISTA FC
CHAVES
FAMALICÃO
SANTA CLARA
SPORTING BRAGA
FAMALICÃO
FC VIZELA
FC AROUCA
ESTORIL
CASA PIA
FC PORTO
MARITIMO
SPORTING CP
BOAVISTA FC
GIL VICENTE

oddsFile

2.37
3.10
3.00
2.15
3.20
3.35
2.25
3.15
3.15
2.45
3.10
2.85
4.90
3.55
1.70
2.55
3.20
2.67
2.55
3.15
2.72
9.50
5.00
1.29
7.50
4.05
1.42

Output: ('PORTIMONENSE\n', 'CASA PIA\n') ('2.37\n', '3.10\n', '3.00\n')
('GIL VICENTE\n', 'SANTA CLARA\n') ('2.15\n', '3.20\n', '3.35\n')
('ESTORIL\n', 'BOAVISTA FC\n') ('2.25\n', '3.15\n', '3.15\n')
('CHAVES\n', 'FAMALICÃO\n') ('2.45\n', '3.10\n', '2.85\n')
('SANTA CLARA\n', 'SPORTING BRAGA\n') ('4.90\n', '3.55\n', '1.70\n')
('FAMALICÃO\n', 'FC VIZELA\n') ('2.55\n', '3.20\n', '2.67\n')
('FC AROUCA\n', 'ESTORIL\n') ('2.55\n', '3.15\n', '2.72\n')
('CASA PIA\n', 'FC PORTO\n') ('9.50\n', '5.00\n', '1.29\n')
('MARITIMO\n', 'SPORTING CP\n') ('7.50\n', '4.05\n', '1.42\n')

is there any cleaner way of doing this? even though the odds are correct and are where they should be, I don't like the amount of \n and '' and ().
Desired Output: Team 1 - Team 2
Odd 1
Odd x (draw)
Odd 2

Team 3 - Team 4
Odd 1
Odd x
Odd 2


问:
Merge Two Large Adjacent Meshes at Boundary Face
I’m trying to merge two adjacent large 3D independently meshed volume meshes at a single face, such that there is only overlap is right at that face and the nodes aren’t guaranteed to overlap. I could obviously retriangulate with Delaunay the entire merged mesh, but that would be very wasteful since I only need to retriangulate the boundary face. Is there a way with CGAL that I can force retriangulation on only the boundary nodes?

Perhaps I need to select the boundary nodes and all nodes within some alpha distance from the boundary, triangulate that and then merge that into the larger mesh.


问:
How to get values from Fortran DLL using Python?
I have Fortran dll(FortDll.dll) similar to;

```<code>integer function FortAddr(x) bind(c, name="FORTADDR") RESULT(res)
!DEC$ ATTRIBUTES DLLEXPOR::FortAddr
use, intrinsic :: iso_c_binding
integer(kind=c_int), intent(in) :: x
integer :: y

y = 2*x
res = loc(y)
end function
</code>```

I want to import Fortran data to visualize using python.
And from python, I call it as

```<code>import ctypes

flib = CDLL('FortDll.dll')
x = c_int(15)
addrx = flib.FORTADDR(byref(x))
val = ctypes.cast(addrx, ctypes.py_object).value
</code>```

But Python script stops at ctypes.cast. How can I get the value in Fortran dll?

Body:
I have Fortran dll(FortDll.dll) similar to;

integer function FortAddr(x) bind(c, name="FORTADDR") RESULT(res)
!DEC$ ATTRIBUTES DLLEXPOR::FortAddr
use, intrinsic :: iso_c_binding
integer(kind=c_int), intent(in) :: x
integer :: y

y = 2*x
res = loc(y)
end function

I want to import Fortran data to visualize using python.
And from python, I call it as

import ctypes

flib = CDLL('FortDll.dll')
x = c_int(15)
addrx = flib.FORTADDR(byref(x))
val = ctypes.cast(addrx, ctypes.py_object).value

But Python script stops at ctypes.cast. How can I get the value in Fortran dll?