问:
Error when use semicolon delimiter in AWS ATHENA
I created the table below with ';' delimiter, but in the column 'value' it only appears numbers without 'comma', numbers with comma doesn't appear.</p>
```<code>CREATE EXTERNAL TABLE `table` (
  `value` double,
ROW FORMAT DELIMITED
  FIELDS TERMINATED BY '\;'
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
</code>```
```<code>Inside CSV: | output:
  value        value
    24          24.0
    24,96
</code>```
```<code>Expect:
Inside CSV: | output:
  value        value
    24          24.0
    24,96       24.96
</code>```

Body:
I created the table below with ';' delimiter, but in the column 'value' it only appears numbers without 'comma', numbers with comma doesn't appear.

CREATE EXTERNAL TABLE `table` (
  `value` double,
ROW FORMAT DELIMITED
  FIELDS TERMINATED BY '\;'
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'

Inside CSV: | output:
  value        value
    24          24.0
    24,96

Expect:
Inside CSV: | output:
  value        value
    24          24.0
    24,96       24.96


来源: stackexchange

问:
Identify SNP from genetic position
I am looking for a way to obtain SNP names from their coordinates (Chromosome:BP) - very much the reverse of the question answered here:

(Map SNP IDs to genome coordinates)

Is this possible in R - and if so, how?

ContentLicense: CC BY-SA 4.0

Title: Identify SNP from genetic position


问:
How to capture and send data to two topics with different partition key in Debezium
I want to create one single connector that sends db changes to two different topic with different message key.

So, there should be two different topics that should have same data with different message keys.

Partition keys should be gotten from event data.

Table colums are a and b.

topic-1 is use field a in the event, topic-2 is use field b in the event as message key.

How can I ensure this?


问:
How to get information from a radio button?
I am currently in the process of creating a form and was wondering if there is a way to save radio button information within the function send data. Is there a specific method or technique that I can use to achieve this?</p>
```<code>
<!DOCTYPE html>
<head>
    <base target="_top">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Form</title>
</head>
<body>
<div class="container">
    <br>
    <h1>Custom HTML Forms to Google Sheet</h1>
    <br>
    <div id="form">
        <form>
            <div class="form-group">
                Are you a freshman, sophomore, junior, or senior?
            <br>
            <input type="radio" name="class" value="freshman"> Freshman
            <br>
            <input type="radio" name="class" value="sophomore"> Sophomore
            <br>
            <input type="radio" name="class" value="junior"> Junior
            <br>
            <input type="radio" name="class" value="senior"> Senior
            </div>
    <div id="completion-msg" style="display: none;">
        Thank you for completing this form!
    </div>

</div>

<script>

    function send_data(){
        const form_data = document.getElementsByClassName("form-data"); //retrieve filled form data
        let i;
        const data = [];
        for(i=0; i<form_data.length; i++){
            data.push(form_data[i].value);
        }
        google.script.run.saveData(data); // send to google app script
        document.getElementById("form").style.display = "none"; // make form invisible
        document.getElementById("completion-msg").style.display = "block";
    }
</script>

</body>
</code>```

Body:
I am currently in the process of creating a form and was wondering if there is a way to save radio button information within the function send data. Is there a specific method or technique that I can use to achieve this?

<!DOCTYPE html>

    <base target="_top">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Form</title>

Custom HTML Forms to Google Sheet

        <form>

                Are you a freshman, sophomore, junior, or senior?

            <input type="radio" name="class" value="freshman"> Freshman

            <input type="radio" name="class" value="sophomore"> Sophomore

            <input type="radio" name="class" value="junior"> Junior

            <input type="radio" name="class" value="senior"> Senior

        Thank you for completing this form!


问:
Express Multer - req.file returns undefined
I am trying to upload image file via multer and I dont understand why req.file returns undefined
I have set up form encType to mulipart/form-data, input name matches with the upload.single() parameter. I have also tried to set header multipart/form-data via axios but also did not help

auth.js

```<code>const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, DIR);
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(" ").join("-");
    cb(null, Date.now() + "-" + fileName);
  },
});

const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (
      file.mimetype == "image/png" ||
      file.mimetype == "image/jpg" ||
      file.mimetype == "image/jpeg"
    ) {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error("Only .png, .jpg and .jpeg format allowed!"));
    }
  },
});
router.post(
  "/changeAvatar",
  upload.single("avatar"),
  userAuth,
  async (req, res, next) => {
    try {
      console.log(req.file);
      const url =
        req.protocol + "://" + req.get("host") + "/public/" + req.file.filename;
      const user = await User.findByIdAndUpdate(req.user.id, { image: url });
      res.json({ user });
    } catch (err) {
      res.json({ err });
    }
  }
);
</code>```

react form

```<code>                      <form
                        onSubmit={handlePostAvatar}
                        encType="multipart/form-data"
                      >
                        <input
                          // style={{ display: "none" }}
                          type="file"
                          name="avatar"
                          id="avatar"
                          // ref={avatarFileRef}
                          onChange={changeHandle}
                        />
                        <button style={{ cursor: "pointer" }}>Save</button>
                      </form>
</code>```

post request

```<code>  const handlePostAvatar = async (e) => {
    e.preventDefault();
    try {
      const res = await axios.post("/api/auth/changeAvatar");
      console.log(res);
    } catch (err) {
      console.log(err);
    }
  };
</code>```

Body:
I am trying to upload image file via multer and I dont understand why req.file returns undefined
I have set up form encType to mulipart/form-data, input name matches with the upload.single() parameter. I have also tried to set header multipart/form-data via axios but also did not help

auth.js

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, DIR);
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(" ").join("-");
    cb(null, Date.now() + "-" + fileName);
  },
});

const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (
      file.mimetype == "image/png" ||
      file.mimetype == "image/jpg" ||
      file.mimetype == "image/jpeg"
    ) {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error("Only .png, .jpg and .jpeg format allowed!"));
    }
  },
});
router.post(
  "/changeAvatar",
  upload.single("avatar"),
  userAuth,
  async (req, res, next) => {
    try {
      console.log(req.file);
      const url =
        req.protocol + "://" + req.get("host") + "/public/" + req.file.filename;
      const user = await User.findByIdAndUpdate(req.user.id, { image: url });
      res.json({ user });
    } catch (err) {
      res.json({ err });
    }
  }
);

react form

                      <form
                        onSubmit={handlePostAvatar}
                        encType="multipart/form-data"
                      >
                        <input
                          // style={{ display: "none" }}
                          type="file"
                          name="avatar"
                          id="avatar"
                          // ref={avatarFileRef}
                          onChange={changeHandle}
                        />
                        <button style={{ cursor: "pointer" }}>Save</button>
                      </form>

post request

  const handlePostAvatar = async (e) => {
    e.preventDefault();
    try {
      const res = await axios.post("/api/auth/changeAvatar");
      console.log(res);
    } catch (err) {
      console.log(err);
    }
  };


问:
Python IBKR twsapi reqcontractDetails return value
I am trying to return contractDetails.contract.primaryExchange to my contract object.  I  am isolating the string without problems but I am unable to se it outside of the definition.

```<code>def contractDetails(self, reqId, contractDetails):
     print("redID: {}, contract:{}".format(reqId,contractDetails.contract.primaryExchange))
     return (contractDetails.contract.primaryExchange)
</code>```

.)
.

```<code>api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

time.sleep(1) #Sleep interval to allow time for connection to server

#Create contract object
contract = Contract()
contract.symbol = 'CORN'
contract.secType = 'STK'
contract.exchange = 'SMART'
contract.primaryExchange = ''
contract.currency = 'USD'

contract.primaryExchange = app.reqContractDetails(99, contract)
print(contract)

time.sleep(1) #sleep to allow enough time for data to be returned

print(contract)
</code>```

What am I not understanding or doing wrong?

Thanks in advance

Body:
I am trying to return contractDetails.contract.primaryExchange to my contract object.  I  am isolating the string without problems but I am unable to se it outside of the definition.

def contractDetails(self, reqId, contractDetails):
     print("redID: {}, contract:{}".format(reqId,contractDetails.contract.primaryExchange))
     return (contractDetails.contract.primaryExchange)

.)
.

api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

time.sleep(1) #Sleep interval to allow time for connection to server

#Create contract object
contract = Contract()
contract.symbol = 'CORN'
contract.secType = 'STK'
contract.exchange = 'SMART'
contract.primaryExchange = ''
contract.currency = 'USD'

contract.primaryExchange = app.reqContractDetails(99, contract)
print(contract)

time.sleep(1) #sleep to allow enough time for data to be returned

print(contract)

What am I not understanding or doing wrong?

Thanks in advance


问:
XSLT: Unable to apply UTF-16 LE BOM encoding to output file
I'm using Oxygen XML Editor 25.0, Saxon-PE 11.4.
I need to convert a dictionary to ABBYY DSL format, and it requires the file to be in UTF-16 LE BOM encoding. For some reason, the output file is in UTF-16 BOM format (without LE, little endian). How can I fix this?

The XML file is in UTF-8 encoding.

Here's the XSLT

```<code><?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:character-map name="escape-square-brackets">
    <xsl:output-character character="[" string="\["/>
    <xsl:output-character character="]" string="\]"/>
  </xsl:character-map>

  <xsl:output method="text" encoding="utf-16le" byte-order-mark="no" use-character-maps="escape-square-brackets"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/root">
    <xsl:result-document href="/Users/xinatanil/Desktop/compiling stuff/abbyy_udahin_kg_ru.dsl" method="text">
      <xsl:text>#NAME "Кыргызско-русский словарь"</xsl:text>
      <xsl:text>
</xsl:text>
      <xsl:text>#INDEX_LANGUAGE "Russian"</xsl:text>
      <xsl:text>
</xsl:text>
      <xsl:text>#CONTENTS_LANGUAGE "Russian"</xsl:text>
      <xsl:text>
</xsl:text>
      <xsl:text>
</xsl:text>

      <root>
        <xsl:for-each select="card">
          <xsl:value-of select="k"/>
          <xsl:text>
</xsl:text>
          <xsl:for-each select="body/blockquote">
            <xsl:text> </xsl:text>
            <xsl:value-of select="."/>
            <xsl:text>
</xsl:text>
          </xsl:for-each>
          <xsl:text>
</xsl:text>
        </xsl:for-each>
      </root>
    </xsl:result-document>
  </xsl:template>
</xsl:stylesheet>
</code>```

And here's a small chunk of the XML I'm trying to transform

