问:
Serial read operation not getting timed out despite setting SerialPort.ReadTimeout property?
I am developing an HMI for displaying the data acquired from 8 (Data Acquisition DAQ) cards each having 8 channels through serial port (RS-232).

I want to implement a time-out operation in which the HMI should dispay a message if a particular DAQ card wasn't able to serially send its acquired data within a specific time interval (let's say 20 seconds), and then continue to acquire data from the remaining cards.

For this I am setting the serialPort.ReadTimeout = 20000 but the operation isn't getting properly timed out as expected.

I am using the BackgroundWorker class to serially send and acquire data of 4000 samples from the cards and it is working fine except for the time-out function. Can anyone point out the issue?

```<code>//code snippet
    serialP.DataBits = 8;
    serialP.StopBits = StopBits.One;
    //serialP.Handshake = Handshake.RequestToSend;
    serialP.Parity = Parity.None;

    serialP.DataReceived += serialP_DataReceived;

    serialP.WriteTimeout = 20000;
    serialP.ReadTimeout = 20000;

    serialP.Open();

    serialRtx.DoWork += serialRtx_DoWork;

    if (!serialRtx.IsBusy)
        serialRtx.RunWorkerAsync();

    serialRtx.RunWorkerCompleted += serialRtx_RunWorkerCompleted;

}

    private void serialRtx_DoWork(object sender, DoWorkEventArgs e)
    {
     //Send token packets to DAQ cards sequentially
    }

    private void serialP_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        while (serialP.BytesToRead > 0)
        {
            dataBytet1 = serialP.ReadByte();
            dataByte2 = serialP.ReadByte();

            try
            {
                logData[sample_No, chNo - 1] = ((dataBytet1 * 256) + dataByte2 );

                chNo++;

                if (chNo > 8)
                {
                    sample_No++;
                    chNo = 1;
                }

                if (sample_No > 3999)//total 4000 samples of 8 channels
                {
                    cardNo++;
                    sample_No = 0;
                }
            }
            catch (IndexOutOfRangeException)
            { }
        }
    }

</code>```

Body:
I am developing an HMI for displaying the data acquired from 8 (Data Acquisition DAQ) cards each having 8 channels through serial port (RS-232).

I want to implement a time-out operation in which the HMI should dispay a message if a particular DAQ card wasn't able to serially send its acquired data within a specific time interval (let's say 20 seconds), and then continue to acquire data from the remaining cards.

For this I am setting the serialPort.ReadTimeout = 20000 but the operation isn't getting properly timed out as expected.

I am using the BackgroundWorker class to serially send and acquire data of 4000 samples from the cards and it is working fine except for the time-out function. Can anyone point out the issue?

//code snippet
    serialP.DataBits = 8;
    serialP.StopBits = StopBits.One;
    //serialP.Handshake = Handshake.RequestToSend;
    serialP.Parity = Parity.None;

    serialP.DataReceived += serialP_DataReceived;

    serialP.WriteTimeout = 20000;
    serialP.ReadTimeout = 20000;

    serialP.Open();

    serialRtx.DoWork += serialRtx_DoWork;

    if (!serialRtx.IsBusy)
        serialRtx.RunWorkerAsync();

    serialRtx.RunWorkerCompleted += serialRtx_RunWorkerCompleted;

}

    private void serialRtx_DoWork(object sender, DoWorkEventArgs e)
    {
     //Send token packets to DAQ cards sequentially
    }

    private void serialP_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        while (serialP.BytesToRead > 0)
        {
            dataBytet1 = serialP.ReadByte();
            dataByte2 = serialP.ReadByte();

            try
            {
                logData[sample_No, chNo - 1] = ((dataBytet1 * 256) + dataByte2 );

                chNo++;

                if (chNo > 8)
                {
                    sample_No++;
                    chNo = 1;
                }

                if (sample_No > 3999)//total 4000 samples of 8 channels
                {
                    cardNo++;
                    sample_No = 0;
                }
            }
            catch (IndexOutOfRangeException)
            { }
        }
    }


来源: stackexchange

问:
Getting exception in Writing Spark Structured Streaming to HBase Table
As described in Spark Structured Streaming with Hbase integration, I'm interesting in writing data to HBase in structured streaming framework. I've cloned SHC code from github, extend it by sync provider and trying to write records to HBase. Buy, I've received error: """Queries with streaming sources must be executed with writeStream.start(). My python code is below:

JARS

Spark version: 2.4.0, scala.version: 2.11.8, com.hortonworks.shc-core: 1.1.1-2.1-s_2.11 spark-sql-kafka-0-10_2.11

```<code>    spark = SparkSession \
        .builder \
        .appName("SparkConsumer") \
        .getOrCreate()

    print 'read Avro schema from file: {}...'.format(schema_name)
    schema = avro.schema.parse(open(schema_name, 'rb').read())
    reader = avro.io.DatumReader(schema)
    print 'the schema is read'

    rows = spark \
        .readStream \
        .format('kafka') \
        .option('kafka.bootstrap.servers', brokers) \
        .option('subscribe', topic) \
        .option('group.id', group_id) \
        .option('maxOffsetsPerTrigger', 1000) \
        .option("startingOffsets", "earliest") \
        .load()
    rows.printSchema()

    schema = StructType([ \
            StructField('consumer_id', StringType(), False), \
            StructField('audit_system_id', StringType(), False), \
            StructField('object_path', StringType(), True), \
            StructField('object_type', StringType(), False), \
            StructField('what_action', StringType(), False), \
            StructField('when', LongType(), False), \
            StructField('where', StringType(), False), \
            StructField('who', StringType(), True), \
            StructField('workstation', StringType(), True) \
        ])

    def decode_avro(msg):
        bytes_reader = io.BytesIO(bytes(msg))
        decoder = avro.io.BinaryDecoder(bytes_reader)
        data = reader.read(decoder)
        return (\
                data['consumer_id'],\
                data['audit_system_id'],\
                data['object_path'],\
                data['object_type'],\
                data['what_action'],\
                data['when'],\
                data['where'],\
                data['who'],\
                data['workstation']\
               )

    udf_decode_avro = udf(decode_avro, schema)

    values = rows.select('value')
    values.printSchema()

    changes = values.withColumn('change', udf_decode_avro(col('value'))).select('change.*')
    changes.printSchema()

    change_catalog = '''
    {
        "table":
        {
            "namespace": "uba_input",
            "name": "changes"
        },
        "rowkey": "consumer_id",
        "columns":
        {
            "consumer_id": {"cf": "rowkey", "col": "consumer_id", "type": "string"},
            "audit_system_id": {"cf": "data", "col": "audit_system_id", "type": "string"},
            "object_path": {"cf": "data", "col": "object_path", "type": "string"},
            "object_type": {"cf": "data", "col": "object_type", "type": "string"},
            "what_action": {"cf": "data", "col": "what_action", "type": "string"},
            "when": {"cf": "data", "col": "when", "type": "bigint"},
            "where": {"cf": "data", "col": "where", "type": "string"},
            "who": {"cf": "data", "col": "who", "type": "string"},
            "workstation": {"cf": "data", "col": "workstation", "type": "string"}
        }
    }'''

    query = changes \
        .writeStream \
        .outputMode("append") \
        .format('HBase.HBaseSinkProvider')\
        .option('hbasecat', change_catalog) \
        .option("checkpointLocation", '/tmp/checkpoint') \
        .start()

#        .format('org.apache.spark.sql.execution.datasources.hbase')\
#    query = changes \
#        .writeStream \
#        .format('console') \
#        .start()

    query.awaitTermination()
</code>```

EXCEPTION

org.apache.spark.sql.AnalysisException: Queries with streaming sources must be executed with writeStream.start();;
LogicalRDD [key#146, value#147, topic#148, partition#149, offset#150L, timestamp#151, timestampType#152], true at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$.org$apache$spark$sql$catalyst$analysis$UnsupportedOperationChecker$$throwError(UnsupportedOperationChecker.scala:374)
at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$$anonfun$checkForBatch$1.apply(UnsupportedOperationChecker.scala:37)
at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$$anonfun$checkForBatch$1.apply(UnsupportedOperationChecker.scala:35)
at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:127)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at scala.collection.immutable.List.foreach(List.scala:381)
at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:126)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at scala.collection.immutable.List.foreach(List.scala:381)
at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:126)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at scala.collection.immutable.List.foreach(List.scala:381)

ContentLicense: CC BY-SA 4.0

Body:
As described in Spark Structured Streaming with Hbase integration, I'm interesting in writing data to HBase in structured streaming framework. I've cloned SHC code from github, extend it by sync provider and trying to write records to HBase. Buy, I've received error: """Queries with streaming sources must be executed with writeStream.start(). My python code is below:

JARS