```<code><?xml version="1.0" encoding="utf-8"?>
<root>
   <card>
      <k>а</k>
      <body>
         <blockquote>а I</blockquote>
         <blockquote>1. возглас удивления;</blockquote>
         <blockquote>2. вопрос с оттенком удивления или неудовольствия.</blockquote>
         <blockquote>а II</blockquote>
         <blockquote>см. ал II;</blockquote>
         <blockquote>мейли, не болсо, а болсун всё равно, будь, что будет;</blockquote>
         <blockquote>а түгүл</blockquote>
         <blockquote>1) не тот; не он;</blockquote>
         <blockquote>2) не только тот;</blockquote>
         <blockquote>а береги вон тот;</blockquote>
         <blockquote>а болду, бу болду, Эшкаранын он төөсү өлдү погов. то было, (да) это было, десять верблюдов Эшкары пало (что ни говори, а это факт).</blockquote>
         <blockquote>а III</blockquote>
         <blockquote>(неправ. вместо аа)</blockquote>
         <blockquote>см. ал II;</blockquote>
         <blockquote>а көрө муну сүйлөйлүчү вместо того (лучше) поговорим об этом;</blockquote>
         <blockquote>а эмне дедиңер? вы что ему сказали?</blockquote>
         <blockquote>бирок а Темирдин көзү жетти но Темир понял это;</blockquote>
         <blockquote>адам баласы аа эмне дебес! что (только) человек не скажет об этом!</blockquote>
         <blockquote>а IV</blockquote>
         <blockquote>р.</blockquote>
         <blockquote>союз а;</blockquote>
         <blockquote>а сен эмне үчүн кетпей отурасың? а ты почему сидишь и не уходишь?</blockquote>
         <blockquote>ах сен болсоң... а что касается тебя...; а ты...;</blockquote>
         <blockquote>а эмичи? ну, а теперь?</blockquote>
         <blockquote>а эми болсо... а вот теперь... аа см. ал II.</blockquote>
      </body>
   </card>
   <card>
      <k>аалам</k>
      <body>
         <blockquote>ар.</blockquote>
         <blockquote>мир, вселенная;</blockquote>
         <blockquote>ааламды басып шоораты фольк. слава о нём разнеслась по всему миру;</blockquote>
         <blockquote>ааламга белгилүү всемирно известный;</blockquote>
         <blockquote>он сегиз миң аалам фольк. вселенная (земля со всем населяющим её);</blockquote>
         <blockquote>он сегиз миң аалам - көк өгүздүн жонунда стих. вселенная (держится) на хребте сивого быка (по старому народному представлению);</blockquote>
         <blockquote>он сегиз миң ааламды камырдай тепсеп баскаңдай фольк. (у богатыря такой вид) будто всю вселенную может месить, как тесто;</blockquote>
         <blockquote>бул бала ааламга татыйт этот паренёк мировой;</blockquote>
         <blockquote>ааламдан ашкан см. аш- II 2.</blockquote>
      </body>
   </card>
   <card>
      <k>ааламдык</k>
      <body>
         <blockquote>несметный (букв. то, что есть во всём мире);</blockquote>
         <blockquote>ааламдык дилде, сансыз мүлк фольк. несметное количество золота, бесчисленные богатства.</blockquote>
      </body>
   </card>
</root>
</code>```

Body:
I'm using Oxygen XML Editor 25.0, Saxon-PE 11.4.
I need to convert a dictionary to ABBYY DSL format, and it requires the file to be in UTF-16 LE BOM encoding. For some reason, the output file is in UTF-16 BOM format (without LE, little endian). How can I fix this?

The XML file is in UTF-8 encoding.

Here's the XSLT

<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:character-map name="escape-square-brackets">
    <xsl:output-character character="[" string="\["/>
    <xsl:output-character character="]" string="\]"/>
  </xsl:character-map>

  <xsl:output method="text" encoding="utf-16le" byte-order-mark="no" use-character-maps="escape-square-brackets"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/root">
    <xsl:result-document href="/Users/xinatanil/Desktop/compiling stuff/abbyy_udahin_kg_ru.dsl" method="text">
      <xsl:text>#NAME "Кыргызско-русский словарь"</xsl:text>
      <xsl:text>
</xsl:text>
      <xsl:text>#INDEX_LANGUAGE "Russian"</xsl:text>
      <xsl:text>
</xsl:text>
      <xsl:text>#CONTENTS_LANGUAGE "Russian"</xsl:text>
      <xsl:text>
</xsl:text>
      <xsl:text>
</xsl:text>

      <root>
        <xsl:for-each select="card">
          <xsl:value-of select="k"/>
          <xsl:text>
</xsl:text>
          <xsl:for-each select="body/blockquote">
            <xsl:text> </xsl:text>
            <xsl:value-of select="."/>
            <xsl:text>
</xsl:text>
          </xsl:for-each>
          <xsl:text>
</xsl:text>
        </xsl:for-each>
      </root>
    </xsl:result-document>
  </xsl:template>
</xsl:stylesheet>

And here's a small chunk of the XML I'm trying to transform

<?xml version="1.0" encoding="utf-8"?>
<root>
   <card>
      <k>а</k>

а I

1. возглас удивления;

2. вопрос с оттенком удивления или неудовольствия.

а II

см. ал II;

мейли, не болсо, а болсун всё равно, будь, что будет;

а түгүл

1) не тот; не он;

2) не только тот;

а береги вон тот;

а болду, бу болду, Эшкаранын он төөсү өлдү погов. то было, (да) это было, десять верблюдов Эшкары пало (что ни говори, а это факт).

а III

(неправ. вместо аа)

см. ал II;

а көрө муну сүйлөйлүчү вместо того (лучше) поговорим об этом;

а эмне дедиңер? вы что ему сказали?

бирок а Темирдин көзү жетти но Темир понял это;

адам баласы аа эмне дебес! что (только) человек не скажет об этом!

а IV

р.

союз а;

а сен эмне үчүн кетпей отурасың? а ты почему сидишь и не уходишь?

ах сен болсоң... а что касается тебя...; а ты...;

а эмичи? ну, а теперь?

а эми болсо... а вот теперь... аа см. ал II.

   </card>
   <card>
      <k>аалам</k>

ар.

мир, вселенная;

ааламды басып шоораты фольк. слава о нём разнеслась по всему миру;

ааламга белгилүү всемирно известный;

он сегиз миң аалам фольк. вселенная (земля со всем населяющим её);

он сегиз миң аалам - көк өгүздүн жонунда стих. вселенная (держится) на хребте сивого быка (по старому народному представлению);

он сегиз миң ааламды камырдай тепсеп баскаңдай фольк. (у богатыря такой вид) будто всю вселенную может месить, как тесто;

бул бала ааламга татыйт этот паренёк мировой;

ааламдан ашкан см. аш- II 2.

   </card>
   <card>
      <k>ааламдык</k>

несметный (букв. то, что есть во всём мире);

ааламдык дилде, сансыз мүлк фольк. несметное количество золота, бесчисленные богатства.

   </card>
</root>


问:
Map with optional variables as Keys and multiple if elseif condition
Need your help because I'm overthinking a bit. :P
I'm doing a development in apex where we build a Map based on certain keys. Those keys are a mix of multiple variables and so when building a map we have something like:

```<code>for(rule){
    key = String.isBlank(rule.CompanyRisk) ? '' : rule.CompanyRisk;
    key +=  String.isBlank(rule.PriceType) ? '' : rule.PriceType;
    key +=  String.isBlank(rule.Product) ? '' : rule.Product;
    key +=  String.isBlank(rule.CompanySize) ? '' : rule.CompanySize;
    //..
    map.put(Key, rule.Value);
}
return map;

//and later to get the correct value
for(offerRecord){
String accRisk = offerRecord.CompanyRisk;
String price = offerRecord.PriceType;
String product= offerRecord.Product;
String accSize = offerRecord.CompanySize;

    if(map.contains(accRisk + price + product + accSize)){
        key = accRisk + price + product + accSize;
    }else if(map.contains( accRisk + price + product + '')){
        key = accRisk + price + product + '';
    }else if(map.contains(accRisk + price + '' + accSize)){
        key = accRisk + price + '' + accSize,
    }else if.. //16 conditions now (4 variables as optional)
}
return map.get(key);
</code>```

Issue:
Some fields on the key are optional and that happens so the users dont need to create all the rules for all the combinatorions. and when those  optional fields are empty/null it's because it applies for all values of the field.

Example: We can have a rule as (LowRisk + Indexed + Computer + Small) with Value=4 and a rule for (Low + Indexed + Computer + '' ) with Value=5 , meaning if the company is small applies the 1st rule but if it it's medium/big/top it applies the one without. Same for the other fields. I can have just one saying (HighRisk + + +) with a value of 0 without the need of specifying all the other criteriums and it applies for all of them.

Because we need to always checking first rules/keys with the optional fields filled, it will become a mess due to a lot of if else.
The conditions are like (ABCD, ABC, ABD, AB, ACD, AC, AD, A, BCD, BC, BD, B, CD, C, D ,'' )

Is there any better solution that could improve this?

I was trying now building some Wrapper class that would return a List for the all combinations and then have a specific method getRuleForRecord() which based on the List (ordered) creates a key from the values of record and checks if map has that key. Not a much prettier aproach. The worst now is building the listOfCombinations on the order I want

```<code>List<String> keyList = singleton.listOfCombinations;
for (String fieldList : keyList) {
    String mapKey = '';
    for (String field : fieldList.split('_')) {
        mapKey += recordToGetInfoFrom.get(field);
    }
    if (singleton.ruleMap.containsKey(mapKey)) {
        return singleton.remRules.get(mapKey);
    }
}
</code>```

Body:
Need your help because I'm overthinking a bit. :P
I'm doing a development in apex where we build a Map based on certain keys. Those keys are a mix of multiple variables and so when building a map we have something like:

for(rule){
    key = String.isBlank(rule.CompanyRisk) ? '' : rule.CompanyRisk;
    key +=  String.isBlank(rule.PriceType) ? '' : rule.PriceType;
    key +=  String.isBlank(rule.Product) ? '' : rule.Product;
    key +=  String.isBlank(rule.CompanySize) ? '' : rule.CompanySize;
    //..
    map.put(Key, rule.Value);
}
return map;

//and later to get the correct value
for(offerRecord){
String accRisk = offerRecord.CompanyRisk;
String price = offerRecord.PriceType;
String product= offerRecord.Product;
String accSize = offerRecord.CompanySize;

    if(map.contains(accRisk + price + product + accSize)){
        key = accRisk + price + product + accSize;
    }else if(map.contains( accRisk + price + product + '')){
        key = accRisk + price + product + '';
    }else if(map.contains(accRisk + price + '' + accSize)){
        key = accRisk + price + '' + accSize,
    }else if.. //16 conditions now (4 variables as optional)
}
return map.get(key);

Issue:
Some fields on the key are optional and that happens so the users dont need to create all the rules for all the combinatorions. and when those  optional fields are empty/null it's because it applies for all values of the field.

Example: We can have a rule as (LowRisk + Indexed + Computer + Small) with Value=4 and a rule for (Low + Indexed + Computer + '' ) with Value=5 , meaning if the company is small applies the 1st rule but if it it's medium/big/top it applies the one without. Same for the other fields. I can have just one saying (HighRisk + + +) with a value of 0 without the need of specifying all the other criteriums and it applies for all of them.

Because we need to always checking first rules/keys with the optional fields filled, it will become a mess due to a lot of if else.
The conditions are like (ABCD, ABC, ABD, AB, ACD, AC, AD, A, BCD, BC, BD, B, CD, C, D ,'' )

Is there any better solution that could improve this?

I was trying now building some Wrapper class that would return a List for the all combinations and then have a specific method getRuleForRecord() which based on the List (ordered) creates a key from the values of record and checks if map has that key. Not a much prettier aproach. The worst now is building the listOfCombinations on the order I want

List<String> keyList = singleton.listOfCombinations;
for (String fieldList : keyList) {
    String mapKey = '';
    for (String field : fieldList.split('_')) {
        mapKey += recordToGetInfoFrom.get(field);
    }
    if (singleton.ruleMap.containsKey(mapKey)) {
        return singleton.remRules.get(mapKey);
    }
}


问:
How to execute a function according to user's input to make a two 3x3 matrices? Program in C to make calculations on matrices
I'm trying to make my first program in C today, and I've had some troubles with it. I wanted to make program that can make calculations on 2D matrices, i made it working for most of the part, except evaluating division. I suppose it's because matrices are integers and divisions can be floats. Is there a way to make only division function work with floats instead of whole program? Second, and the most important issue comes with my own put() function. I would like to make this whole program work on two modes, first works with already declared matrices, so we don't have to write them every time, second asks you for input to make new matrices to work with.

```<code>#include <stdio.h>
//-------------------PUT--------------------//
//=================================================//
int put(int i, int k, int tabA[3][3], int tabB[3][3]) {
    int n;
    for (int i = 0; i < 3; i++) {
        for (int k = 0; k < 3; k++) {
            scanf("A|%d:%d|:%d\t", &i, &k, &n);
            tabA[i][k] = n;
        }
    }
    for (int i = 0; i < 3; i++) {
        for (int k = 0; k < 3; k++) {
            scanf("A|%d:%d|:%d\t", &i, &k, &n);
            tabB[i][k] = n;
        }
    }
    return tabA[i][k] && tabB[i][k];
}
//-------------------SUM-------------------//
//=================================================//
int sum(int i, int k, int tabD[3][3], int tabA[3][3], int tabB[3][3]) {
    for (int i = 0; i < 3; i++) {
        for (int k = 0; k < 3; k++) {
            tabD[i][k] = tabA[i][k] + tabB[i][k];
        }
    }
    return tabD[i][k];
}
//-------------------DIF-------------------//
//=================================================//
int dif(int i, int k, int tabD[3][3], int tabA[3][3], int tabB[3][3]) {
    for (int i = 0; i < 3; i++) {
        for (int k = 0; k < 3; k++) {
            tabD[i][k] = tabA[i][k] - tabB[i][k];
        }
    }
    return tabD[i][k];
}
//-------------------DIV-------------------//
//=================================================//
//TODO: fix div - CONVERT TO FLOAT
int div(int i, int k, int tabD[3][3], int tabA[3][3], int tabB[3][3]) {
    for (int i = 0; i < 3; i++) {
        for (int k = 0; k < 3; k++) {
            tabD[i][k] = tabD[i][k] + tabA[i][k] / tabB[i][k];
        }
    }
    return tabD[i][k];
}
//-------------------MUL-------------------//
//=================================================//
int mul(int i, int j, int k, int tabD[3][3], int tabA[3][3], int tabB[3][3]) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            tabD[i][k] = 0;
            for (int k = 0; k < 3; k++) {
                tabD[i][k] = tabD[i][k] + tabA[i][k] * tabB[i][k];
            }
        }
    }
    return tabD[i][k];
}

//-------------------MAIN-------------------//
//=================================================//
int main() {
    //-------------------//
    int i, j, k;
    int y; printf("1: put,\t0: get\t:..."); scanf("%d", &y);
    int tabA[3][3] = { {1, 2, 3}, {1, 2, 3}, {1, 2, 3} };
    int tabB[3][3] = { {4, 5, 6}, {4, 5, 6}, {4, 5, 6} };
    int tabD[3][3];

    //TODO: fix put
    \*
        if (y == 1) {
            put(int i, int k, int tabA[3][3], int tabB[3][3]);
        }
    */

        int x; printf("1: sum,\t2: dif,\t3: div(In Work),\t4: mul\t:..."); scanf("%d", &x);
    //-------------------//

    for (i = 0; i < 3; i++) {
        for (k = 0; k < 3; k++) {
            switch (x) {
            case 1: printf("|%d:%d| = %d\t", i, k, sum(i, k, tabD, tabA, tabB));
                break;
            case 2: printf("|%d:%d| = %d\t", i, k, dif(i, k, tabD, tabA, tabB));
                break;
            case 3: printf("|%d:%d| = %d\t", i, k, div(i, k, tabD, tabA, tabB));
                break;
            case 4: printf("|%d:%d| = %d\t", i, k, mul(i, j, k, tabD, tabA, tabB));
                break;
            }
        }
    }

    return 0;
}
//=================================================//
</code>```

I already tried it to work with if statement, and similary with switch, but couldnt get it going.

Body:
I'm trying to make my first program in C today, and I've had some troubles with it. I wanted to make program that can make calculations on 2D matrices, i made it working for most of the part, except evaluating division. I suppose it's because matrices are integers and divisions can be floats. Is there a way to make only division function work with floats instead of whole program? Second, and the most important issue comes with my own put() function. I would like to make this whole program work on two modes, first works with already declared matrices, so we don't have to write them every time, second asks you for input to make new matrices to work with.

#include <stdio.h>
//-------------------PUT--------------------//
//=================================================//
int put(int i, int k, int tabA[3][3], int tabB[3][3]) {
    int n;
    for (int i = 0; i < 3; i++) {
        for (int k = 0; k < 3; k++) {
            scanf("A|%d:%d|:%d\t", &i, &k, &n);
            tabA[i][k] = n;
        }
    }
    for (int i = 0; i < 3; i++) {
        for (int k = 0; k < 3; k++) {
            scanf("A|%d:%d|:%d\t", &i, &k, &n);
            tabB[i][k] = n;
        }
    }
    return tabA[i][k] && tabB[i][k];
}
//-------------------SUM-------------------//
//=================================================//
int sum(int i, int k, int tabD[3][3], int tabA[3][3], int tabB[3][3]) {
    for (int i = 0; i < 3; i++) {
        for (int k = 0; k < 3; k++) {
            tabD[i][k] = tabA[i][k] + tabB[i][k];
        }
    }
    return tabD[i][k];
}
//-------------------DIF-------------------//
//=================================================//
int dif(int i, int k, int tabD[3][3], int tabA[3][3], int tabB[3][3]) {
    for (int i = 0; i < 3; i++) {
        for (int k = 0; k < 3; k++) {
            tabD[i][k] = tabA[i][k] - tabB[i][k];
        }
    }
    return tabD[i][k];
}
//-------------------DIV-------------------//
//=================================================//
//TODO: fix div - CONVERT TO FLOAT
int div(int i, int k, int tabD[3][3], int tabA[3][3], int tabB[3][3]) {
    for (int i = 0; i < 3; i++) {
        for (int k = 0; k < 3; k++) {
            tabD[i][k] = tabD[i][k] + tabA[i][k] / tabB[i][k];
        }
    }
    return tabD[i][k];
}
//-------------------MUL-------------------//
//=================================================//
int mul(int i, int j, int k, int tabD[3][3], int tabA[3][3], int tabB[3][3]) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            tabD[i][k] = 0;
            for (int k = 0; k < 3; k++) {
                tabD[i][k] = tabD[i][k] + tabA[i][k] * tabB[i][k];
            }
        }
    }
    return tabD[i][k];
}

//-------------------MAIN-------------------//
//=================================================//
int main() {
    //-------------------//
    int i, j, k;
    int y; printf("1: put,\t0: get\t:..."); scanf("%d", &y);
    int tabA[3][3] = { {1, 2, 3}, {1, 2, 3}, {1, 2, 3} };
    int tabB[3][3] = { {4, 5, 6}, {4, 5, 6}, {4, 5, 6} };
    int tabD[3][3];

    //TODO: fix put
    \*
        if (y == 1) {
            put(int i, int k, int tabA[3][3], int tabB[3][3]);
        }
    */

        int x; printf("1: sum,\t2: dif,\t3: div(In Work),\t4: mul\t:..."); scanf("%d", &x);
    //-------------------//

    for (i = 0; i < 3; i++) {
        for (k = 0; k < 3; k++) {
            switch (x) {
            case 1: printf("|%d:%d| = %d\t", i, k, sum(i, k, tabD, tabA, tabB));
                break;
            case 2: printf("|%d:%d| = %d\t", i, k, dif(i, k, tabD, tabA, tabB));
                break;
            case 3: printf("|%d:%d| = %d\t", i, k, div(i, k, tabD, tabA, tabB));
                break;
            case 4: printf("|%d:%d| = %d\t", i, k, mul(i, j, k, tabD, tabA, tabB));
                break;
            }
        }
    }

    return 0;
}
//=================================================//

I already tried it to work with if statement, and similary with switch, but couldnt get it going.


问:
preventing two identical files from being uploaded React JS
how to prevent duplicate files from being added to the state?

```<code>export const Files = React.memo(() => {
  const [uploadFiles, setFiles] = React.useState([]);

  const handleFile = (event) => {
    const file = event.target.files;
    setFiles(uploadFiles.concat([...file]));
  };

  console.log(uploadFiles);

  return (
    <div>
      <input type="file" multiple onChange={handleFile} />
      {uploadFiles && uploadFiles?.map((f) => <div>{f.name}</div>)}
    </div>
  );
});
</code>```

as a result, I can output 2 identical files. But I need only 1
can be like that before adding to compare file names and remove them from the mass state?

Body:
how to prevent duplicate files from being added to the state?

export const Files = React.memo(() => {
  const [uploadFiles, setFiles] = React.useState([]);

  const handleFile = (event) => {
    const file = event.target.files;
    setFiles(uploadFiles.concat([...file]));
  };

  console.log(uploadFiles);

  return (

      <input type="file" multiple onChange={handleFile} />
      {uploadFiles && uploadFiles?.map((f) =>
{f.name}
)}

  );
});

as a result, I can output 2 identical files. But I need only 1
can be like that before adding to compare file names and remove them from the mass state?


问:
cmd Redirect Standard Input c#
I am writing my own terminal and want to add the ability to execute CMD commas. I found this code on Microsoft website:

```<code>
using System;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;

namespace ProcessStandardInputSample
{
    class StandardInputTest
    {
        static void Main()
        {
            Console.WriteLine("Ready to sort one or more text lines...");

            // Start the Sort.exe process with redirected input.
            // Use the sort command to sort the input text.
            using (Process myProcess = new Process())
            {
                myProcess.StartInfo.FileName = "cmd.exe";
                myProcess.StartInfo.UseShellExecute = false;
                myProcess.StartInfo.RedirectStandardInput = true;

                myProcess.Start();

                StreamWriter myStreamWriter = myProcess.StandardInput;

                // Prompt the user for input text lines to sort.
                // Write each line to the StandardInput stream of
                // the sort command.
                String inputText;
                int numLines = 0;
                do
                {
                    Console.WriteLine("Enter a line of text (or press the Enter key to stop):");

                    inputText = Console.ReadLine();
                    if (inputText.Length > 0)
                    {
                        numLines++;
                        myStreamWriter.WriteLine(inputText);
                    }
                } while (inputText.Length > 0);

                // Write a report header to the console.
                if (numLines > 0)
                {
                    Console.WriteLine($" {numLines} sorted text line(s) ");
                    Console.WriteLine("------------------------");
                }
                else
                {
                    Console.WriteLine(" No input was sorted");
                }

                // End the input stream to the sort command.
                // When the stream closes, the sort command
                // writes the sorted text lines to the
                // console.
                myStreamWriter.Close();

                // Wait for the sort process to write the sorted text lines.
                myProcess.WaitForExit();
            }
        }
    }

}
</code>```