Spark version: 2.4.0, scala.version: 2.11.8, com.hortonworks.shc-core: 1.1.1-2.1-s_2.11 spark-sql-kafka-0-10_2.11

    spark = SparkSession \
        .builder \
        .appName("SparkConsumer") \
        .getOrCreate()

    print 'read Avro schema from file: {}...'.format(schema_name)
    schema = avro.schema.parse(open(schema_name, 'rb').read())
    reader = avro.io.DatumReader(schema)
    print 'the schema is read'

    rows = spark \
        .readStream \
        .format('kafka') \
        .option('kafka.bootstrap.servers', brokers) \
        .option('subscribe', topic) \
        .option('group.id', group_id) \
        .option('maxOffsetsPerTrigger', 1000) \
        .option("startingOffsets", "earliest") \
        .load()
    rows.printSchema()

    schema = StructType([ \
            StructField('consumer_id', StringType(), False), \
            StructField('audit_system_id', StringType(), False), \
            StructField('object_path', StringType(), True), \
            StructField('object_type', StringType(), False), \
            StructField('what_action', StringType(), False), \
            StructField('when', LongType(), False), \
            StructField('where', StringType(), False), \
            StructField('who', StringType(), True), \
            StructField('workstation', StringType(), True) \
        ])

    def decode_avro(msg):
        bytes_reader = io.BytesIO(bytes(msg))
        decoder = avro.io.BinaryDecoder(bytes_reader)
        data = reader.read(decoder)
        return (\
                data['consumer_id'],\
                data['audit_system_id'],\
                data['object_path'],\
                data['object_type'],\
                data['what_action'],\
                data['when'],\
                data['where'],\
                data['who'],\
                data['workstation']\
               )

    udf_decode_avro = udf(decode_avro, schema)

    values = rows.select('value')
    values.printSchema()

    changes = values.withColumn('change', udf_decode_avro(col('value'))).select('change.*')
    changes.printSchema()

    change_catalog = '''
    {
        "table":
        {
            "namespace": "uba_input",
            "name": "changes"
        },
        "rowkey": "consumer_id",
        "columns":
        {
            "consumer_id": {"cf": "rowkey", "col": "consumer_id", "type": "string"},
            "audit_system_id": {"cf": "data", "col": "audit_system_id", "type": "string"},
            "object_path": {"cf": "data", "col": "object_path", "type": "string"},
            "object_type": {"cf": "data", "col": "object_type", "type": "string"},
            "what_action": {"cf": "data", "col": "what_action", "type": "string"},
            "when": {"cf": "data", "col": "when", "type": "bigint"},
            "where": {"cf": "data", "col": "where", "type": "string"},
            "who": {"cf": "data", "col": "who", "type": "string"},
            "workstation": {"cf": "data", "col": "workstation", "type": "string"}
        }
    }'''

    query = changes \
        .writeStream \
        .outputMode("append") \
        .format('HBase.HBaseSinkProvider')\
        .option('hbasecat', change_catalog) \
        .option("checkpointLocation", '/tmp/checkpoint') \
        .start()

#        .format('org.apache.spark.sql.execution.datasources.hbase')\
#    query = changes \
#        .writeStream \
#        .format('console') \
#        .start()

    query.awaitTermination()

EXCEPTION

org.apache.spark.sql.AnalysisException: Queries with streaming sources must be executed with writeStream.start();;
LogicalRDD [key#146, value#147, topic#148, partition#149, offset#150L, timestamp#151, timestampType#152], true at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$.org$apache$spark$sql$catalyst$analysis$UnsupportedOperationChecker$$throwError(UnsupportedOperationChecker.scala:374)
at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$$anonfun$checkForBatch$1.apply(UnsupportedOperationChecker.scala:37)
at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$$anonfun$checkForBatch$1.apply(UnsupportedOperationChecker.scala:35)
at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:127)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at scala.collection.immutable.List.foreach(List.scala:381)
at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:126)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at scala.collection.immutable.List.foreach(List.scala:381)
at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:126)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$foreachUp$1.apply(TreeNode.scala:126)
at scala.collection.immutable.List.foreach(List.scala:381)


问:
Conditional typescript explaination & error
I was wondering if someone could walk me through how this typescript works and explain the syntax of each type and how the types are assigned. I'm getting an error on line 46:

```<code>(onChange(options[e.target.selectedIndex])
</code>```

Error:

Argument of type 'Value | Value | undefined' is not assignable to
parameter of type 'Value'.   'Value' could be instantiated with an
arbitrary type which could be unrelated to 'Value | Value |
undefined'.ts(2345)

Component:

```<code>type Allowed = string | number;

type BaseProps<Value> = {
  value: Value;
  onChange: (newValue: Value) => void;
  options: readonly Value[];
  mapOptionToLabel?: (option: Value) => Allowed;
  mapOptionToValue?: (option: Value) => Allowed;
};

// mappers required only in certain cirumstances
// we could get fancier here and also not require if `Value` has `value`/`label` properties
type Props<Value> = Value extends Allowed
  ? BaseProps<Value>
  : Required<BaseProps<Value>>;

// type guard function checks value and refines type
const isAllowed = (v: any): v is Allowed =>
  typeof v === "string" || typeof v === "number";

function CustomSelect<Value>({
  value,
  onChange,
  options,
  mapOptionToLabel,
  mapOptionToValue
}: Props<Value>) {
  const toLabel = (option: Value): Allowed => {
    if (mapOptionToLabel) {
      return mapOptionToLabel(option);
    }
    // if our props are provided correctly, this should never be false
    return isAllowed(option) ? option : String(option);
  };

  const toValue = (option: Value): Allowed => {
    if (mapOptionToValue) {
      return mapOptionToValue(option);
    }
    return isAllowed(option) ? option : String(option);
  };

  const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    onChange(options[e.target.selectedIndex]);
  };

  return (
    <select value={toValue(value)} onChange={handleChange}>
      {options.map((value) => (
        <option value={toValue(value)} key={toValue(value)}>
          {toLabel(value)}
        </option>
      ))}
    </select>
  );
}
</code>```

Usage:

```<code>const SelectUser = () => {
  const users: User[] = [
    {
      id: 1,
      name: "John"
    },
    {
      id: 322,
      name: "Susan"
    },
    {
      id: 57,
      name: "Bill"
    }
  ];

  const [user, setUser] = React.useState(users[0]);

  return (
    <div>
      <div>Value: {JSON.stringify(user)}</div>

      <CustomSelect
        value={user}
        onChange={setUser}
        options={users}
        // has an error if no mapOptionToLabel is provided!
        // I don't know why the type for user isn't automatic
        mapOptionToLabel={(user: User) => user.name}
        mapOptionToValue={(user: User) => user.id}
      />
    </div>
  );
};
</code>```

For reference, this is the answer to someone else's stackoverflow question:

How to type a custom React select component using TypeScript?

Body:
I was wondering if someone could walk me through how this typescript works and explain the syntax of each type and how the types are assigned. I'm getting an error on line 46:

(onChange(options[e.target.selectedIndex])

Error:

Argument of type 'Value | Value | undefined' is not assignable to
parameter of type 'Value'.   'Value' could be instantiated with an
arbitrary type which could be unrelated to 'Value | Value |
undefined'.ts(2345)

Component:

type Allowed = string | number;

type BaseProps<Value> = {
  value: Value;
  onChange: (newValue: Value) => void;
  options: readonly Value[];
  mapOptionToLabel?: (option: Value) => Allowed;
  mapOptionToValue?: (option: Value) => Allowed;
};

// mappers required only in certain cirumstances
// we could get fancier here and also not require if `Value` has `value`/`label` properties
type Props<Value> = Value extends Allowed
  ? BaseProps<Value>
  : Required<BaseProps<Value>>;

// type guard function checks value and refines type
const isAllowed = (v: any): v is Allowed =>
  typeof v === "string" || typeof v === "number";

function CustomSelect<Value>({
  value,
  onChange,
  options,
  mapOptionToLabel,
  mapOptionToValue
}: Props<Value>) {
  const toLabel = (option: Value): Allowed => {
    if (mapOptionToLabel) {
      return mapOptionToLabel(option);
    }
    // if our props are provided correctly, this should never be false
    return isAllowed(option) ? option : String(option);
  };

  const toValue = (option: Value): Allowed => {
    if (mapOptionToValue) {
      return mapOptionToValue(option);
    }
    return isAllowed(option) ? option : String(option);
  };

  const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    onChange(options[e.target.selectedIndex]);
  };

  return (
    <select value={toValue(value)} onChange={handleChange}>
      {options.map((value) => (
        <option value={toValue(value)} key={toValue(value)}>
          {toLabel(value)}
        </option>
      ))}
    </select>
  );
}

Usage:

const SelectUser = () => {
  const users: User[] = [
    {
      id: 1,
      name: "John"
    },
    {
      id: 322,
      name: "Susan"
    },
    {
      id: 57,
      name: "Bill"
    }
  ];

  const [user, setUser] = React.useState(users[0]);

  return (

Value: {JSON.stringify(user)}

      <CustomSelect
        value={user}
        onChange={setUser}
        options={users}
        // has an error if no mapOptionToLabel is provided!
        // I don't know why the type for user isn't automatic
        mapOptionToLabel={(user: User) => user.name}
        mapOptionToValue={(user: User) => user.id}
      />

  );
};

For reference, this is the answer to someone else's stackoverflow question:

How to type a custom React select component using TypeScript?


问:
How to handle websocket traffic in Python Websocket?
I can use websockets in my code and i can easily store it some list. Here is code

```<code>import websockets
import asyncio

clients = {}

async def handle_connection(websocket, path):
    # save websocket connection in clients dictionary
    clients[websocket] = path
    try:
        # messages from client
        async for message in websocket:
            for to_client in clients.keys():
                dest_username = clients[to_client]
                source_username = clients[websocket]
                text_data = message
                if source_username == dest_username:
                    await to_client.send(f"{source_username}: {text_data}")
    except Exception as e:
        print(e)
    finally:
        # remove websocket connection
        clients.pop(websocket)

# websocket server port
PORT = 5678

start_server = websockets.serve(handle_connection, 'localhost', PORT)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
</code>```

My question is this, is it the correct way to store all websockets in a list ? Because i can not find any example for storing websockets.Some adviced tornado.But are there any best(optimal) solution ? Thank you for your answers

Body:
I can use websockets in my code and i can easily store it some list. Here is code

import websockets
import asyncio

clients = {}

async def handle_connection(websocket, path):
    # save websocket connection in clients dictionary
    clients[websocket] = path
    try:
        # messages from client
        async for message in websocket:
            for to_client in clients.keys():
                dest_username = clients[to_client]
                source_username = clients[websocket]
                text_data = message
                if source_username == dest_username:
                    await to_client.send(f"{source_username}: {text_data}")
    except Exception as e:
        print(e)
    finally:
        # remove websocket connection
        clients.pop(websocket)

# websocket server port
PORT = 5678

start_server = websockets.serve(handle_connection, 'localhost', PORT)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

My question is this, is it the correct way to store all websockets in a list ? Because i can not find any example for storing websockets.Some adviced tornado.But are there any best(optimal) solution ? Thank you for your answers


问:
Firebase Realtime Database Subscription Limits
I am looking for max allowed active connections to Firebase Realtime DB in Blaze Plan for below

How many active RtDB listeners (StreamSubscription) from single device

How many active RtDB listeners (StreamSubscription) to single db from all connected devices

In below link I see,

total Simultaneous connections allowed are 200,000

https://firebase.google.com/docs/database/usage/limits

(A simultaneous connection is equivalent to one mobile device, browser tab, or server app connected to the database.)

But I could not find StreamSubscription limit per device, and StreamSubscription limit per  db.


问:
Recursion vs Backtracking, which code is correct
I tried solving https://www.techiedelight.com/?problem=SubsetSum problem using backtracking. My code is shard here. https://techiedelight.com/compiler/?~SubseSum . I believe my code is correct, but when I submit the code, I get: Failed for Input = [7, 8, 1, 2, 3, 5], target = 10

Expected output —> 16 Your output —> 18

The expected output is a recursion code from https://www.techiedelight.com/find-ways-calculate-target-elements-array/, which gives 16 as total ways to get target sum. However for a simpler case: Input: nums = [5, 3, -6, 2], target = 6, both codes give same answer.

So which code is incorrect and why?

My code with input is below. Please see link above for techiedelight code.

```<code>class Solution:

    def countWays(self, nums, target):
        nt = len(nums)
        lpath = []
        result = []
        signs = [1, 0, -1]

        def countback(lpath):
            if len(lpath) == nt and lpath[-1][1] == target:
                result.append(lpath.copy())
            if len(lpath) == nt:
                return
            else:
                for sign in signs:
                    i = len(lpath)
                    if i == 0:
                        rsum = 0
                    else:
                        rsum = lpath[i-1][1]
                    rsum += sign*nums[i]
                    lpath.append([sign, rsum])
                    countback(lpath)
                    lpath.pop(-1)

        countback(lpath)

        sym ={1:"+", -1:"-"}

        for i in result:
            for j in range(len(i)):
                if i[j][0] != 0:
                    print(sym[i[j][0]],nums[j], " ", end='')
            print()

        return len(result)

a = Solution()
nums = [7, 8, 1, 2, 3, 5]
print("nums ", nums)
target = 10
print(a.countWays(nums, target), "ways")

</code>```

Body:
I tried solving https://www.techiedelight.com/?problem=SubsetSum problem using backtracking. My code is shard here. https://techiedelight.com/compiler/?~SubseSum . I believe my code is correct, but when I submit the code, I get: Failed for Input = [7, 8, 1, 2, 3, 5], target = 10

Expected output —> 16 Your output —> 18

The expected output is a recursion code from https://www.techiedelight.com/find-ways-calculate-target-elements-array/, which gives 16 as total ways to get target sum. However for a simpler case: Input: nums = [5, 3, -6, 2], target = 6, both codes give same answer.

So which code is incorrect and why?

My code with input is below. Please see link above for techiedelight code.

class Solution:

    def countWays(self, nums, target):
        nt = len(nums)
        lpath = []
        result = []
        signs = [1, 0, -1]

        def countback(lpath):
            if len(lpath) == nt and lpath[-1][1] == target:
                result.append(lpath.copy())
            if len(lpath) == nt:
                return
            else:
                for sign in signs:
                    i = len(lpath)
                    if i == 0:
                        rsum = 0
                    else:
                        rsum = lpath[i-1][1]
                    rsum += sign*nums[i]
                    lpath.append([sign, rsum])
                    countback(lpath)
                    lpath.pop(-1)

        countback(lpath)

        sym ={1:"+", -1:"-"}

        for i in result:
            for j in range(len(i)):
                if i[j][0] != 0:
                    print(sym[i[j][0]],nums[j], " ", end='')
            print()

        return len(result)

a = Solution()
nums = [7, 8, 1, 2, 3, 5]
print("nums ", nums)
target = 10
print(a.countWays(nums, target), "ways")


问:
How to add consumer and producer credentials in a docker file using jwt authentication
ERROR SASL authentication failed using login context 'Client' with exception: {}

The docker is also showing that the token has been verified, but how is autnetication happenng here?

`The below given is my yaml file.

```<code>

version: '3.1'

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.3.1
    ports:
      - '2181:2181'
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka:
    image: confluentinc/cp-server:5.4.0
    depends_on:
      - zookeeper
    ports:
      - '9092:9092'
      - '9093:9093'
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      ZOOKEEPER_SASL_ENABLED: 'false'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT, SASL_PLAINTEXT:SASL_PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: SASL_PLAINTEXT://localhost:9092, PLAINTEXT://localhost:9093
      KAFKA_SECURITY_INTER_BROKER_PROTOCOL : SASL_PLAINTEXT
      KAFKA_SASL_MECHANISM_INTER_BROKER_PROTOCOL: OAUTHBEARER
      KAFKA_SASL_ENABLED_MECHANISMS: OAUTHBEARER
      KAFKA_OPTS: '-Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf'
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      # KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_CONFLUENT_LICENSE_TOPIC_REPLICATION_FACTOR: 1
      KAFKAJS_NO_PARTITIONER_WARNING: 1
      KAFKA_SOCKET_REQUEST_MAX_BYTES: 500000000
      # OAuth Configuration
      OAUTH_WITH_SSL: "false"
      # OAUTH_LOGIN_SERVER : "hydra:4444"
      # OAUTH_LOGIN_ENDPOINT : "/oauth2/token"
      # OAUTH_LOGIN_GRANT_TYPE: "client_credentials"
      # OAUTH_LOGIN_SCOPE: "broker.kafka"
      # OAUTH_AUTHORIZATION : "Basic YnJva2VyLWthZmthOmJyb2tlci1rYWZrYQ=="
      # OAUTH_INTROSPECT_SERVER : "hydra:4445"
      # OAUTH_INTROSPECT_ENDPOINT : "/oauth2/introspect"
      # OAUTH_INTROSPECT_AUTHORIZATION : "Basic YnJva2VyLWthZmthOmJyb2tlci1rYWZrYQ=="
      # CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS: kafka:29092
      # CONFLUENT_METRICS_REPORTER_ZOOKEEPER_CONNECT: zookeeper:2181
      # CONFLUENT_METRICS_REPORTER_TOPIC_REPLICAS: 1
      # CONFLUENT_METRICS_ENABLE: 'true'
      # CONFLUENT_SUPPORT_CUSTOMER_ID: 'anonymous'
    volumes:
      - ./testHelpers/kafka:/etc/kafka
</code>```

`

Body:
ERROR SASL authentication failed using login context 'Client' with exception: {}

The docker is also showing that the token has been verified, but how is autnetication happenng here?

`The below given is my yaml file.

version: '3.1'

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.3.1
    ports:
      - '2181:2181'
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka:
    image: confluentinc/cp-server:5.4.0
    depends_on:
      - zookeeper
    ports:
      - '9092:9092'
      - '9093:9093'
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      ZOOKEEPER_SASL_ENABLED: 'false'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT, SASL_PLAINTEXT:SASL_PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: SASL_PLAINTEXT://localhost:9092, PLAINTEXT://localhost:9093
      KAFKA_SECURITY_INTER_BROKER_PROTOCOL : SASL_PLAINTEXT
      KAFKA_SASL_MECHANISM_INTER_BROKER_PROTOCOL: OAUTHBEARER
      KAFKA_SASL_ENABLED_MECHANISMS: OAUTHBEARER
      KAFKA_OPTS: '-Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf'
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      # KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_CONFLUENT_LICENSE_TOPIC_REPLICATION_FACTOR: 1
      KAFKAJS_NO_PARTITIONER_WARNING: 1
      KAFKA_SOCKET_REQUEST_MAX_BYTES: 500000000
      # OAuth Configuration
      OAUTH_WITH_SSL: "false"
      # OAUTH_LOGIN_SERVER : "hydra:4444"
      # OAUTH_LOGIN_ENDPOINT : "/oauth2/token"
      # OAUTH_LOGIN_GRANT_TYPE: "client_credentials"
      # OAUTH_LOGIN_SCOPE: "broker.kafka"
      # OAUTH_AUTHORIZATION : "Basic YnJva2VyLWthZmthOmJyb2tlci1rYWZrYQ=="
      # OAUTH_INTROSPECT_SERVER : "hydra:4445"
      # OAUTH_INTROSPECT_ENDPOINT : "/oauth2/introspect"
      # OAUTH_INTROSPECT_AUTHORIZATION : "Basic YnJva2VyLWthZmthOmJyb2tlci1rYWZrYQ=="
      # CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS: kafka:29092
      # CONFLUENT_METRICS_REPORTER_ZOOKEEPER_CONNECT: zookeeper:2181
      # CONFLUENT_METRICS_REPORTER_TOPIC_REPLICAS: 1
      # CONFLUENT_METRICS_ENABLE: 'true'
      # CONFLUENT_SUPPORT_CUSTOMER_ID: 'anonymous'
    volumes:
      - ./testHelpers/kafka:/etc/kafka

`