I tested this code on several commands and everything worked fine, without errors. But I decided to test running python scripts with this code. I decided to run sqlmap through my terminal with the command:

python C:\sqlmap\sqlmap.py --wizard

I got the following result:

```<code>        ___
       __H__
 ___ ___["]_____ ___ ___  {1.6.11.3#dev}
|_ -| . [(]     | .'| . |
|___|_  ["]_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 22:26:59 /2022-12-07/

[22:26:59] [INFO] starting wizard interface
Please enter full target URL (-u):
</code>```

At this stage, everything works properly, without errors.
When I enter any link, I always get the same result:

```<code>POST data (--data) [Enter for None]:
Injection difficulty (--level/--risk). Please choose:
[1] Normal (default)
[2] Medium
[3] Hard
> 1
Enumeration (--banner/--current-user/etc). Please choose:
[1] Basic (default)
[2] Intermediate
[3] All
> 1

sqlmap is running, please wait..
</code>```

The problem is that after entering the link in the future, the program does not expect any input from the user, all the parameters in the above result were not entered by the user

I did not find an answer to my question on the Internet, why the parameters are set themselves, without user participation. I would be very grateful if I get an answer to my question, because I do not understand what exactly the problem is

I wanted all parameters to be requested from the user, and not set without his knowledge.

Title: cmd Redirect Standard Input c#

Body:
I am writing my own terminal and want to add the ability to execute CMD commas. I found this code on Microsoft website:

using System;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;

namespace ProcessStandardInputSample
{
    class StandardInputTest
    {
        static void Main()
        {
            Console.WriteLine("Ready to sort one or more text lines...");

            // Start the Sort.exe process with redirected input.
            // Use the sort command to sort the input text.
            using (Process myProcess = new Process())
            {
                myProcess.StartInfo.FileName = "cmd.exe";
                myProcess.StartInfo.UseShellExecute = false;
                myProcess.StartInfo.RedirectStandardInput = true;

                myProcess.Start();

                StreamWriter myStreamWriter = myProcess.StandardInput;

                // Prompt the user for input text lines to sort.
                // Write each line to the StandardInput stream of
                // the sort command.
                String inputText;
                int numLines = 0;
                do
                {
                    Console.WriteLine("Enter a line of text (or press the Enter key to stop):");

                    inputText = Console.ReadLine();
                    if (inputText.Length > 0)
                    {
                        numLines++;
                        myStreamWriter.WriteLine(inputText);
                    }
                } while (inputText.Length > 0);

                // Write a report header to the console.
                if (numLines > 0)
                {
                    Console.WriteLine($" {numLines} sorted text line(s) ");
                    Console.WriteLine("------------------------");
                }
                else
                {
                    Console.WriteLine(" No input was sorted");
                }

                // End the input stream to the sort command.
                // When the stream closes, the sort command
                // writes the sorted text lines to the
                // console.
                myStreamWriter.Close();

                // Wait for the sort process to write the sorted text lines.
                myProcess.WaitForExit();
            }
        }
    }

}

I tested this code on several commands and everything worked fine, without errors. But I decided to test running python scripts with this code. I decided to run sqlmap through my terminal with the command:

python C:\sqlmap\sqlmap.py --wizard