问:
How to know whice sim receive incoming sms using telephony in flutter
I am developing sms reading app using the flutter telephony package. Everything is working fine, but there is a problem when the mobile has two sim cards. I am unable to track which sim card is receiving SMS. Can anyone help me to achieve my goal?
Here is code

```<code>
  onMessage(SmsMessage message) async {
    print('sid: ${message.subscriptionId}');
    ToasterShow('sub= ${message.subject}');
    String? operatorName = await telephony.simOperatorName;
  }
</code>```

here subscriptionId return null.

Hope anyone help me.
Thanks

Body:
I am developing sms reading app using the flutter telephony package. Everything is working fine, but there is a problem when the mobile has two sim cards. I am unable to track which sim card is receiving SMS. Can anyone help me to achieve my goal?
Here is code

  onMessage(SmsMessage message) async {
    print('sid: ${message.subscriptionId}');
    ToasterShow('sub= ${message.subject}');
    String? operatorName = await telephony.simOperatorName;
  }

here subscriptionId return null.

Hope anyone help me.
Thanks


问:
Informix server is not able to start time to time
I am trying to find the root cause of the issue with the Informix installation where the server is restarted every night (some legacy setup). Most of the restarts are OK, but from time to time the database does not start.
It ends just with the following lines:

```<code>...
Thu Dec 15 00:36:17 2022

00:36:17  Successfully added a bufferpool of page size 2K.

00:36:17  Event alarms enabled.  ALARMPROG = '/opt/IBM/informix/12.10/etc/alarmprogram.sh'
00:36:17  Booting Language <c> from module <>
00:36:17  Loading Module <CNULL>
00:36:17  Booting Language <builtin> from module <>
00:36:17  Loading Module <BUILTINNULL>
00:36:22  Entries in the surrogates file /etc/informix/allowed.surrogates are loaded into surrogate cache.
00:36:22  Trusted host cache successfully built:/etc/hosts.equiv.
00:36:22  DR: DRAUTO is 0 (Off)
00:36:22  DR: ENCRYPT_HDR is 0 (HDR encryption Disabled)
00:36:22  Event notification facility epoll enabled.
00:36:23  IBM Informix Dynamic Server Version 12.10.FC2WE Software Serial Number AAA#B000000
00:36:23  (5) connection rejected - no calls allowed for sqlexec
00:36:23  (6) connection rejected - no calls allowed for sqlexec
</code>```

When I then SSH to the server, I am able to start it normally. Do you please have any idea what can cause this issue?

Thank you.

On the link bellow, there is a log from a successful start and from a failed on.

https://pastebin.com/hQPBccX6

Body:
I am trying to find the root cause of the issue with the Informix installation where the server is restarted every night (some legacy setup). Most of the restarts are OK, but from time to time the database does not start.
It ends just with the following lines:

...
Thu Dec 15 00:36:17 2022

00:36:17  Successfully added a bufferpool of page size 2K.

00:36:17  Event alarms enabled.  ALARMPROG = '/opt/IBM/informix/12.10/etc/alarmprogram.sh'
00:36:17  Booting Language <c> from module <>
00:36:17  Loading Module <CNULL>
00:36:17  Booting Language <builtin> from module <>
00:36:17  Loading Module <BUILTINNULL>
00:36:22  Entries in the surrogates file /etc/informix/allowed.surrogates are loaded into surrogate cache.
00:36:22  Trusted host cache successfully built:/etc/hosts.equiv.
00:36:22  DR: DRAUTO is 0 (Off)
00:36:22  DR: ENCRYPT_HDR is 0 (HDR encryption Disabled)
00:36:22  Event notification facility epoll enabled.
00:36:23  IBM Informix Dynamic Server Version 12.10.FC2WE Software Serial Number AAA#B000000
00:36:23  (5) connection rejected - no calls allowed for sqlexec
00:36:23  (6) connection rejected - no calls allowed for sqlexec

When I then SSH to the server, I am able to start it normally. Do you please have any idea what can cause this issue?

Thank you.

On the link bellow, there is a log from a successful start and from a failed on.

https://pastebin.com/hQPBccX6


问:
getStaticProps showing wrong/previous data in Reactjs
I am working on Rectjs,I am using nextjs, I created "[slug.js]" for dynamic routes,But its showing previous data instead of current data(fetching from database via axios),I checked in console.log,and in console showing old data not current,where i am wrong ?Here is my current code</p>
```<code>const Post = function ({post}) {
  useEffect(() => {
    // showing old record/title instead of current
    console.log(`Found Post title : ${post.title}`);
  }, []);
};

export const getStaticProps = async ({ params }) => {
  const { data } = await axios.get(
    `https://diggdevelopment.com/blackstallion_new/api/getblogbyuserid/${params.slug}`
  );
  const post = data;

  console.log('dat is' + post);

  return {
    props: {
      post,
    },
  };
};

export const getStaticPaths = async () => {
  const { data } = await axios.get(
    'http://diggdevelopment.com/blackstallion_new/api/blogscopy'
  );
  const posts = data.slice(0, 10);
  const paths = posts.map((post) => ({ params: { slug: post.id.toString() } }));
  return {
    paths,
    fallback: true,
  };
};

</code>```

Body:
I am working on Rectjs,I am using nextjs, I created "[slug.js]" for dynamic routes,But its showing previous data instead of current data(fetching from database via axios),I checked in console.log,and in console showing old data not current,where i am wrong ?Here is my current code

const Post = function ({post}) {
  useEffect(() => {
    // showing old record/title instead of current
    console.log(`Found Post title : ${post.title}`);
  }, []);
};

export const getStaticProps = async ({ params }) => {
  const { data } = await axios.get(
    `https://diggdevelopment.com/blackstallion_new/api/getblogbyuserid/${params.slug}`
  );
  const post = data;

  console.log('dat is' + post);

  return {
    props: {
      post,
    },
  };
};

export const getStaticPaths = async () => {
  const { data } = await axios.get(
    'http://diggdevelopment.com/blackstallion_new/api/blogscopy'
  );
  const posts = data.slice(0, 10);
  const paths = posts.map((post) => ({ params: { slug: post.id.toString() } }));
  return {
    paths,
    fallback: true,
  };
};


问:
load registered model with mlflow
I have registered a model to mlflow server, where artifact stored in aws bucket.

Now I want to load the model with mlflow API

```<code>model = mlflow.tensorflow.log_model("models:/sample-ann-1/1", artifact_path="")
</code>```

However, I'm not sure where is the artifact stored, or what is the artifact path.

I know the uri of my tracking server. The artifact is stored in AWS s3 host and I have the s3 uri. How can I find the path of the artifact of registered model?

Title: load registered model with mlflow

Body:
I have registered a model to mlflow server, where artifact stored in aws bucket.

Now I want to load the model with mlflow API

model = mlflow.tensorflow.log_model("models:/sample-ann-1/1", artifact_path="")

However, I'm not sure where is the artifact stored, or what is the artifact path.

I know the uri of my tracking server. The artifact is stored in AWS s3 host and I have the s3 uri. How can I find the path of the artifact of registered model?


问:
deecrypt or decoding binary strings in the websocket requests in burpsuite
i was doing pentetsing on a websocket, the server uses blazer framework, and the websocket request data contains unusual characters like this in burpsuite

```<code>Ö•€À·BeginInvokeDotNetFromJS•¢12À²DispatchEventAsyncÚ[{"eventHandlerId":79,"eventName":"click","eventFieldInfo":null},{"detail":1,"screenX":933,"screenY":491,"clientX":933,"clientY":388,"offsetX":280,"offsetY":9,"pageX":933,"pageY":787,"button":0,"buttons":0,"ctrlKey":false,"shiftKey":false,"altKey":false,"metaKey":false,"type":"click"}]
</code>```

i dont know about the characters, but when o rty to interecept and chnage the requests data the server not accepting, i was thinking it was a kind of protection, does any one know about this type of websocket requests.

Body:
i was doing pentetsing on a websocket, the server uses blazer framework, and the websocket request data contains unusual characters like this in burpsuite

Ö•€À·BeginInvokeDotNetFromJS•¢12À²DispatchEventAsyncÚ[{"eventHandlerId":79,"eventName":"click","eventFieldInfo":null},{"detail":1,"screenX":933,"screenY":491,"clientX":933,"clientY":388,"offsetX":280,"offsetY":9,"pageX":933,"pageY":787,"button":0,"buttons":0,"ctrlKey":false,"shiftKey":false,"altKey":false,"metaKey":false,"type":"click"}]

i dont know about the characters, but when o rty to interecept and chnage the requests data the server not accepting, i was thinking it was a kind of protection, does any one know about this type of websocket requests.


问:
Kindy help me solve the problem with window.addEventListener
Hello everyone am trying to do a tab menu navigation.I want when I click on the left menu item, it becomes active and the right menu becomes inactive.I have tried using window onload function, the problem it was overriding the second menu function.Somebody suggested I use addEventListener.I have tried to figure out but am stack in the implementationpart

Result using onload

Result using addEventListener