I got the following result:

        ___
       __H__
 ___ ___["]_____ ___ ___  {1.6.11.3#dev}
|_ -| . [(]     | .'| . |
|___|_  ["]_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 22:26:59 /2022-12-07/

[22:26:59] [INFO] starting wizard interface
Please enter full target URL (-u):

At this stage, everything works properly, without errors.
When I enter any link, I always get the same result:

POST data (--data) [Enter for None]:
Injection difficulty (--level/--risk). Please choose:
[1] Normal (default)
[2] Medium
[3] Hard
> 1
Enumeration (--banner/--current-user/etc). Please choose:
[1] Basic (default)
[2] Intermediate
[3] All
> 1

sqlmap is running, please wait..

The problem is that after entering the link in the future, the program does not expect any input from the user, all the parameters in the above result were not entered by the user

I did not find an answer to my question on the Internet, why the parameters are set themselves, without user participation. I would be very grateful if I get an answer to my question, because I do not understand what exactly the problem is

I wanted all parameters to be requested from the user, and not set without his knowledge.


问:
Vue - TextArea maxLength restriction inconsistent between OS
I have a textarea input that I'm looking to restrict to a certain number of characters.

```<code><textarea
    id="text-area"
    class="form-control"
    v-model="textContent"
    maxlength="100">
</textarea>
<span>{{textContent.length}} / 100</span>
</code>```

This works fine on a windows machine but if it is being interacted with on macOS/iOS using chrome the inconsistency with newline characters causes the textContent.length to never reach the 500 limit as it appears the textarea counts newline characters as 2 characters but the browser does not and will only register 1 character with regards to the binded property's length.

Is there a way to get consistent behavior across the experiences?

Body:
I have a textarea input that I'm looking to restrict to a certain number of characters.

<textarea
    id="text-area"
    class="form-control"
    v-model="textContent"
    maxlength="100">
</textarea>
{{textContent.length}} / 100

This works fine on a windows machine but if it is being interacted with on macOS/iOS using chrome the inconsistency with newline characters causes the textContent.length to never reach the 500 limit as it appears the textarea counts newline characters as 2 characters but the browser does not and will only register 1 character with regards to the binded property's length.

Is there a way to get consistent behavior across the experiences?


问:
What is the actual impact of choosing ".NET" as "Active Solution Platform"?
I would like to understand the real implications of choosing the ".NET" as the "Active Solution Platform" on a Visual Studio 2010 solution.

For each project listed on my solution I have the available options as Platform target: "Any CPU" or "x86". So I'm not sure what does the ".NET" option, as a solution-wide setting means.

ContentLicense: CC BY-SA 3.0


问:
What impacts the latency of requests with proxies in a threaded environment (Python)?
I'm doing some web scraping, and once I start running more than 50 threads (One dedicated proxy per One thread, with some of them seemingly being on the same subnet, all though I'm not sure if that's indicative of anything) the measured response time increases (I simply measure it by asserting the time before the request and printing the difference of the time after the thread and the starting time).
What might cause that?

To make sure that it's not a Python performance issue, or software design flaw I split the amount of threads per program and ran multiple instances of the scraper to utilize multiprocessing.
This did not increase the response times.


问:
How to scroll to the particular row after loading data in Infinite Loading? In React BaseTable
```<code>const tableRef = createRef(null)

useEffect(() => {
      if (sessionStorage.getItem('transactionScrollTopPosition') && tableRef.current != null) {

        const transactionOffsetTopPosition = sessionStorage.getItem('transactionScrollTopPosition')

        tableRef.current.scrollToTop(transactionOffsetTopPosition)

        setOffset(transactionOffsetTopPosition)
        sessionStorage.removeItem('transactionScrollTopPosition')
      }
    }, [tableRef])
</code>```

tableRef.current.scrollToTop(transactionOffsetTopPosition)

I already use this method [scrollToPosition, scrollToRow] but
this method works only in normal scenarios, that not working in infinite loading. Is there any way to do that?

Body:
const tableRef = createRef(null)

useEffect(() => {
      if (sessionStorage.getItem('transactionScrollTopPosition') && tableRef.current != null) {

        const transactionOffsetTopPosition = sessionStorage.getItem('transactionScrollTopPosition')

        tableRef.current.scrollToTop(transactionOffsetTopPosition)

        setOffset(transactionOffsetTopPosition)
        sessionStorage.removeItem('transactionScrollTopPosition')
      }
    }, [tableRef])

tableRef.current.scrollToTop(transactionOffsetTopPosition)

I already use this method [scrollToPosition, scrollToRow] but
this method works only in normal scenarios, that not working in infinite loading. Is there any way to do that?


问:
Can I use Laravel's File Response with AJAX calls to fetch many images?
I want to display images that users upload to storage/uploads/ folder which is outside of the website's root folder (Because I don't want other users to have access to each other's uploaded photos).

I did a test and tried to use the File Response as described in the docs: https://laravel.com/docs/9.x/responses#file-responses

This is how I did it:

In web.php:

Route::get('show_image', [ImageController::class, 'show_image']);
```
<p>In <code>ImageController</code>:</p>
<pre class="lang-php prettyprint-override"><code>public function show_image(Request $request)
{
    $pathToFile = '../storage/uploads/460s6DLmCnvoom90S7wfk.jpg';
    return response()->file($pathToFile);
}
</code>```

Now when I enter the url of the route in the browser: http://mysite.dev/show_image it displays me the image in the browser inside an img tag with src=http://mysite.dev/show_image (Not a blade file or anything, I simply enter the URL in the browser and it does that automatically.

But the above example was done only with 1 file, and with simply going to the URL in the browser.

But what I really need is to fetch many images from the storage/uploads/ folder using AJAX (Or Fetch API in my case) and then append these images to a list in the browser.

Currently this is how I fetch the files with Fetch API:

const getImagesPromise = fetch('get_images');
getImages
    .then((response) => {

    })
    .then((data) => {

    });
```

But it doesn't seem to return anything I can work with? When I call it for the single image in the test above, I see in devtools that the response preview says Image from http://mysite.dev/show_image. (And again this is just for single file, haven't figured how to call multiple)

Body:
I want to display images that users upload to storage/uploads/ folder which is outside of the website's root folder (Because I don't want other users to have access to each other's uploaded photos).

I did a test and tried to use the File Response as described in the docs: https://laravel.com/docs/9.x/responses#file-responses

This is how I did it:

In web.php:

Route::get('show_image', [ImageController::class, 'show_image']);

In ImageController:

public function show_image(Request $request)
{
    $pathToFile = '../storage/uploads/460s6DLmCnvoom90S7wfk.jpg';
    return response()->file($pathToFile);
}

Now when I enter the url of the route in the browser: http://mysite.dev/show_image it displays me the image in the browser inside an img tag with src=http://mysite.dev/show_image (Not a blade file or anything, I simply enter the URL in the browser and it does that automatically.

But the above example was done only with 1 file, and with simply going to the URL in the browser.

But what I really need is to fetch many images from the storage/uploads/ folder using AJAX (Or Fetch API in my case) and then append these images to a list in the browser.

Currently this is how I fetch the files with Fetch API:

const getImagesPromise = fetch('get_images');
getImages
    .then((response) => {

    })
    .then((data) => {

    });

But it doesn't seem to return anything I can work with? When I call it for the single image in the test above, I see in devtools that the response preview says Image from http://mysite.dev/show_image. (And again this is just for single file, haven't figured how to call multiple)


问:
SAPUI5 - Find View-Elements by BindingPath
Is there a way to determine the view element for a BindingPath. So the elements that have a binding to this path.

I have the binding path and want to use it to determine the view element.

Example:

var sPath = "/SomeSet/results/0";
```
<p>Something like</p>
<pre class="lang-js prettyprint-override"><code>aViewElements = this.getView().byBindingPath("/BudgetSet/results/0");
</code>```

Background of the question is that I want to give ALL input fields that have this binding a CSS class

My most promising approach is via the model binding, since that's where the refresh happens.
Unfortunately, I could only find the bindings that are active there. But from there I can't get to the view elements yet.

this.getView().getModel("SomeModel").getBindings()
```

After a long search, I ask here.
I hope you can help me.

Greetings

Body:
Is there a way to determine the view element for a BindingPath. So the elements that have a binding to this path.

I have the binding path and want to use it to determine the view element.

Example:

var sPath = "/SomeSet/results/0";

Something like

aViewElements = this.getView().byBindingPath("/BudgetSet/results/0");

Background of the question is that I want to give ALL input fields that have this binding a CSS class

My most promising approach is via the model binding, since that's where the refresh happens.
Unfortunately, I could only find the bindings that are active there. But from there I can't get to the view elements yet.

this.getView().getModel("SomeModel").getBindings()

After a long search, I ask here.
I hope you can help me.

Greetings


问:
pyodbc [unixODBC][Driver Manager]Can't open lib 'PostgreSQL Unicode' : file not found
I'm trying to use pyodbc to connect postgresql db:

```<code>import pyodbc
conn_str = (
    "DRIVER={PostgreSQL Unicode};"
    "DATABASE=postgres;"
    "UID=postgres;"
    "PWD=11111;"
    "SERVER=localhost;"
    "PORT=5432;"
    )
conn = pyodbc.connect(conn_str)
</code>```

Error:

```<code>Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'PostgreSQL Unicode' : file not found (0) (SQLDriverConnect)")
</code>```

Did I missed install some other packages like driver ?

Body:
I'm trying to use pyodbc to connect postgresql db:

import pyodbc
conn_str = (
    "DRIVER={PostgreSQL Unicode};"
    "DATABASE=postgres;"
    "UID=postgres;"
    "PWD=11111;"
    "SERVER=localhost;"
    "PORT=5432;"
    )
conn = pyodbc.connect(conn_str)

Error:

Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'PostgreSQL Unicode' : file not found (0) (SQLDriverConnect)")

Did I missed install some other packages like driver ?


问:
Solidity Proxies, Multiple Inheritance, and Storage Slots
Foundation for questions: scenario where multiple parent (base) contracts are inherited:

```<code>contract Base1 {
    // do something
    uint256[1000] private __gap;
}

contract Base2 {
    // do something
    uint256[1000] private __gap;
}

contract Child is Base1, Base2 {
    uint256 testVariable = 123;
}
</code>```

Questions:

If a large storage gap is left, you could theoretically replace Base2 with two new contracts (ex: Base2A and Base2B), so long as the storage used, including gaps, for both sums to the total gap left by the original Base2, right?

On implementation upgrades, since storage variables from previous implementations can't be removed, but byte code can nevertheless be reduced (ex: nuking Base2's code), each proxy upgrade is still ultimately constrained by the max contract size. To be clear, the available bytecode space would be 24576 bytes - contract_to_replace_size. Given that the legacy storage variables from Base2 are still taking up storage slots, they would eat into the available bytecode space for implementation upgrades, correct? In other words, even if, like in #1, large gaps were left, you cant continue replacing parent contracts forever, because each replacement leaves behind non-removable storage variables that eats into contract size?

Trying to better understand the constraints on optionality.

Body:
Foundation for questions: scenario where multiple parent (base) contracts are inherited:

contract Base1 {
    // do something
    uint256[1000] private __gap;
}

contract Base2 {
    // do something
    uint256[1000] private __gap;
}

contract Child is Base1, Base2 {
    uint256 testVariable = 123;
}

Questions:

If a large storage gap is left, you could theoretically replace Base2 with two new contracts (ex: Base2A and Base2B), so long as the storage used, including gaps, for both sums to the total gap left by the original Base2, right?

On implementation upgrades, since storage variables from previous implementations can't be removed, but byte code can nevertheless be reduced (ex: nuking Base2's code), each proxy upgrade is still ultimately constrained by the max contract size. To be clear, the available bytecode space would be 24576 bytes - contract_to_replace_size. Given that the legacy storage variables from Base2 are still taking up storage slots, they would eat into the available bytecode space for implementation upgrades, correct? In other words, even if, like in #1, large gaps were left, you cant continue replacing parent contracts forever, because each replacement leaves behind non-removable storage variables that eats into contract size?

Trying to better understand the constraints on optionality.


问:
Using sparklyr and geospark in R, convert Spark DataFrame to Spark Spatial DataFrame (for point to line distance calculation)
I have a Spark DataFrame with latitude and longitude where I'm trying to calculate the distance between the coordinates and a polyline.

The dataframe I'm working with is large (about 10 billion observations) and I load using spark_read_parquet(), so it's originally loaded as a Spark dataframe. I'm wondering how to convert that to a Spark Spatial dataframe so then--using geospark--I can use sf methods to calculate the distance from the points to the line.

(Or the ultimate goal is to calculate the distance between the lat/lon in the Spark dataframe to one other polyline, so if there's another way to go about this then that works too).

The below code sets up an example with dummy data

## Setup
library(dplyr)
library(sparklyr)
library(geospark)

sc <- spark_connect(master="local")
register_gis(sc)

## Make dummy dataframe data
df <- data.frame(uid = 1:10,
                 latitude = 1:10,
                 longitude = 1:10)

s_df <- sdf_copy_to(sc = sc, x = df, overwrite = T)

## Make dummy polyline data
polyl <- rbind(c(0,3),c(0,4),c(1,5),c(2,5)) %>% st_linestring()
polyl_sf <- data.frame(id = 1, geom = st_sfc(polyl)) %>% st_as_sf(crs = 4326)
```
<p>The below code converts from a datafrasme to a spatial dataframe (sf object)</p>
<pre class="lang-r prettyprint-override"><code>## Convert from dataframe to spatial dataframe
df %>%
  st_as_sf(coords = c("longitude", "latitude"),
           crs = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
</code>```

But the below code returns the below error

## Attempt to convert from Spark dataframe to Spark spatial dataframe
s_df %>%
  st_as_sf(coords = c("longitude", "latitude"),
           crs = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
```
```Error in UseMethod("st_as_sf") :
  no applicable method for 'st_as_sf' applied to an object of class "c('tbl_spark', 'tbl_sql', 'tbl_lazy', 'tbl')"
```

Or not sure if this should somehow be done using st_point?

Body:
I have a Spark DataFrame with latitude and longitude where I'm trying to calculate the distance between the coordinates and a polyline.

The dataframe I'm working with is large (about 10 billion observations) and I load using spark_read_parquet(), so it's originally loaded as a Spark dataframe. I'm wondering how to convert that to a Spark Spatial dataframe so then--using geospark--I can use sf methods to calculate the distance from the points to the line.

(Or the ultimate goal is to calculate the distance between the lat/lon in the Spark dataframe to one other polyline, so if there's another way to go about this then that works too).

The below code sets up an example with dummy data

## Setup
library(dplyr)
library(sparklyr)
library(geospark)

sc <- spark_connect(master="local")
register_gis(sc)

## Make dummy dataframe data
df <- data.frame(uid = 1:10,
                 latitude = 1:10,
                 longitude = 1:10)

s_df <- sdf_copy_to(sc = sc, x = df, overwrite = T)

## Make dummy polyline data
polyl <- rbind(c(0,3),c(0,4),c(1,5),c(2,5)) %>% st_linestring()
polyl_sf <- data.frame(id = 1, geom = st_sfc(polyl)) %>% st_as_sf(crs = 4326)

The below code converts from a datafrasme to a spatial dataframe (sf object)

## Convert from dataframe to spatial dataframe
df %>%
  st_as_sf(coords = c("longitude", "latitude"),
           crs = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")

But the below code returns the below error

## Attempt to convert from Spark dataframe to Spark spatial dataframe
s_df %>%
  st_as_sf(coords = c("longitude", "latitude"),
           crs = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")

Error in UseMethod("st_as_sf") :
  no applicable method for 'st_as_sf' applied to an object of class "c('tbl_spark', 'tbl_sql', 'tbl_lazy', 'tbl')"

Or not sure if this should somehow be done using st_point?


问:
MaziDazi1 with checkout try
Is there anything you guys would do better than this?
its supposed to be very basic checkout.

Main

```<code>SnimaciPokladniSystem pokladna1 = new Pokladna("Mazanek Pardubice", 12);

Polozka polozky[] = {
    new Polozka("McRoyal",1234567, 50.0),
    new Polozka("Velké hranolky",1357901, 45.0),
    new Polozka("Sladkokyselá omáčka",1111111, 15.0),
    new Polozka("Vinea nápoj",1924873, 30.0),
    new Polozka("Sladkokyselá omáčka",1111111, 15.0),
    new Polozka("Krokety",1254457,50.0)
    };
    for (int i = 0; i < (polozky.length); i++) {
            pokladna1.vlozPolozku(polozky[i]);
        }
    System.out.println("Tato polozka se vyskytuje " + pokladna1.pocetPolozekSCarovymKodem(1111111) + "krat");

    pokladna1.NovyNakup();
    for (int i = 0; i < (polozky.length-2); i++) {
            pokladna1.vlozPolozku(polozky[i]);
        }
    pokladna1.ulozUctenku("vystup.txt");
</code>```

item

```<code>public class Polozka {
    private String nazev;
    private long carovyKod;
    private double cena;

    public Polozka(String nazev, long carovyKod, double cena) {
        this.nazev = nazev;
        this.carovyKod = carovyKod;
        this.cena = cena;
    }
</code>```

checkout

```<code>import java.io.PrintWriter;

public class Pokladna implements SnimaciPokladniSystem{
    private String nazevPodniku;
    private Polozka[] nakup;
    private final int velikostPokladny;
    private int pocetPolozek;

    public Pokladna(String nazevPodniku,int velikostPokladny ) {
        this.nazevPodniku = nazevPodniku;
        this.velikostPokladny = velikostPokladny;
        this.nakup = new Polozka[velikostPokladny];
        this.pocetPolozek = 0;
    }

    @Override
    public boolean vlozPolozku(Polozka polozkaNakupu) {
        for (int i = 0; i<pocetPolozek; i++){
            if (pocetPolozek == nakup.length){
            return false;
            }
        }
        nakup[pocetPolozek] = polozkaNakupu;
        pocetPolozek++;
        return true;
    }

    @Override
    public void NovyNakup() {
        nakup = new Polozka[velikostPokladny];
        pocetPolozek = 0;
        System.out.println("Pamet vymazana!");
    }

    @Override
    public int pocetPolozekSCarovymKodem(long carovyKod) {
         int pocet = 0;
         for (int i = 0; i<pocetPolozek; i++){
            if (nakup[i].getCarovyKod() == carovyKod){
            pocet++;
            }
        }
         return pocet;
    }

    @Override
    public void ulozUctenku(String cestaKSouboru) {
        try (PrintWriter zapis = new PrintWriter(cestaKSouboru)) {
            zapis.println(nazevPodniku);
            for (int i = 0; i <pocetPolozek; i++){
                zapis.println(nakup[i].getNazev() +"\t"+ nakup[i].getCarovyKod() +"\t"+ nakup[i].getCena());
            }
            zapis.close();
        } catch (Exception e){
            System.err.println("Chyba se souborem!");
        }
    }
</code>```

Interface

```<code>public interface SnimaciPokladniSystem{
    boolean vlozPolozku(Polozka polozkaNakupu);

    void NovyNakup();

    int pocetPolozekSCarovymKodem(long carovyKod);

    void ulozUctenku(String cestaKSouboru);
}
</code>```

this is basicly the the whole program and is working correctly. I just want to see any points for potential upgrade. If theres anything really bad dont worry and speak out. It would be really helpful. mainly the checkout part and the main part.

Main

```<code>SnimaciPokladniSystem pokladna1 = new Pokladna("Mazanek Pardubice", 12);

Polozka polozky[] = {
    new Polozka("McRoyal",1234567, 50.0),
    new Polozka("Velké hranolky",1357901, 45.0),
    new Polozka("Sladkokyselá omáčka",1111111, 15.0),
    new Polozka("Vinea nápoj",1924873, 30.0),
    new Polozka("Sladkokyselá omáčka",1111111, 15.0),
    new Polozka("Krokety",1254457,50.0)
    };
    for (int i = 0; i < (polozky.length); i++) {
            pokladna1.vlozPolozku(polozky[i]);
        }
    System.out.println("Tato polozka se vyskytuje " + pokladna1.pocetPolozekSCarovymKodem(1111111) + "krat");

    pokladna1.NovyNakup();
    for (int i = 0; i < (polozky.length-2); i++) {
            pokladna1.vlozPolozku(polozky[i]);
        }
    pokladna1.ulozUctenku("vystup.txt");
</code>```

checkout

```<code>import java.io.PrintWriter;

public class Pokladna implements SnimaciPokladniSystem{
    private String nazevPodniku;
    private Polozka[] nakup;
    private final int velikostPokladny;
    private int pocetPolozek;

    public Pokladna(String nazevPodniku,int velikostPokladny ) {
        this.nazevPodniku = nazevPodniku;
        this.velikostPokladny = velikostPokladny;
        this.nakup = new Polozka[velikostPokladny];
        this.pocetPolozek = 0;
    }

    @Override
    public boolean vlozPolozku(Polozka polozkaNakupu) {
        for (int i = 0; i<pocetPolozek; i++){
            if (pocetPolozek == nakup.length){
            return false;
            }
        }
        nakup[pocetPolozek] = polozkaNakupu;
        pocetPolozek++;
        return true;
    }

    @Override
    public void NovyNakup() {
        nakup = new Polozka[velikostPokladny];
        pocetPolozek = 0;
        System.out.println("Pamet vymazana!");
    }

    @Override
    public int pocetPolozekSCarovymKodem(long carovyKod) {
         int pocet = 0;
         for (int i = 0; i<pocetPolozek; i++){
            if (nakup[i].getCarovyKod() == carovyKod){
            pocet++;
            }
        }
         return pocet;
    }

    @Override
    public void ulozUctenku(String cestaKSouboru) {
        try (PrintWriter zapis = new PrintWriter(cestaKSouboru)) {
            zapis.println(nazevPodniku);
            for (int i = 0; i <pocetPolozek; i++){
                zapis.println(nakup[i].getNazev() +"\t"+ nakup[i].getCarovyKod() +"\t"+ nakup[i].getCena());
            }
            zapis.close();
        } catch (Exception e){
            System.err.println("Chyba se souborem!");
        }
    }
</code>```

Title: MaziDazi1 with checkout try

Body:
Is there anything you guys would do better than this?
its supposed to be very basic checkout.

Main

SnimaciPokladniSystem pokladna1 = new Pokladna("Mazanek Pardubice", 12);

Polozka polozky[] = {
    new Polozka("McRoyal",1234567, 50.0),
    new Polozka("Velké hranolky",1357901, 45.0),
    new Polozka("Sladkokyselá omáčka",1111111, 15.0),
    new Polozka("Vinea nápoj",1924873, 30.0),
    new Polozka("Sladkokyselá omáčka",1111111, 15.0),
    new Polozka("Krokety",1254457,50.0)
    };
    for (int i = 0; i < (polozky.length); i++) {
            pokladna1.vlozPolozku(polozky[i]);
        }
    System.out.println("Tato polozka se vyskytuje " + pokladna1.pocetPolozekSCarovymKodem(1111111) + "krat");

    pokladna1.NovyNakup();
    for (int i = 0; i < (polozky.length-2); i++) {
            pokladna1.vlozPolozku(polozky[i]);
        }
    pokladna1.ulozUctenku("vystup.txt");

item

public class Polozka {
    private String nazev;
    private long carovyKod;
    private double cena;

    public Polozka(String nazev, long carovyKod, double cena) {
        this.nazev = nazev;
        this.carovyKod = carovyKod;
        this.cena = cena;
    }

checkout

import java.io.PrintWriter;

public class Pokladna implements SnimaciPokladniSystem{
    private String nazevPodniku;
    private Polozka[] nakup;
    private final int velikostPokladny;
    private int pocetPolozek;

    public Pokladna(String nazevPodniku,int velikostPokladny ) {
        this.nazevPodniku = nazevPodniku;
        this.velikostPokladny = velikostPokladny;
        this.nakup = new Polozka[velikostPokladny];
        this.pocetPolozek = 0;
    }

    @Override
    public boolean vlozPolozku(Polozka polozkaNakupu) {
        for (int i = 0; i<pocetPolozek; i++){
            if (pocetPolozek == nakup.length){
            return false;
            }
        }
        nakup[pocetPolozek] = polozkaNakupu;
        pocetPolozek++;
        return true;
    }

    @Override
    public void NovyNakup() {
        nakup = new Polozka[velikostPokladny];
        pocetPolozek = 0;
        System.out.println("Pamet vymazana!");
    }

    @Override
    public int pocetPolozekSCarovymKodem(long carovyKod) {
         int pocet = 0;
         for (int i = 0; i<pocetPolozek; i++){
            if (nakup[i].getCarovyKod() == carovyKod){
            pocet++;
            }
        }
         return pocet;
    }

    @Override
    public void ulozUctenku(String cestaKSouboru) {
        try (PrintWriter zapis = new PrintWriter(cestaKSouboru)) {
            zapis.println(nazevPodniku);
            for (int i = 0; i <pocetPolozek; i++){
                zapis.println(nakup[i].getNazev() +"\t"+ nakup[i].getCarovyKod() +"\t"+ nakup[i].getCena());
            }
            zapis.close();
        } catch (Exception e){
            System.err.println("Chyba se souborem!");
        }
    }

Interface

public interface SnimaciPokladniSystem{
    boolean vlozPolozku(Polozka polozkaNakupu);

    void NovyNakup();

    int pocetPolozekSCarovymKodem(long carovyKod);

    void ulozUctenku(String cestaKSouboru);
}

this is basicly the the whole program and is working correctly. I just want to see any points for potential upgrade. If theres anything really bad dont worry and speak out. It would be really helpful. mainly the checkout part and the main part.

Main

SnimaciPokladniSystem pokladna1 = new Pokladna("Mazanek Pardubice", 12);

Polozka polozky[] = {
    new Polozka("McRoyal",1234567, 50.0),
    new Polozka("Velké hranolky",1357901, 45.0),
    new Polozka("Sladkokyselá omáčka",1111111, 15.0),
    new Polozka("Vinea nápoj",1924873, 30.0),
    new Polozka("Sladkokyselá omáčka",1111111, 15.0),
    new Polozka("Krokety",1254457,50.0)
    };
    for (int i = 0; i < (polozky.length); i++) {
            pokladna1.vlozPolozku(polozky[i]);
        }
    System.out.println("Tato polozka se vyskytuje " + pokladna1.pocetPolozekSCarovymKodem(1111111) + "krat");

    pokladna1.NovyNakup();
    for (int i = 0; i < (polozky.length-2); i++) {
            pokladna1.vlozPolozku(polozky[i]);
        }
    pokladna1.ulozUctenku("vystup.txt");

checkout

import java.io.PrintWriter;

public class Pokladna implements SnimaciPokladniSystem{
    private String nazevPodniku;
    private Polozka[] nakup;
    private final int velikostPokladny;
    private int pocetPolozek;

    public Pokladna(String nazevPodniku,int velikostPokladny ) {
        this.nazevPodniku = nazevPodniku;
        this.velikostPokladny = velikostPokladny;
        this.nakup = new Polozka[velikostPokladny];
        this.pocetPolozek = 0;
    }

    @Override
    public boolean vlozPolozku(Polozka polozkaNakupu) {
        for (int i = 0; i<pocetPolozek; i++){
            if (pocetPolozek == nakup.length){
            return false;
            }
        }
        nakup[pocetPolozek] = polozkaNakupu;
        pocetPolozek++;
        return true;
    }

    @Override
    public void NovyNakup() {
        nakup = new Polozka[velikostPokladny];
        pocetPolozek = 0;
        System.out.println("Pamet vymazana!");
    }

    @Override
    public int pocetPolozekSCarovymKodem(long carovyKod) {
         int pocet = 0;
         for (int i = 0; i<pocetPolozek; i++){
            if (nakup[i].getCarovyKod() == carovyKod){
            pocet++;
            }
        }
         return pocet;
    }

    @Override
    public void ulozUctenku(String cestaKSouboru) {
        try (PrintWriter zapis = new PrintWriter(cestaKSouboru)) {
            zapis.println(nazevPodniku);
            for (int i = 0; i <pocetPolozek; i++){
                zapis.println(nakup[i].getNazev() +"\t"+ nakup[i].getCarovyKod() +"\t"+ nakup[i].getCena());
            }
            zapis.close();
        } catch (Exception e){
            System.err.println("Chyba se souborem!");
        }
    }


问:
Can I use C++ to access a firebase written in react nativr
I’m just wondering, is all firebase code universal? For example If I code a firebase script in C++ can I use the same C++ code to access a database written in react native?</p>


问:
bottomNavigationBar not saving dark mode status
I am almost beginner, i have a project where I want to add the ability of changing appearance of Application.
i use BottomNavigationView where my App has 3 Activities (Home, Video and Setting)
in setting Activity, i added an ImageBotton which open a dialogue where user can choose mode of the app from RadioGroup.
The problem is After closing the App from background. And reopen it the application turn back in default mode even dark mode selected before closing the App. But when user click on setting Activity, the app mode change to dark.
Can anyone help me
I link the project here.

https://github.com/forotan1/dark_mode

I tried to use darkModehleper but it didnt help


问:
Is it possible to mix positional arguments with subcommands in oclif or other cli frameworks?
I'm using oclif and am generally very happy with the facility and the folder=(sub)command structure of it. I'm struggling to find in the docs though how it is possible to do the following:

```<code>./mycli command <arg> subcommand1 subcommand2 --flag --flag
</code>```

Such that both subcommand1 and 2 are aware of <arg>.

Body:
I'm using oclif and am generally very happy with the facility and the folder=(sub)command structure of it. I'm struggling to find in the docs though how it is possible to do the following:

./mycli command <arg> subcommand1 subcommand2 --flag --flag

Such that both subcommand1 and 2 are aware of <arg>.


问:
How to save the client requests, which got failed, to database in spring boot?
Background
I am working on a service which accepts the request from client(s), process it and make call(s) to different downstream services using RestTemplate to fetch some data, and then use those responses to frame my service response to return to the client.
Client's requests can be sync(REST API) or async(consumed from queue/messaging system, say, Kafka).
My service is a spring boot app. Database used is Azure cosmosdb.

Problem Statement and Question
I need to save every incoming request (whether it is sync or async) to Database (collection name- payloads) with its completion status (success or failed).
Along with this, I also need to save the request to "retry" collection if it gets failed when calling downstream services.
For example - I received a request from client, and I make a call to a downstream service, and it resulted in timeout. So I want this request to be saved in "payloads" collection with status as failed, and also want to store in "retry" collection so that I can retry it at later point of time once that downstream is up and running.

The question is -
Since the request failure can happen at any point during the whole execution, How can I write the code to save these into DB at a single place, so that irrespective of where the failure occurred, save to DB is executed, and I do not have to call save to DB manually at each possible failure point.
Please see below sample code.

```<code>public class MyController { // to process clients request synchronously

    @PostMapping("/v1")
    public ResponseEntity\<ResponseDTO\> do(@RequestBody RequestDTO requestDTO) {
        myService.do(requestDTO);
        return new ResponseEntity\<\>(response, HttpStatus.OK);
    }
}

public class MyKafkaConsumer { // process clients request asynchronously

    public void consume(RequestDTO requestDTO) {
        myService.do(requestDTO);
    }
}

public class MyService { // actual business logic class

    public void do(RequestDTO requestDTO) {
        Data data1 = downstream1Client.getData();
        helperClass.doSomething();
    }
}

public class HelperClass {

    public void doSomething() {
        Data data = downstream2Client.getData();
    }
}

public class Downstream1Client {

    public Data getData() {
        // rest template call
        if 5xx response, save failed req to DB
    }
}

public class Downstream2Client {

    public Data getData() {
        // rest template call
        if 5xx response, save failed req to DB
    }
}
</code>```

Checked multiple posts; and Filter, Interceptor, etc might work for HTTP Controller requests, but how can I do this for async request consumed from kafka.

Body:
Background
I am working on a service which accepts the request from client(s), process it and make call(s) to different downstream services using RestTemplate to fetch some data, and then use those responses to frame my service response to return to the client.
Client's requests can be sync(REST API) or async(consumed from queue/messaging system, say, Kafka).
My service is a spring boot app. Database used is Azure cosmosdb.

Problem Statement and Question
I need to save every incoming request (whether it is sync or async) to Database (collection name- payloads) with its completion status (success or failed).
Along with this, I also need to save the request to "retry" collection if it gets failed when calling downstream services.
For example - I received a request from client, and I make a call to a downstream service, and it resulted in timeout. So I want this request to be saved in "payloads" collection with status as failed, and also want to store in "retry" collection so that I can retry it at later point of time once that downstream is up and running.

The question is -
Since the request failure can happen at any point during the whole execution, How can I write the code to save these into DB at a single place, so that irrespective of where the failure occurred, save to DB is executed, and I do not have to call save to DB manually at each possible failure point.
Please see below sample code.

public class MyController { // to process clients request synchronously

    @PostMapping("/v1")
    public ResponseEntity\<ResponseDTO\> do(@RequestBody RequestDTO requestDTO) {
        myService.do(requestDTO);
        return new ResponseEntity\<\>(response, HttpStatus.OK);
    }
}

public class MyKafkaConsumer { // process clients request asynchronously

    public void consume(RequestDTO requestDTO) {
        myService.do(requestDTO);
    }
}

public class MyService { // actual business logic class

    public void do(RequestDTO requestDTO) {
        Data data1 = downstream1Client.getData();
        helperClass.doSomething();
    }
}

public class HelperClass {

    public void doSomething() {
        Data data = downstream2Client.getData();
    }
}

public class Downstream1Client {

    public Data getData() {
        // rest template call
        if 5xx response, save failed req to DB
    }
}

public class Downstream2Client {

    public Data getData() {
        // rest template call
        if 5xx response, save failed req to DB
    }
}

Checked multiple posts; and Filter, Interceptor, etc might work for HTTP Controller requests, but how can I do this for async request consumed from kafka.


问:
Using the same action several times with different parameters with Redux
I have a problem with actions in React-Redux.
I'm trying to create a virtual store and I want to create a showcase containing a list of all products, and two more separated by brand, so I created an action with the "mark" parameter in the action.

```<code>export const getProductsByMark = mark => async dispatch => {
  try {
    dispatch({type: actionTypes.GET_PRODUCTSBYMARK_REQUEST})

    const {data} = await Api.getRequest(`/api/products/mark/${mark}`)
    dispatch({
      type: actionTypes.GET_PRODUCTSBYMARK_SUCCESS,
      payload: JSON.parse(data),
    })
  } catch (error) {
    dispatch({
      type: actionTypes.GET_PRODUCTSBYMARK_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    })
  }
}
</code>```

But when I call the action on my home page multiple times, with different parameters, the element is repeated several times with the last request I passed

```<code>export const SetNikeProducts = () => {
  const nikeDispatch = useDispatch()
  const getProductsMark = useSelector(state => state.getProductsByMark)
  const { products: productsNike, loading: loadingNike, error: erroNike } = getProductsMark;

  useEffect(() => {
    nikeDispatch(listProductsMark('Nike'))
  }, [])

  return (
  productsNike.length != 0 || productsNike != undefined ?
    <div>
      <br></br>
      <h2 className="homescreen__title">Nike</h2>
      <div className="homescreen__products">
        {loadingNike ? (
          <h2>Loading...</h2>
        ) : erroNike ? (
          <h2>{erroNike}</h2>
        ) : (
          productsNike.map(product => (
            <Product
              key={product._id}
              name={product.name}
              description={product.description}
              mark={product.mark}
              price={product.price}
              discount={product.discount}
              imageUrl={product.imageUrl}
              productId={product._id}
            />
          ))
        )}
      </div>
    </div>

    :
    <div>Deu ruim</div>
  )
}
</code>```

Exemplo:

SetNikeProducts
SetFilaProducts
SetAdidasProducts

Vitrine:

*Adidas Products
*Adidas Products
*Adidas Products

I tried to change the name of the dispatch multiple times but without success, I wanted to split the tags using the same controller function, to avoid having to create a controller for each tag.

Body:
I have a problem with actions in React-Redux.
I'm trying to create a virtual store and I want to create a showcase containing a list of all products, and two more separated by brand, so I created an action with the "mark" parameter in the action.

export const getProductsByMark = mark => async dispatch => {
  try {
    dispatch({type: actionTypes.GET_PRODUCTSBYMARK_REQUEST})

    const {data} = await Api.getRequest(`/api/products/mark/${mark}`)
    dispatch({
      type: actionTypes.GET_PRODUCTSBYMARK_SUCCESS,
      payload: JSON.parse(data),
    })
  } catch (error) {
    dispatch({
      type: actionTypes.GET_PRODUCTSBYMARK_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    })
  }
}

But when I call the action on my home page multiple times, with different parameters, the element is repeated several times with the last request I passed

export const SetNikeProducts = () => {
  const nikeDispatch = useDispatch()
  const getProductsMark = useSelector(state => state.getProductsByMark)
  const { products: productsNike, loading: loadingNike, error: erroNike } = getProductsMark;

  useEffect(() => {
    nikeDispatch(listProductsMark('Nike'))
  }, [])

  return (
  productsNike.length != 0 || productsNike != undefined ?

Nike

        {loadingNike ? (

Loading...

        ) : erroNike ? (

{erroNike}

        ) : (
          productsNike.map(product => (
            <Product
              key={product._id}
              name={product.name}
              description={product.description}
              mark={product.mark}
              price={product.price}
              discount={product.discount}
              imageUrl={product.imageUrl}
              productId={product._id}
            />
          ))
        )}

    :

Deu ruim

  )
}

Exemplo:

SetNikeProducts
SetFilaProducts
SetAdidasProducts

Vitrine:

*Adidas Products
*Adidas Products
*Adidas Products

I tried to change the name of the dispatch multiple times but without success, I wanted to split the tags using the same controller function, to avoid having to create a controller for each tag.


问:
Singular matrix error when attempting to cross validate volatility model on python
I am performing cross validation on python and am running into the "singular matrix" erorr.

The part of code that i run into the error is pasted below. Can someone assist with explaining where i am going wrong?

```<code>#%% Running cross validation

vol_dist_spec_cv_l = list()

for vol_label, vol_model in zip(vol_labels_l, vol_spec_l): # Loop for volitility model
    for err_label, dist in zip(errdist_labels_l, errdist_l): # Loop for error distribution model
        exo_spec_cv_l = list()
        for exo_label, exo_model in zip(exo_labels_l, exo_spec_l): # Loop for exogenous variabales
            cv_all_l = list()
            for split in split_df:
                model_name=exo_label+' ['+vol_label+', '+err_label+']'
                df_cv = pd.concat(split)
                df_cv = df_cv.droplevel(0)
                dg_cv = DistGARCH(depvar_str='FX log returns', # Name of dep var
                                data=df_cv, # Dataframe to work on
                                level_str='FX level', # Name of level dep var for descriptive plot
                                exog_l=exo_model,
                                lags_l=lag_ar,
                                vol_model= vol_model,
                                dist_family=dist)

                # Get the separation point between training and testing set
                last_obs_mod_cv = min(split['test'].index)
                # Set the separation point as last observation [excl.]
                dg_os_fit = dg_cv.fit(last_obs = last_obs_mod_cv)

                # Fit from the seperation point
                predict_os_df = dg_os_fit.forecast(last_obs_mod_cv, horizon=1).dfor

                # Cross validation conditional mean: RMSE and MAE
                mean_os_df = predict_os_df[['true_val', 'cond_mean']].copy()
                mean_os_df['mean_forecast']  = mean_os_df['cond_mean'].shift(1)
                mean_os_df['mean_resid'] = mean_os_df['true_val'] - mean_os_df['mean_forecast']
                mean_os_rmse_score = rmse_cal(mean_os_df['mean_resid'])
                mean_os_mae_score = mae_cal(mean_os_df['mean_resid'])
                cv_df = pd.DataFrame(columns=[model_name])
                cv_df.loc['Cross Validation Out-sample RMSE (COND MEAN)'] = mean_os_rmse_score
                cv_df.loc['Cross Validation Out-sample MAE (COND MEAN)'] = mean_os_mae_score

                # Cross validation conditional density: MIS
                mis_os_df =  predict_os_df.copy()
                mis_os_df['is'] = (mis_os_df['cond_quant_0.975']-mis_os_df['cond_quant_0.025'])+(2/(1-0.95))*(mis_os_df['cond_quant_0.025']-mis_os_df['true_val'])*(mis_os_df['true_val']<mis_os_df['cond_quant_0.025'])+(2/(1-0.95))*(mis_os_df['true_val']-mis_os_df['cond_quant_0.975'])*(mis_os_df['true_val']>mis_os_df['cond_quant_0.975'])
                mis_os_score = np.nanmean(mis_os_df['is'])
                cv_df.loc['Cross Validation Out-sample MIS'] = mis_os_score

                # Cross validation conditional density: KS test
                ks_stats_os = stats.kstest(predict_os_df['pit'].dropna(), 'uniform').statistic
                ks_pval_os = stats.kstest(predict_os_df['pit'].dropna(), 'uniform').pvalue
                cv_df.loc['Cross Validation Out-sample KS stat'] = ks_stats_os
                cv_df.loc['Cross Validation Out-sample KS pvalue'] = ks_pval_os
                cv_df.loc['Cross Validation Out-sample KS Pass Pct'] = 1 if ks_pval_os>0.05 else 0

                cv_all_l.append(cv_df)

            # Merge all summary table
            cv_all_df = pd.concat(cv_all_l, axis=1)
            cv_avg_single_df = pd.DataFrame(cv_all_df.mean(axis=1))
            cv_avg_single_df.columns=[model_name]
            exo_spec_cv_l.append(cv_avg_single_df)
        exo_spec_cv_df = pd.concat(exo_spec_cv_l, axis=1)
        vol_dist_spec_cv_l.append(exo_spec_cv_df)

all_comb_cv_t = pd.concat(vol_dist_spec_cv_l, axis=1)

# Save the table
all_comb_cv_t.to_excel('output/cross_validation_performace_table.xlsx')

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

Cross validating a volatility model and was expecting cross validation table results.

Body:
I am performing cross validation on python and am running into the "singular matrix" erorr.

The part of code that i run into the error is pasted below. Can someone assist with explaining where i am going wrong?

#%% Running cross validation

vol_dist_spec_cv_l = list()

for vol_label, vol_model in zip(vol_labels_l, vol_spec_l): # Loop for volitility model
    for err_label, dist in zip(errdist_labels_l, errdist_l): # Loop for error distribution model
        exo_spec_cv_l = list()
        for exo_label, exo_model in zip(exo_labels_l, exo_spec_l): # Loop for exogenous variabales
            cv_all_l = list()
            for split in split_df:
                model_name=exo_label+' ['+vol_label+', '+err_label+']'
                df_cv = pd.concat(split)
                df_cv = df_cv.droplevel(0)
                dg_cv = DistGARCH(depvar_str='FX log returns', # Name of dep var
                                data=df_cv, # Dataframe to work on
                                level_str='FX level', # Name of level dep var for descriptive plot
                                exog_l=exo_model,
                                lags_l=lag_ar,
                                vol_model= vol_model,
                                dist_family=dist)

                # Get the separation point between training and testing set
                last_obs_mod_cv = min(split['test'].index)
                # Set the separation point as last observation [excl.]
                dg_os_fit = dg_cv.fit(last_obs = last_obs_mod_cv)

                # Fit from the seperation point
                predict_os_df = dg_os_fit.forecast(last_obs_mod_cv, horizon=1).dfor

                # Cross validation conditional mean: RMSE and MAE
                mean_os_df = predict_os_df[['true_val', 'cond_mean']].copy()
                mean_os_df['mean_forecast']  = mean_os_df['cond_mean'].shift(1)
                mean_os_df['mean_resid'] = mean_os_df['true_val'] - mean_os_df['mean_forecast']
                mean_os_rmse_score = rmse_cal(mean_os_df['mean_resid'])
                mean_os_mae_score = mae_cal(mean_os_df['mean_resid'])
                cv_df = pd.DataFrame(columns=[model_name])
                cv_df.loc['Cross Validation Out-sample RMSE (COND MEAN)'] = mean_os_rmse_score
                cv_df.loc['Cross Validation Out-sample MAE (COND MEAN)'] = mean_os_mae_score

                # Cross validation conditional density: MIS
                mis_os_df =  predict_os_df.copy()
                mis_os_df['is'] = (mis_os_df['cond_quant_0.975']-mis_os_df['cond_quant_0.025'])+(2/(1-0.95))*(mis_os_df['cond_quant_0.025']-mis_os_df['true_val'])*(mis_os_df['true_val']<mis_os_df['cond_quant_0.025'])+(2/(1-0.95))*(mis_os_df['true_val']-mis_os_df['cond_quant_0.975'])*(mis_os_df['true_val']>mis_os_df['cond_quant_0.975'])
                mis_os_score = np.nanmean(mis_os_df['is'])
                cv_df.loc['Cross Validation Out-sample MIS'] = mis_os_score

                # Cross validation conditional density: KS test
                ks_stats_os = stats.kstest(predict_os_df['pit'].dropna(), 'uniform').statistic
                ks_pval_os = stats.kstest(predict_os_df['pit'].dropna(), 'uniform').pvalue
                cv_df.loc['Cross Validation Out-sample KS stat'] = ks_stats_os
                cv_df.loc['Cross Validation Out-sample KS pvalue'] = ks_pval_os
                cv_df.loc['Cross Validation Out-sample KS Pass Pct'] = 1 if ks_pval_os>0.05 else 0

                cv_all_l.append(cv_df)

            # Merge all summary table
            cv_all_df = pd.concat(cv_all_l, axis=1)
            cv_avg_single_df = pd.DataFrame(cv_all_df.mean(axis=1))
            cv_avg_single_df.columns=[model_name]
            exo_spec_cv_l.append(cv_avg_single_df)
        exo_spec_cv_df = pd.concat(exo_spec_cv_l, axis=1)
        vol_dist_spec_cv_l.append(exo_spec_cv_df)

all_comb_cv_t = pd.concat(vol_dist_spec_cv_l, axis=1)

# Save the table
all_comb_cv_t.to_excel('output/cross_validation_performace_table.xlsx')

###############################################################################

Cross validating a volatility model and was expecting cross validation table results.


问:
Assignment incompatibility error from Pylance
Pylance is giving this error message:

Argument of type "tuple[Literal[1], Literal[3]]" cannot be assigned to parameter "__s" of type "slice" in function "__setitem__"
  "tuple[Literal[1], Literal[3]]" is incompatible with "slice"
```
```from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(
    n_samples=20, n_features=10
)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.33, random_state=42
)

X_train[1, 3] = 3
```

Any idea why?

Body:
Pylance is giving this error message:

Argument of type "tuple[Literal[1], Literal[3]]" cannot be assigned to parameter "__s" of type "slice" in function "__setitem__"
  "tuple[Literal[1], Literal[3]]" is incompatible with "slice"

from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(
    n_samples=20, n_features=10
)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.33, random_state=42
)

X_train[1, 3] = 3

Any idea why?


问:
EF Core 7 Inheritance - mapping abstract fields
I have a following hierarchy I'd like to map:

public abstract class Investment
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public class Stock : Investment
{
    public virtual ICollection<Dividend> Dividends { get; set; }
}

public class Bond : Investment
{
   public virtual ICollection<Coupon> Coupons { get; set; }
}

public abstract class InvestmentYield
{
    public int Id { get; set; }

    public decimal Amount { get; set; }

    // This is the tricky part!
    public abstract Investment Investment { get; }
    public abstract int InvestmentId { get; }
}

public partial class Dividend : InvestmentYield
{
    public virtual Stock Stock { get; set; }
    public int StockId { get; set; }

    public override Investment Investment => Stock;
    public override int InvestmentId => StockId;
}

public class Coupon : InvestmentYield
{
    public virtual Bond Bond { get; set; }
    public int BondId { get; set; }

    public override Investment Investment => Bond;
    public override int InvestmentId => BondId;
}
```
<p>and I'd like to make a query to get all InvestmentYields including their investments.
I tried following code:</p>
```_context.Yields.Include(yield => yield.Investment)
```
<p>but it ended up with error</p>
<blockquote>
<p>"The expression 'yield.Investment' is invalid inside an 'Include' operation, since it does not  represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.</p>
</blockquote>
<p>so I followed the advice and added those castings.</p>
<p>I got something like this:</p>
<pre class="lang-cs prettyprint-override"><code>_context.Yields
  .Include(yield => (yield as Dividend).Stock)
  .Include(yield => (yield as Coupon).Bond)
</code>```

which is really ugly, but works. Even WHERE condition can be used as following

  .Where(yield => (yield as Dividend).Stock.Id == investmentId
    || (yield as Interest).SavingsAccount.Id == investmentId
    || (yield as Coupon).Bond.Id == investmentId);
```

But problem is when it comes to using it in GroupBy, Select and other expressions. Another problem would be of course scalability - adding new entities would be pain and break things.

Ideally, I'd like to use TPT or TPC mapping and avoid TPH if possible. And I would like to have tables  Stock, Bond and Dividend with foreign key to Stock, Coupon with foreign key to Bond.

Is this possible in EF.Core 7? I use MySQL as a database, if it makes any difference.

Body:
I have a following hierarchy I'd like to map:

public abstract class Investment
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public class Stock : Investment
{
    public virtual ICollection<Dividend> Dividends { get; set; }
}

public class Bond : Investment
{
   public virtual ICollection<Coupon> Coupons { get; set; }
}

public abstract class InvestmentYield
{
    public int Id { get; set; }

    public decimal Amount { get; set; }

    // This is the tricky part!
    public abstract Investment Investment { get; }
    public abstract int InvestmentId { get; }
}

public partial class Dividend : InvestmentYield
{
    public virtual Stock Stock { get; set; }
    public int StockId { get; set; }

    public override Investment Investment => Stock;
    public override int InvestmentId => StockId;
}

public class Coupon : InvestmentYield
{
    public virtual Bond Bond { get; set; }
    public int BondId { get; set; }

    public override Investment Investment => Bond;
    public override int InvestmentId => BondId;
}

and I'd like to make a query to get all InvestmentYields including their investments.
I tried following code:

_context.Yields.Include(yield => yield.Investment)

but it ended up with error

"The expression 'yield.Investment' is invalid inside an 'Include' operation, since it does not  represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.

so I followed the advice and added those castings.

I got something like this:

_context.Yields
  .Include(yield => (yield as Dividend).Stock)
  .Include(yield => (yield as Coupon).Bond)

which is really ugly, but works. Even WHERE condition can be used as following

  .Where(yield => (yield as Dividend).Stock.Id == investmentId
    || (yield as Interest).SavingsAccount.Id == investmentId
    || (yield as Coupon).Bond.Id == investmentId);

But problem is when it comes to using it in GroupBy, Select and other expressions. Another problem would be of course scalability - adding new entities would be pain and break things.

Ideally, I'd like to use TPT or TPC mapping and avoid TPH if possible. And I would like to have tables  Stock, Bond and Dividend with foreign key to Stock, Coupon with foreign key to Bond.

Is this possible in EF.Core 7? I use MySQL as a database, if it makes any difference.