UI Source Code

```<code><div class="leftpane">
  <nav style="margin-top: 30px;" id="menu">
    <a class="tablinks " onclick="openMenu('why')" id="whyBtn">
      <h2 class="cooler">why<span class="arrow"></span></h2>
    </a>
    <a class="tablinks" onclick="openMenu('process')" id="processBtn">
      <h2 class="cooler">process<span class="arrow"></span></h2>
    </a>

  </nav>
</div>
<div class="middlepane">
  <div class="content" id="why"></div>
  <div class="content" id="process"></div>
  <div class="content" id="scarves"></div>
  <div class="content" id="stockists"></div>
</div>

<div class="rightpane">
  <div style="margin-top: 60%;">
    <nov id="menu">
      <a class="rightlinks" onclick="openLeftMenu('scarves')" id="scarvesBtn">
        <h2 class="drool">scarves<span class="arrow"></span></h2>
      </a>
      <a class="rightlinks" onclick="openLeftMenu('stockists')" id="stockistsBtn">
        <h2 class="drool">stockists<span class="arrow"></span></h2>
      </a>
    </nov>
  </div>
</div>
</code>```

Windows  addEventListener  Logic

```<code>window.addEventListener("DOMContentLoaded", function() {
        const scarves = document.getElementById('scarves');
        const scarvesBtn = document.getElementById('scarvesBtn');
        const stockists = document.getElementById('stockists');
        const stockistsBtn = document.getElementById('stockistsBtn');
        const why = document.getElementById('why');
        const rightlinks = document.querySelector('.rightlinks');
        const tablinks = document.querySelector('.tablinks')

        const openLeftMenu = menu => {
            scarves.classList.toggle("content", menu === 'stockists')
            scarvesBtn.classList.toggle("active", menu === 'scarves')
            stockists.classList.toggle("content", menu === 'scarves')
                .classList.toggle("active", menu === 'stockists')
        }

        // init
        scarves.classList.remove("active");
        why.classList.remove("active");
        rightlinks.classList.add("active");
        tablinks.classList.add("active");
    });
</code>```

Windows  onload one that is displaying but overwrites each other Logic.See image one
Link :https://leskoy.bonusgigs.com/

```<code>window.onload = function() {
        document.getElementById('scarves').className = '';
        document.getElementsByClassName('rightlinks')[0].className = 'active'
    };
    function openLeftMenu( menu) {
        if (menu === 'scarves') {
            document.getElementById('scarves').className = '';
            document.getElementById('stockists').className = 'content';

            document.getElementById('scarvesBtn').className = 'active';
            document.getElementById('stockistsBtn').className = '';

        }

        if (menu === 'stockists') {
            document.getElementById('stockists').className = '';
            document.getElementById('scarves').className = 'content';

            document.getElementById('stockistsBtn').className = 'active';
            document.getElementById('scarvesBtn').className = '';

        }

    }

    window.onload = function() {
        document.getElementById('why').className = '';
        document.getElementsByClassName('tablinks')[0].className = 'active'
    };

    function openMenu( menu) {
        if (menu === 'why') {
            document.getElementById('why').className = '';
            document.getElementById('process').className = 'content';
            document.getElementById('connect').className = 'content';
            document.getElementById('faq').className = 'content';

            document.getElementById('whyBtn').className = 'active';
            document.getElementById('processBtn').className = '';
            document.getElementById('connectBtn').className = '';
            document.getElementById('faqBtn').className = '';

        }

        if (menu === 'process') {
            document.getElementById('process').className = '';
            document.getElementById('why').className = 'content';
            document.getElementById('connect').className = 'content';
            document.getElementById('faq').className = 'content';

            document.getElementById('processBtn').className = 'active';
            document.getElementById('whyBtn').className = '';
            document.getElementById('connectBtn').className = '';
            document.getElementById('faqBtn').className = '';

        }

        if (menu === 'connect') {
            document.getElementById('connect').className = '';
            document.getElementById('process').className = 'content';
            document.getElementById('why').className = 'content';
            document.getElementById('faq').className = 'content';

            document.getElementById('connectBtn').className = 'active';
            document.getElementById('whyBtn').className = '';
            document.getElementById('processBtn').className = '';
            document.getElementById('faqBtn').className = '';

        }

        if (menu === 'faq') {
            document.getElementById('faq').className = '';
            document.getElementById('process').className = 'content';
            document.getElementById('why').className = 'content';
            document.getElementById('connect').className = 'content';

            document.getElementById('faqBtn').className = 'active';
            document.getElementById('whyBtn').className = '';
            document.getElementById('processBtn').className = '';
            document.getElementById('connectBtn').className = '';

        }

    }
</code>```

**Final Solution **

```<code><script type="text/javascript">

    window.addEventListener("load", function() {
        var li_elements = document.querySelectorAll(".leftpane nav a");
        var item_elements = document.querySelectorAll(".content");
        var a_elements = document.querySelectorAll(".rightpane nov a");

        if (li_elements){
            for (var i = 0; i < li_elements.length; i++) {
                li_elements[i].addEventListener("click", function() {
                    li_elements.forEach(function(li) {
                        li.classList.remove("active");
                    });
                    this.classList.add("active");
                    var li_value = this.getAttribute("data-li");
                    item_elements.forEach(function(item) {
                        item.style.display = "none";
                    });
                    if (li_value == "why") {
                        document.querySelector("." + li_value).style.display = "block";
                    } else if (li_value == "process") {
                        document.querySelector("." + li_value).style.display = "block";
                    } else if (li_value == "connect") {
                        document.querySelector("." + li_value).style.display = "block";
                    } else if (li_value == "faq") {
                        document.querySelector("." + li_value).style.display = "block";
                    } else {
                        console.log("");
                    }
                });
            }

        }

        if (a_elements){

            for (var i = 0; i < a_elements.length; i++) {
                a_elements[i].addEventListener("click", function() {
                    a_elements.forEach(function(li) {
                        li.classList.remove("active");
                    });
                    this.classList.add("active");
                    var li_value = this.getAttribute("data-li");
                    item_elements.forEach(function(item) {
                        item.style.display = "none";
                    });
                    if (li_value == "scarves") {
                        document.querySelector("." + li_value).style.display = "block";
                    } else if (li_value == "stockists") {
                        document.querySelector("." + li_value).style.display = "block";
                    }  else {
                        console.log("");
                    }
                });
            }

        }

    }, false);

</script>
</code>```

Body:
Hello everyone am trying to do a tab menu navigation.I want when I click on the left menu item, it becomes active and the right menu becomes inactive.I have tried using window onload function, the problem it was overriding the second menu function.Somebody suggested I use addEventListener.I have tried to figure out but am stack in the implementationpart

Result using onload

Result using addEventListener

UI Source Code

why

process

    <nov id="menu">

scarves

stockists

    </nov>

Windows  addEventListener  Logic

window.addEventListener("DOMContentLoaded", function() {
        const scarves = document.getElementById('scarves');
        const scarvesBtn = document.getElementById('scarvesBtn');
        const stockists = document.getElementById('stockists');
        const stockistsBtn = document.getElementById('stockistsBtn');
        const why = document.getElementById('why');
        const rightlinks = document.querySelector('.rightlinks');
        const tablinks = document.querySelector('.tablinks')

        const openLeftMenu = menu => {
            scarves.classList.toggle("content", menu === 'stockists')
            scarvesBtn.classList.toggle("active", menu === 'scarves')
            stockists.classList.toggle("content", menu === 'scarves')
                .classList.toggle("active", menu === 'stockists')
        }

        // init
        scarves.classList.remove("active");
        why.classList.remove("active");
        rightlinks.classList.add("active");
        tablinks.classList.add("active");
    });

Windows  onload one that is displaying but overwrites each other Logic.See image one
Link :https://leskoy.bonusgigs.com/

window.onload = function() {
        document.getElementById('scarves').className = '';
        document.getElementsByClassName('rightlinks')[0].className = 'active'
    };
    function openLeftMenu( menu) {
        if (menu === 'scarves') {
            document.getElementById('scarves').className = '';
            document.getElementById('stockists').className = 'content';

            document.getElementById('scarvesBtn').className = 'active';
            document.getElementById('stockistsBtn').className = '';

        }

        if (menu === 'stockists') {
            document.getElementById('stockists').className = '';
            document.getElementById('scarves').className = 'content';

            document.getElementById('stockistsBtn').className = 'active';
            document.getElementById('scarvesBtn').className = '';

        }

    }

    window.onload = function() {
        document.getElementById('why').className = '';
        document.getElementsByClassName('tablinks')[0].className = 'active'
    };

    function openMenu( menu) {
        if (menu === 'why') {
            document.getElementById('why').className = '';
            document.getElementById('process').className = 'content';
            document.getElementById('connect').className = 'content';
            document.getElementById('faq').className = 'content';

            document.getElementById('whyBtn').className = 'active';
            document.getElementById('processBtn').className = '';
            document.getElementById('connectBtn').className = '';
            document.getElementById('faqBtn').className = '';

        }

        if (menu === 'process') {
            document.getElementById('process').className = '';
            document.getElementById('why').className = 'content';
            document.getElementById('connect').className = 'content';
            document.getElementById('faq').className = 'content';

            document.getElementById('processBtn').className = 'active';
            document.getElementById('whyBtn').className = '';
            document.getElementById('connectBtn').className = '';
            document.getElementById('faqBtn').className = '';

        }

        if (menu === 'connect') {
            document.getElementById('connect').className = '';
            document.getElementById('process').className = 'content';
            document.getElementById('why').className = 'content';
            document.getElementById('faq').className = 'content';

            document.getElementById('connectBtn').className = 'active';
            document.getElementById('whyBtn').className = '';
            document.getElementById('processBtn').className = '';
            document.getElementById('faqBtn').className = '';

        }

        if (menu === 'faq') {
            document.getElementById('faq').className = '';
            document.getElementById('process').className = 'content';
            document.getElementById('why').className = 'content';
            document.getElementById('connect').className = 'content';

            document.getElementById('faqBtn').className = 'active';
            document.getElementById('whyBtn').className = '';
            document.getElementById('processBtn').className = '';
            document.getElementById('connectBtn').className = '';

        }

    }

**Final Solution **


问:
I use the emacs to start or connect clojurescript but show error: ClojureScript is not available
I use the emacs to start or connect clojurescript but show error:

```<code>error in process filter: ClojureScript is not available.  See https://docs.cider.mx/cider/basics/clojurescript for details
</code>```
```<code>In terminal I use `npx shadow-cljs watch main` to start clojurescript app. It's to started.  so in emacs I use `cider-connect-cljs` connect
</code>```

M-x cider-connect-cljs
Host: localhost
Port: 3477
Select ClojureScript REPL type: shandow
Select shadow-cljs build: main

```<code>
[terminal starts app](https://i.stack.imgur.com/Ait43.png)
[emacs](https://i.stack.imgur.com/0WUfC.png)

On the other hand. I use `cider-jack-in-cljs` to start app in emacs alone. the error as same as up.
</code>```

shadow-cljs.edn

```<code>;; shadow-cljs configuration
{:deps     {:aliases [:dev]}
 :http     {:port 3448}
 :nrepl    {:port 3447 :host "0.0.0.0"}
 :jvm-opts ["-Xmx700m" "-Xms100m" "-XX:+UseSerialGC" "-XX:-OmitStackTraceInFastThrow"]
 :dev-http {8888 "classpath:public"}

 :builds
 {:main
  {:target        :browser
   :output-dir    "resources/public/js/"
   :asset-path    "/js"
   :devtools      {:browser-inject :main
                   :watch-dir      "resources/public"}
   :build-options {:manifest-name "manifest.json"}

   :modules
   {:main {:entries [app.main]
           :init-fn app.main/init}}}

  }}

</code>```

deps.edn

```<code>{:paths ["src" "vendor" "resources" "test"]
 :deps {org.clojure/clojure {:mvn/version "1.11.1"}
        org.clojure/clojurescript {:mvn/version "1.11.60"}

        lilactown/helix {:mvn/version "0.1.9"}}

 :aliases {:dev
           {:extra-paths ["test" "dev"]
            :extra-deps
            {thheller/shadow-cljs {:mvn/version "2.20.2"}
             org.clojure/tools.namespace {:mvn/version "RELEASE"}
             cider/cider-nrepl {:mvn/version "0.29.0"}}}}}

</code>```

Body:
I use the emacs to start or connect clojurescript but show error:

error in process filter: ClojureScript is not available.  See https://docs.cider.mx/cider/basics/clojurescript for details

In terminal I use `npx shadow-cljs watch main` to start clojurescript app. It's to started.  so in emacs I use `cider-connect-cljs` connect

M-x cider-connect-cljs
Host: localhost
Port: 3477
Select ClojureScript REPL type: shandow
Select shadow-cljs build: main

[terminal starts app](https://i.stack.imgur.com/Ait43.png)
[emacs](https://i.stack.imgur.com/0WUfC.png)

On the other hand. I use `cider-jack-in-cljs` to start app in emacs alone. the error as same as up.

shadow-cljs.edn

;; shadow-cljs configuration
{:deps     {:aliases [:dev]}
 :http     {:port 3448}
 :nrepl    {:port 3447 :host "0.0.0.0"}
 :jvm-opts ["-Xmx700m" "-Xms100m" "-XX:+UseSerialGC" "-XX:-OmitStackTraceInFastThrow"]
 :dev-http {8888 "classpath:public"}

 :builds
 {:main
  {:target        :browser
   :output-dir    "resources/public/js/"
   :asset-path    "/js"
   :devtools      {:browser-inject :main
                   :watch-dir      "resources/public"}
   :build-options {:manifest-name "manifest.json"}

   :modules
   {:main {:entries [app.main]
           :init-fn app.main/init}}}

  }}

deps.edn

{:paths ["src" "vendor" "resources" "test"]
 :deps {org.clojure/clojure {:mvn/version "1.11.1"}
        org.clojure/clojurescript {:mvn/version "1.11.60"}

        lilactown/helix {:mvn/version "0.1.9"}}

 :aliases {:dev
           {:extra-paths ["test" "dev"]
            :extra-deps
            {thheller/shadow-cljs {:mvn/version "2.20.2"}
             org.clojure/tools.namespace {:mvn/version "RELEASE"}
             cider/cider-nrepl {:mvn/version "0.29.0"}}}}}


问:
Same War, Same Tomcat, Error on only one machine
I think I have some dependency conflict. This comes up when I deploy my WAR file via the Tomcat management page. I'm using the "Deploy directory or WAR file located on server" option. I specify a context of /eda-poc-java-war and the fully qualified war file on the server. I deploy the same war file, the same way on the same Tomcat version (8.5.84) on both my local development machine, and a remote EC2 instance.

The EC2 instance fails and I get the following exception in the stack trace. What should I look for?

I don't know what the difference is or what I should look for.

SLF4J: Actual binding is of type [org.slf4j.impl.Reload4jLoggerFactory]
16-Dec-2022 05:57:13.262 SEVERE [http-nio-9080-exec-2] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/eda-poc-java-war]]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1016)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:543)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1682)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:291)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1583)
at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:994)
at org.apache.catalina.manager.HTMLManagerServlet.deployInternal(HTMLManagerServlet.java:317)
at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:207)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:682)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:765)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:203)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:126)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:109)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:662)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:885)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1688)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:750)
Caused by: java.lang.IllegalArgumentException: LoggerFactory is not a Logback LoggerContext but Logback is on the classpath. Either remove Logback or the competing implementation (class org.slf4j.impl.Reload4jLoggerFactory loaded from file:/home/ubuntu/apache-tomcat-8.5.84-solace/webapps/eda-poc-java-war/WEB-INF/lib/slf4j-reload4j-1.7.36.jar). If you are using WebLogic you will need to add 'org.slf4j' to prefer-application-packages in WEB-INF/weblogic.xml: org.slf4j.impl.Reload4jLoggerFactory
at org.springframework.util.Assert.instanceCheckFailed(Assert.java:702)
at org.springframework.util.Assert.isInstanceOf(Assert.java:621)
at org.springframework.boot.logging.logback.LogbackLoggingSystem.getLoggerContext(LogbackLoggingSystem.java:294)
at org.springframework.boot.logging.logback.LogbackLoggingSystem.beforeInitialize(LogbackLoggingSystem.java:118)
at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationStartingEvent(LoggingApplicationListener.java:232)
at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:213)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131)
at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:79)
at org.springframework.boot.SpringApplicationRunListeners.lambda$starting$0(SpringApplicationRunListeners.java:56)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:120)
at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:56)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:298)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:175)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:155)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:97)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:174)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5218)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
... 50 more
16-Dec-2022 05:57:13.266 SEVERE [http-nio-9080-exec-2] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive [/home/ubuntu/apache-tomcat-8.5.84-solace/webapps/eda-poc-java-war.war]
java.lang.IllegalStateException: Error starting child
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:757)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1016)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:543)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1682)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:291)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1583)
at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:994)
at org.apache.catalina.manager.HTMLManagerServlet.deployInternal(HTMLManagerServlet.java:317)
at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:207)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:682)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:765)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:203)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:126)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:109)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:662)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:885)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1688)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:750)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/eda-poc-java-war]]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753)
... 49 more
Caused by: java.lang.IllegalArgumentException: LoggerFactory is not a Logback LoggerContext but Logback is on the classpath. Either remove Logback or the competing implementation (class org.slf4j.impl.Reload4jLoggerFactory loaded from file:/home/ubuntu/apache-tomcat-8.5.84-solace/webapps/eda-poc-java-war/WEB-INF/lib/slf4j-reload4j-1.7.36.jar). If you are using WebLogic you will need to add 'org.slf4j' to prefer-application-packages in WEB-INF/weblogic.xml: org.slf4j.impl.Reload4jLoggerFactory
at org.springframework.util.Assert.instanceCheckFailed(Assert.java:702)
at org.springframework.util.Assert.isInstanceOf(Assert.java:621)
at org.springframework.boot.logging.logback.LogbackLoggingSystem.getLoggerContext(LogbackLoggingSystem.java:294)
at org.springframework.boot.logging.logback.LogbackLoggingSystem.beforeInitialize(LogbackLoggingSystem.java:118)
at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationStartingEvent(LoggingApplicationListener.java:232)
at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:213)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131)
at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:79)
at org.springframework.boot.SpringApplicationRunListeners.lambda$starting$0(SpringApplicationRunListeners.java:56)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:120)
at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:56)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:298)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:175)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:155)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:97)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:174)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5218)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
... 50 more

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


问:
how to render ejs template (stored in blob/database) in node js, so that it can act as a CDN?
I have a scenario, where I need to render a dynamic html content whenever API is requested.
Now, one solution is to keep all the template related files and images in the API job itself. whenever the API is requested, we can simply render it:

```<code>app.get('/', (req: any, res: any) => {
res.render('index, { reportData: data, vehicleImg:vehicleImg })})
</code>```

But, I don't want to do that. Instead, I want to store all the template related files, images, assets in a blob and fetch & render them on request. The benefit of doing this is: for every customer, I can have this template stored at one place.

Does anyone know, how can I do this?

Body:
I have a scenario, where I need to render a dynamic html content whenever API is requested.
Now, one solution is to keep all the template related files and images in the API job itself. whenever the API is requested, we can simply render it:

app.get('/', (req: any, res: any) => {
res.render('index, { reportData: data, vehicleImg:vehicleImg })})

But, I don't want to do that. Instead, I want to store all the template related files, images, assets in a blob and fetch & render them on request. The benefit of doing this is: for every customer, I can have this template stored at one place.

Does anyone know, how can I do this?


问:
How to handle mutiple calls at OnReceive method in Actor class in AKKA.NET using C#
I have an C#.net core 3.1 console application. I have developed Actor model in my application using Akka.Net
How to handle multiple calls at OnReceive method (below example: Method_A() invoked multiple times simultaneously, this will making issue in my application). Please check at Actor2 class in below example.

Example:

```<code>public class Actor1: UntypedActor
{
  protected override void OnReceive(object message)
{
for(int i = 100;i<=100;i++)
{
actor2.tell(message)
}
}
}

public class Actor2: UntypedActor
{
protected override void OnReceive(object message)
{
method_A(message);
}
}
</code>```

Can you share me some sample code in C-Sharp?

Regards,
Prabs

Body:
I have an C#.net core 3.1 console application. I have developed Actor model in my application using Akka.Net
How to handle multiple calls at OnReceive method (below example: Method_A() invoked multiple times simultaneously, this will making issue in my application). Please check at Actor2 class in below example.

Example:

public class Actor1: UntypedActor
{
  protected override void OnReceive(object message)
{
for(int i = 100;i<=100;i++)
{
actor2.tell(message)
}
}
}

public class Actor2: UntypedActor
{
protected override void OnReceive(object message)
{
method_A(message);
}
}

Can you share me some sample code in C-Sharp?

Regards,
Prabs


Title: Pivoting an numpy array by using pandas

Body:
I have a  numpy array in the shape of (2,400). I would like to use pandas to convert that to (400,2), so as a pivot shape

path='**.npy'
input=np.load(path)
df = pd.DataFrame(np2)
df.head()
        0        1         2         3         4         5         6    ...       393       394       395       396       397       398       399
0 -0.000039 -0.00002 -0.000019 -0.000028 -0.000030 -0.000008 -0.000017  ... -0.000039 -0.000053 -0.000058 -0.000055 -0.000059 -0.000042 -0.000043
1 -0.000028 -0.00002 -0.000024 -0.000025 -0.000031  0.000002 -0.000015  ... -0.000026 -0.000045 -0.000062 -0.000055 -0.000053 -0.000024 -0.000031

Not sure how to do that in pivot function with pandas?


问:
CPU getting choked when below code is executed
```<code>   public bool CheckIfValidSignedPdfExists(string fileServerPath, int memberagreementId)
        {
            var filePaths = Directory.GetFiles(fileServerPath);

            if (filePaths.Length < 2)
            {
                return false;
            }

            var fileInfo = new List<FileInfo>();
            foreach (var path in filePaths)
            {
                if (File.Exists(path))
                    fileInfo.Add(new FileInfo(path));
            }
            if (fileInfo.Count < 2)
                return false;

            else
            {
                fileInfo = fileInfo.OrderByDescending(x => x.LastWriteTimeUtc).Take(2).ToList();
                //Rules: 1. Name 2.size 3. Last write time 4. Extension
                var firstPdf = fileInfo.FirstOrDefault();
                var lastPdf = fileInfo.LastOrDefault();

                var firstFileNameCheck = string.Concat(Convert.ToString(memberagreementId), ".pdf");
                var lastFileNameCheck = lastPdf.Name.StartsWith(Convert.ToString(memberagreementId) + "-")
                    && lastPdf.Name.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase);

                if ((firstPdf.Name.Equals(firstFileNameCheck, StringComparison.OrdinalIgnoreCase)) &&
                    (lastFileNameCheck) && (firstPdf.Length > lastPdf.Length) && (firstPdf.LastWriteTimeUtc >= lastPdf.LastWriteTimeUtc))
                    return true;
                else
                    return false;
            }
        }
</code>```

When this piece of code is running, we can see the cpu spike and the thread always relate to the above code.
HIGH CPU Thread Code
CPU Spike

We are not sure what wrong we are doing in this code which is causing this issue.

Body:
   public bool CheckIfValidSignedPdfExists(string fileServerPath, int memberagreementId)
        {
            var filePaths = Directory.GetFiles(fileServerPath);

            if (filePaths.Length < 2)
            {
                return false;
            }

            var fileInfo = new List<FileInfo>();
            foreach (var path in filePaths)
            {
                if (File.Exists(path))
                    fileInfo.Add(new FileInfo(path));
            }
            if (fileInfo.Count < 2)
                return false;

            else
            {
                fileInfo = fileInfo.OrderByDescending(x => x.LastWriteTimeUtc).Take(2).ToList();
                //Rules: 1. Name 2.size 3. Last write time 4. Extension
                var firstPdf = fileInfo.FirstOrDefault();
                var lastPdf = fileInfo.LastOrDefault();

                var firstFileNameCheck = string.Concat(Convert.ToString(memberagreementId), ".pdf");
                var lastFileNameCheck = lastPdf.Name.StartsWith(Convert.ToString(memberagreementId) + "-")
                    && lastPdf.Name.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase);

                if ((firstPdf.Name.Equals(firstFileNameCheck, StringComparison.OrdinalIgnoreCase)) &&
                    (lastFileNameCheck) && (firstPdf.Length > lastPdf.Length) && (firstPdf.LastWriteTimeUtc >= lastPdf.LastWriteTimeUtc))
                    return true;
                else
                    return false;
            }
        }

When this piece of code is running, we can see the cpu spike and the thread always relate to the above code.
HIGH CPU Thread Code
CPU Spike

We are not sure what wrong we are doing in this code which is causing this issue.


问:
gitlab pipeline rules for include external files
```<code>include:
  - project: 'path/devops/gitlab-pipeline'
    ref: master
    file: '/modules/deploy/base.yml'
    rules:
      - if: '$CANARY_DEPLOY == "false"'
  - project: 'path/devops/gitlab-pipeline'
    ref: master
    file: '/modules/deploy/canary.yml'
    rules:
      - if: '$CANARY_DEPLOY == "true"'
</code>```

is it correct syntax for including modules/deploy/base.yml and modules/deploy/canary.yml  based on above condition . Its working when I commit the changes through code but if I try to submit a pipeline using gitlab UI , its behaviour is not as expetced.

I tried the above syntax for including modules/deploy/base.yml and modules/deploy/canary.yml  based on above condition . Its working when I commit the changes through code but if I try to submit a pipeline using gitlab UI , its behaviour is not as expetced.

Body:
include:
  - project: 'path/devops/gitlab-pipeline'
    ref: master
    file: '/modules/deploy/base.yml'
    rules:
      - if: '$CANARY_DEPLOY == "false"'
  - project: 'path/devops/gitlab-pipeline'
    ref: master
    file: '/modules/deploy/canary.yml'
    rules:
      - if: '$CANARY_DEPLOY == "true"'

is it correct syntax for including modules/deploy/base.yml and modules/deploy/canary.yml  based on above condition . Its working when I commit the changes through code but if I try to submit a pipeline using gitlab UI , its behaviour is not as expetced.

I tried the above syntax for including modules/deploy/base.yml and modules/deploy/canary.yml  based on above condition . Its working when I commit the changes through code but if I try to submit a pipeline using gitlab UI , its behaviour is not as expetced.


问:
Multivariate paired data simulation
How can I make a simulation scenario in R for multivariate paired data? I have a data matrix. Should I do it using var-cov matrix?</p>

Title: Multivariate paired data simulation


问:
How do I Update CloudFront ResponseHeadersPolicyId
I'm using awscli and shell script
I got under error when I excute awscli
How can I fix it?

Unknown parameter in DistributionConfig.DefaultCacheBehavior: "ResponseHeadersPolicyId", must be one of: TargetOriginId, TrustedSigners, ViewerProtocolPolicy, AllowedMethods, SmoothStreaming, Compress, LambdaFunctionAssociations, FieldLevelEncryptionId, RealtimeLogConfigArn, CachePolicyId, OriginRequestPolicyId, ForwardedValues, MinTTL, DefaultTTL, MaxTTL

awscli = ./example_script.sh example_bucket /index

#!/bin/bash CLOUDFRONT_DISTRIBUTION_ID=EXAMPLE_ID NEW_ORIGIN="$1.s3.ap-northeast-2.amazonaws.com" NEW_PATH="$2" NEW_RES_HEADER_POLICY="5cc3b908-e619-4b99-88e5-2cf7f45965bd" ETAG=`aws cloudfront get-distribution --id $CLOUDFRONT_DISTRIBUTION_ID | jq -r .ETag` aws cloudfront get-distribution --id $CLOUDFRONT_DISTRIBUTION_ID | \ jq --arg NEW_ORIGIN "$NEW_ORIGIN" '.Distribution.DistributionConfig.Origins.Items[0].Id=$NEW_ORIGIN' | \ jq --arg NEW_ORIGIN "$NEW_ORIGIN" '.Distribution.DistributionConfig.Origins.Items[0].DomainName=$NEW_ORIGIN' | \ jq --arg NEW_PATH "$NEW_PATH" '.Distribution.DistributionConfig.Origins.Items[0].OriginPath=$NEW_PATH' | \ jq --arg NEW_RES_HEADER_POLICY "$NEW_RES_HEADER_POLICY" '.Distribution.DistributionConfig.DefaultCacheBehavior.ResponseHeadersPolicyId=$NEW_RES_HEADER_POLICY'  | \ jq --arg NEW_ORIGIN "$NEW_ORIGIN" '.Distribution.DistributionConfig.DefaultCacheBehavior.TargetOriginId=$NEW_ORIGIN' | \ jq .Distribution.DistributionConfig > config.json aws cloudfront update-distribution --id $CLOUDFRONT_DISTRIBUTION_ID --distribution-config "file://config.json" --if-match $ETAG > /dev/null aws cloudfront create-invalidation --distribution-id $CLOUDFRONT_DISTRIBUTION_ID --paths "/*" rm config.json

I want use managed response header policy to update response header policy using awscli


问:
Device collects data less than sampling rate sometimes
I am using a device to capture the ECG data at the sampling rate of 1000. For some seconds, the collected data is not even 500. Is it normal? If yes, do I need to calculate the new sampling rate from the offline data to calculate the correct r peaks? If so, what should my strategy be since I don't want to downsample my data?</p>


问:
Convert where clause(String) to Predicate(CriteriaQuery)
is there a way to convert a where clause to a CriteriaQuery Predicate Object?

I'm looking into JSqlParser to parse a where clause, but before I start trying it myself I wonder if there is already a simple solution out there.


问:
Cookies are not persistent in ionic v1 app since crosswalk plugin removed
I use Ionic v1 and recently have upgraded cordova android to 7.1.4 & removed cordova-plugin-crosswalk-webview plugin as I was facing issue while building the app. I have got new problem that is the cookies are not persisted in the release build. Cookie in our case is used to store session id and inturn used for authorization.
Note: The things works totally fine in the debug version.

Any help will be appreciated.


问:
Slack modal returning nothing, saying "We had some trouble connecting. Try again?"
The problem is, that upon filling in the modal, my client doesn't do anything and instead returns a "We had some trouble connecting. Try again?"

```<code>  app.command("/bugreport", async ({ command, ack, say}) => {
    try {
      await ack();
      app.client.dialog.open(

        {
        "trigger_id": command.trigger_id,
        "dialog": {
          "callback_id": "bug-report",
          "title": "Make an issue",
          "submit_label": "Report",
          "notify_on_cancel": true,
          "elements": [
              {
                  "type": "text",
                  "label": "Your Name",
                  "name": "username"
              },
              {
                "type": "select",
                "label": "Issue Severity",
                "name": "severity",
                "options": [
                  {
                    "label": "Minor",
                    "value": "minor"
                  },
                  {
                    "label": "Moderate",
                    "value": "moderate"
                  },
                  {
                    "label": "Urgent",
                    "value": "urgent"
                  },
                  {
                    "label": "Critical",
                    "value": "critical"
                  }
                ]

              },
              {
                "label": "Description",
                "name": "description",
                "type": "textarea",
                "hint": "Describe the bug in this section. Be thorough and explain the exact cause of the bug"
              },
              {
                "label": "Bug timeline",
                "name": "timeline",
                "type": "text",
                "placeholder": "When did this issue first appear"
              },
              {
                "label": "Expected Behaviour",
                "name": "excpectedBehaviour",
                "type": "textarea",
                "hint": "Detail what you expected the code to do. Just what it was meant to do."
              },
              {
                "label": "Actual Behaviour",
                "name": "actualBehaviour",
                "type": "textarea",
                "hint": "What actually happened, what was different."
              },
              {
                "label": "Steps to reproduce",
                "name": "steps",
                "type": "textarea",
                "placeholder": "1. [First Step]...\n 2. [Second Step]... \n 3. [And so on]... \n"
              },
              {
                "label": "Additional Information",
                "name": "additionalInformation",
                "type": "textarea",
                "hint": "Anything extra to include."
              }

          ]

        }

        }

        )

      } catch (error) {
        console.log("err")
      console.error(error);
    }
  });
  app.event("dialog_submission", async ({ event, context }) => {
    // Extract the values from the submission payload
    const { username, severity, description, timeline, expectedBehaviour, actualBehaviour, steps, additionalInformation } = event.submission;
    if (event.callback_id === "bug-report") {
      // Use the Octokit library to create an issue in the repository
      try {
        const issue = await octokit.issues.create({
          owner: "my-github-username",
          repo: currentRepository,
          title: `${severity} issue reported by ${username}`,
          body: `Description: ${description}
    Timeline: ${timeline}
    Expected Behaviour: ${expectedBehaviour}
    Actual Behaviour: ${actualBehaviour}
    Steps to reproduce: ${steps}
    Additional information: ${additionalInformation}`
        });
        console.log(`Created issue ${issue.data.number}`);
      } catch (error) {
        console.error(`Failed to create issue: ${error.message}`);
      }

      // Use the respond() function to send a response to the user
      try {
        await app.client.chat.postMessage({
          token: context.botToken,
          channel: event.channel.id,
          text: "Thank you for your bug report! We will review it and take appropriate action."
        });
      } catch (error) {
        console.error(`Failed to send response: ${error.message}`);
      }
    }else{
      console.log("what")
    }
  });
</code>```

My code runs fine, just doesn't return anything when you press submit in the modal, and returns an error to the user. I've tried fixing it and scouring for fixes but I don't know what it is. I am using slack in socket mode.

Body:
The problem is, that upon filling in the modal, my client doesn't do anything and instead returns a "We had some trouble connecting. Try again?"

  app.command("/bugreport", async ({ command, ack, say}) => {
    try {
      await ack();
      app.client.dialog.open(

        {
        "trigger_id": command.trigger_id,
        "dialog": {
          "callback_id": "bug-report",
          "title": "Make an issue",
          "submit_label": "Report",
          "notify_on_cancel": true,
          "elements": [
              {
                  "type": "text",
                  "label": "Your Name",
                  "name": "username"
              },
              {
                "type": "select",
                "label": "Issue Severity",
                "name": "severity",
                "options": [
                  {
                    "label": "Minor",
                    "value": "minor"
                  },
                  {
                    "label": "Moderate",
                    "value": "moderate"
                  },
                  {
                    "label": "Urgent",
                    "value": "urgent"
                  },
                  {
                    "label": "Critical",
                    "value": "critical"
                  }
                ]

              },
              {
                "label": "Description",
                "name": "description",
                "type": "textarea",
                "hint": "Describe the bug in this section. Be thorough and explain the exact cause of the bug"
              },
              {
                "label": "Bug timeline",
                "name": "timeline",
                "type": "text",
                "placeholder": "When did this issue first appear"
              },
              {
                "label": "Expected Behaviour",
                "name": "excpectedBehaviour",
                "type": "textarea",
                "hint": "Detail what you expected the code to do. Just what it was meant to do."
              },
              {
                "label": "Actual Behaviour",
                "name": "actualBehaviour",
                "type": "textarea",
                "hint": "What actually happened, what was different."
              },
              {
                "label": "Steps to reproduce",
                "name": "steps",
                "type": "textarea",
                "placeholder": "1. [First Step]...\n 2. [Second Step]... \n 3. [And so on]... \n"
              },
              {
                "label": "Additional Information",
                "name": "additionalInformation",
                "type": "textarea",
                "hint": "Anything extra to include."
              }

          ]

        }

        }

        )

      } catch (error) {
        console.log("err")
      console.error(error);
    }
  });
  app.event("dialog_submission", async ({ event, context }) => {
    // Extract the values from the submission payload
    const { username, severity, description, timeline, expectedBehaviour, actualBehaviour, steps, additionalInformation } = event.submission;
    if (event.callback_id === "bug-report") {
      // Use the Octokit library to create an issue in the repository
      try {
        const issue = await octokit.issues.create({
          owner: "my-github-username",
          repo: currentRepository,
          title: `${severity} issue reported by ${username}`,
          body: `Description: ${description}
    Timeline: ${timeline}
    Expected Behaviour: ${expectedBehaviour}
    Actual Behaviour: ${actualBehaviour}
    Steps to reproduce: ${steps}
    Additional information: ${additionalInformation}`
        });
        console.log(`Created issue ${issue.data.number}`);
      } catch (error) {
        console.error(`Failed to create issue: ${error.message}`);
      }

      // Use the respond() function to send a response to the user
      try {
        await app.client.chat.postMessage({
          token: context.botToken,
          channel: event.channel.id,
          text: "Thank you for your bug report! We will review it and take appropriate action."
        });
      } catch (error) {
        console.error(`Failed to send response: ${error.message}`);
      }
    }else{
      console.log("what")
    }
  });

My code runs fine, just doesn't return anything when you press submit in the modal, and returns an error to the user. I've tried fixing it and scouring for fixes but I don't know what it is. I am using slack in socket mode.


问:
How can I send an attachment from a local drive in a Jenkins FreeStyle Project
I have a FreeStyle project in Jenkins. The project runs a number of tests which are piped to a file on the local drive. I want to be able to pick up the file and email recipients

I tried setting $DEFAULT_CONTENT to c:\temp\results.txt , thinking it will email users in the Project Recipient List, but it didn't.
How can I send this file ?