问:
Spark Scala : Creating Azure Container on the fly with same name as Spark partition Column and dump data into it
Input to Spark Job : csv file
Partition Column Name : OrgId

Output format we need : OrgId\YYYY\MM\DD<csv file>

Using partitionBy(OrgId, year, month, day) we are able to get this but the problem is we are getting all partitions data in a single folder i.e. like below :

partitionedData\OrgId_1\YYYY\MM\DD<csv file>
partitionedData\OrgId_2\YYYY\MM\DD<csv file>

We want to have it like the way below :
{Azure Container OrgId_1}\YYYY\MM\DD<csv file>
{Azure Container OrgId_2}\YYYY\MM\DD<csv file>

We can create a container on the fly, but how to we get the name of the container (eq. to OrgId i.e. parition key value) ?

Since .save(path) method in last only takes 1 output folder destination, hence how we can dynamically pass the container name and make spark job writer efficient to write the specific 1 partition data to 1 container only ?

We tried like below :

```<code>var df = sparkSession
  .read
  .format(outputFormat)
  .csv(inputFilePath: _*) //multiple input csv files
</code>```
```<code>df
.repartition(col(partitionCol))
.write
.mode(SaveMode.Overwrite) //creates a new csv file at partition level
.partitionBy(partitionCol, "year", "month", "day") //slow but folder wise segregation
.format("csv")
.save(outputFilePath)

</code>```

But our objective we are not able to achieve.
It seems like somehow we need to override/hack spark save/write method and ask spark to create container first on the fly as per partition Col value (if it does not exist) and then dump data there and proceed further.

Request for help here !

Body:
Input to Spark Job : csv file
Partition Column Name : OrgId

Output format we need : OrgId\YYYY\MM\DD<csv file>

Using partitionBy(OrgId, year, month, day) we are able to get this but the problem is we are getting all partitions data in a single folder i.e. like below :

partitionedData\OrgId_1\YYYY\MM\DD<csv file>
partitionedData\OrgId_2\YYYY\MM\DD<csv file>

We want to have it like the way below :
{Azure Container OrgId_1}\YYYY\MM\DD<csv file>
{Azure Container OrgId_2}\YYYY\MM\DD<csv file>

We can create a container on the fly, but how to we get the name of the container (eq. to OrgId i.e. parition key value) ?

Since .save(path) method in last only takes 1 output folder destination, hence how we can dynamically pass the container name and make spark job writer efficient to write the specific 1 partition data to 1 container only ?

We tried like below :

var df = sparkSession
  .read
  .format(outputFormat)
  .csv(inputFilePath: _*) //multiple input csv files

df
.repartition(col(partitionCol))
.write
.mode(SaveMode.Overwrite) //creates a new csv file at partition level
.partitionBy(partitionCol, "year", "month", "day") //slow but folder wise segregation
.format("csv")
.save(outputFilePath)

But our objective we are not able to achieve.
It seems like somehow we need to override/hack spark save/write method and ask spark to create container first on the fly as per partition Col value (if it does not exist) and then dump data there and proceed further.

Request for help here !


来源: stackexchange

问:
Installing xarray_spatial - UnsatisfiableError - But there are no incompatible specifications displayed
I am trying to install xarray-spatial using anaconda. I am getting an UnsatisfiableError, but there are no deatils of any incompatible specifications.

Running the following command:

```<code>(geo_env) C:\Users\Alex>conda install -c conda-forge xarray-spatial
</code>```

Here are the details of the error:

```<code>(geo_env) C:\Users\Alex>conda install -c conda-forge xarray-spatial
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: /
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
failed

UnsatisfiableError: The following specifications were found to be incompatible with each other:

Output in format: Requested package -> Available versions
Note that strict channel priority may have removed packages required for satisfiability.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to install xarray-spatial using anaconda. I am getting an UnsatisfiableError, but there are no deatils of any incompatible specifications.

Running the following command:

(geo_env) C:\Users\Alex>conda install -c conda-forge xarray-spatial

Here are the details of the error:

(geo_env) C:\Users\Alex>conda install -c conda-forge xarray-spatial
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: /
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
failed

UnsatisfiableError: The following specifications were found to be incompatible with each other:

Output in format: Requested package -> Available versions
Note that strict channel priority may have removed packages required for satisfiability.


问:
C# timers.timer is not working correctly. it seems to be overlapping
Thanks for your attention.

Here's what my code does:

A method(Using C# WinForm, System.timers.timer) that checks the variables every second, leaves a log, and moves on to the next function if the condition is met.

After working for quite long time(more than 2 weeks), the following symptoms occurred :

overlapping logs left by the timer.

The period of the timer is 1 second, and the operation of the timer is not considered heavy.

here is example of the logs

```<code>[14:06:05]A
[14:06:05]B
[14:06:05]B
[14:06:05]B
[14:06:05]B
[14:06:05]B
... (20 times/sec)
</code>```

I just couldn't figure out why.
I tried running several PGMs simultaneously and applied several timers asynchronously, but the symptoms did not appear.

Ask for advice from teachers. I would like to refer to it for problem solving and study.
Detailed code is below.

This is how I initialized it.

```<code> private static System.Timers.Timer TestEndDetection_Timer_;

 private void SetUp_TestEndDetection_Timer_()
        {

            TestEndDetection_Timer_ = new System.Timers.Timer(1000);

            TestEndDetection_Timer_.Elapsed += TestEndDetection_Timer_Event;
            TestEndDetection_Timer_.AutoReset = true;
            TestEndDetection_Timer_.Enabled = true;
        }
</code>```

I use that 'SetUp_TestEndDetection_Timer_()' only once when PGM start (Form_load())

here is code of TestEndDetection_Timer_Event()

```<code> private void TestEndDetection_Timer_Event(Object source, ElapsedEventArgs e)
        {
            defrostCount++;
            CheckForIllegalCrossThreadCalls = false;

            if (NowTesting && AutoDefrost && checkBox2.Checked)
            {

                TestEndDetectionDealyTimer++;

                if (TestEndDetectionDealyTimer > 180)
                {
                    bool Fix1End = false;
                    bool Fix2End = false;
                    bool Fix3End = false;
                    bool Fix4End = false;
                    bool Fix5End = false;
                    bool Fix6End = false;

                    bool Fix1Done = false;
                    bool Fix2Done = false;
                    bool Fix3Done = false;
                    bool Fix4Done = false;
                    bool Fix5Done = false;
                    bool Fix6Done = false;

                    bool Fix1Power = false;
                    bool Fix2Power = false;
                    bool Fix3Power = false;
                    bool Fix4Power = false;
                    bool Fix5Power = false;
                    bool Fix6Power = false;

                    Fix1Done = File.Exists(@"Z:\result\fix1\hdiag.log");
                    Fix2Done = File.Exists(@"Z:\result\fix2\hdiag.log");
                    Fix3Done = File.Exists(@"Z:\result\fix3\hdiag.log");
                    Fix4Done = File.Exists(@"Z:\result\fix4\hdiag.log");
                    Fix5Done = File.Exists(@"Z:\result\fix5\hdiag.log");
                    Fix6Done = File.Exists(@"Z:\result\fix6\hdiag.log");

                    defrostlogger("TESTDONE: "+Convert.ToInt32(Fix1Done) + "/" + Convert.ToInt32(Fix2Done) + "/" + Convert.ToInt32(Fix3Done) + "/" + Convert.ToInt32(Fix4Done) + "/" + Convert.ToInt32(Fix5Done) + "/" + Convert.ToInt32(Fix6Done));

                    Fix1Power = m_ucFixInfo[1].PowerStat;
                    Fix2Power = m_ucFixInfo[2].PowerStat;
                    Fix3Power = m_ucFixInfo[3].PowerStat;
                    Fix4Power = m_ucFixInfo[4].PowerStat;
                    Fix5Power = m_ucFixInfo[5].PowerStat;
                    Fix6Power = m_ucFixInfo[6].PowerStat;

                    defrostlogger("POWER: "+Convert.ToInt32(Fix1Power) + "/" + Convert.ToInt32(Fix2Power) + "/" + Convert.ToInt32(Fix3Power) + "/" + Convert.ToInt32(Fix4Power) + "/" + Convert.ToInt32(Fix5Power) + "/" + Convert.ToInt32(Fix6Power));

                    if (Fix1Done || !Fix1Power) { Fix1End = true; } else { Fix1End = false; }
                    if (Fix2Done || !Fix2Power) { Fix2End = true; } else { Fix2End = false; }
                    if (Fix3Done || !Fix3Power) { Fix3End = true; } else { Fix3End = false; }
                    if (Fix4Done || !Fix4Power) { Fix4End = true; } else { Fix4End = false; }
                    if (Fix5Done || !Fix5Power) { Fix5End = true; } else { Fix5End = false; }
                    if (Fix6Done || !Fix6Power) { Fix6End = true; } else { Fix6End = false; }

                    if (Fix1End && Fix2End && Fix3End && Fix4End && Fix5End && Fix6End && AutoDefrostRunStat && TestEndCount < 20)
                    {
                        TestEndCount++;
                    }

                    if (TestEndCount > 10)
                    {

                        if (button13.Text == "Door Open" && DefrostAvailable)
                        {
                            defrostlogger("A");
                            RunDefrost();
                            AutoDefrostRunStat = false;
                            NowTesting = false;
                            TestEndCount = 0;
                        }
                        else
                        {
                            defrostlogger("B");
                        }
                    }
                }
            }
            else
            {
                if (defrostCount % 10 == 9&&NowTesting)
                {
                    Load_SV_txt();
                    defrostCount = 0;
                }
            }
        }
</code>```

defrostlogger is :

```<code>private void defrostlogger(string msg)
        {
            using (System.IO.StreamWriter file_ = new System.IO.StreamWriter(Application.StartupPath + @"\Logs\DefrostLog_" + System.DateTime.Now.ToString("MM_dd") + ".txt", true))
            {
                file_.WriteLine("[" + System.DateTime.Now.ToString("HH:mm:ss") + "]" + msg);
            }
        }
</code>```

I did a PGM test in the same environment as when the log was created: no symptoms.

I tried running several PGMs simultaneously : no symptoms.

I Applied several same timers asynchronously : log function was not worked.

Exploring issues related to c# timers on stackoverflow: There are no similar symptoms.

Body:
Thanks for your attention.

Here's what my code does:

A method(Using C# WinForm, System.timers.timer) that checks the variables every second, leaves a log, and moves on to the next function if the condition is met.

After working for quite long time(more than 2 weeks), the following symptoms occurred :

overlapping logs left by the timer.

The period of the timer is 1 second, and the operation of the timer is not considered heavy.

here is example of the logs

[14:06:05]A
[14:06:05]B
[14:06:05]B
[14:06:05]B
[14:06:05]B
[14:06:05]B
... (20 times/sec)

I just couldn't figure out why.
I tried running several PGMs simultaneously and applied several timers asynchronously, but the symptoms did not appear.

Ask for advice from teachers. I would like to refer to it for problem solving and study.
Detailed code is below.

This is how I initialized it.

 private static System.Timers.Timer TestEndDetection_Timer_;

 private void SetUp_TestEndDetection_Timer_()
        {

            TestEndDetection_Timer_ = new System.Timers.Timer(1000);

            TestEndDetection_Timer_.Elapsed += TestEndDetection_Timer_Event;
            TestEndDetection_Timer_.AutoReset = true;
            TestEndDetection_Timer_.Enabled = true;
        }

I use that 'SetUp_TestEndDetection_Timer_()' only once when PGM start (Form_load())

here is code of TestEndDetection_Timer_Event()

 private void TestEndDetection_Timer_Event(Object source, ElapsedEventArgs e)
        {
            defrostCount++;
            CheckForIllegalCrossThreadCalls = false;

            if (NowTesting && AutoDefrost && checkBox2.Checked)
            {

                TestEndDetectionDealyTimer++;

                if (TestEndDetectionDealyTimer > 180)
                {
                    bool Fix1End = false;
                    bool Fix2End = false;
                    bool Fix3End = false;
                    bool Fix4End = false;
                    bool Fix5End = false;
                    bool Fix6End = false;

                    bool Fix1Done = false;
                    bool Fix2Done = false;
                    bool Fix3Done = false;
                    bool Fix4Done = false;
                    bool Fix5Done = false;
                    bool Fix6Done = false;

                    bool Fix1Power = false;
                    bool Fix2Power = false;
                    bool Fix3Power = false;
                    bool Fix4Power = false;
                    bool Fix5Power = false;
                    bool Fix6Power = false;

                    Fix1Done = File.Exists(@"Z:\result\fix1\hdiag.log");
                    Fix2Done = File.Exists(@"Z:\result\fix2\hdiag.log");
                    Fix3Done = File.Exists(@"Z:\result\fix3\hdiag.log");
                    Fix4Done = File.Exists(@"Z:\result\fix4\hdiag.log");
                    Fix5Done = File.Exists(@"Z:\result\fix5\hdiag.log");
                    Fix6Done = File.Exists(@"Z:\result\fix6\hdiag.log");

                    defrostlogger("TESTDONE: "+Convert.ToInt32(Fix1Done) + "/" + Convert.ToInt32(Fix2Done) + "/" + Convert.ToInt32(Fix3Done) + "/" + Convert.ToInt32(Fix4Done) + "/" + Convert.ToInt32(Fix5Done) + "/" + Convert.ToInt32(Fix6Done));

                    Fix1Power = m_ucFixInfo[1].PowerStat;
                    Fix2Power = m_ucFixInfo[2].PowerStat;
                    Fix3Power = m_ucFixInfo[3].PowerStat;
                    Fix4Power = m_ucFixInfo[4].PowerStat;
                    Fix5Power = m_ucFixInfo[5].PowerStat;
                    Fix6Power = m_ucFixInfo[6].PowerStat;

                    defrostlogger("POWER: "+Convert.ToInt32(Fix1Power) + "/" + Convert.ToInt32(Fix2Power) + "/" + Convert.ToInt32(Fix3Power) + "/" + Convert.ToInt32(Fix4Power) + "/" + Convert.ToInt32(Fix5Power) + "/" + Convert.ToInt32(Fix6Power));

                    if (Fix1Done || !Fix1Power) { Fix1End = true; } else { Fix1End = false; }
                    if (Fix2Done || !Fix2Power) { Fix2End = true; } else { Fix2End = false; }
                    if (Fix3Done || !Fix3Power) { Fix3End = true; } else { Fix3End = false; }
                    if (Fix4Done || !Fix4Power) { Fix4End = true; } else { Fix4End = false; }
                    if (Fix5Done || !Fix5Power) { Fix5End = true; } else { Fix5End = false; }
                    if (Fix6Done || !Fix6Power) { Fix6End = true; } else { Fix6End = false; }

                    if (Fix1End && Fix2End && Fix3End && Fix4End && Fix5End && Fix6End && AutoDefrostRunStat && TestEndCount < 20)
                    {
                        TestEndCount++;
                    }

                    if (TestEndCount > 10)
                    {

                        if (button13.Text == "Door Open" && DefrostAvailable)
                        {
                            defrostlogger("A");
                            RunDefrost();
                            AutoDefrostRunStat = false;
                            NowTesting = false;
                            TestEndCount = 0;
                        }
                        else
                        {
                            defrostlogger("B");
                        }
                    }
                }
            }
            else
            {
                if (defrostCount % 10 == 9&&NowTesting)
                {
                    Load_SV_txt();
                    defrostCount = 0;
                }
            }
        }

defrostlogger is :

private void defrostlogger(string msg)
        {
            using (System.IO.StreamWriter file_ = new System.IO.StreamWriter(Application.StartupPath + @"\Logs\DefrostLog_" + System.DateTime.Now.ToString("MM_dd") + ".txt", true))
            {
                file_.WriteLine("[" + System.DateTime.Now.ToString("HH:mm:ss") + "]" + msg);
            }
        }

I did a PGM test in the same environment as when the log was created: no symptoms.

I tried running several PGMs simultaneously : no symptoms.

I Applied several same timers asynchronously : log function was not worked.

Exploring issues related to c# timers on stackoverflow: There are no similar symptoms.


问:
Unable to filter data with timestamp value using Mybatis and Oracle DB
I have a student_audit table where I am storing some audit information for the student.

The table has existing data.

```<code>ID | NAME | AUDIT_TIMESTAMP
___________________________
1  | TEST | 22-JUN-22 07.23.59.515462000 AM

</code>```

The DDL for the table is as follows:

```<code>CREATE TABLE student_audit (
  id NUMBER(8) NOT NULL,
  name VARCHAR2(20 BYTE) NOT NULL,
  audit_timestamp TIMESTAMP NOT NULL,
  CONSTRAINT pk_stdnt_aud PRIMARY KEY (id)
);
</code>```

I have a mapper method in StudentDao.java

```<code>StudentEntity getStudent(@Param("name") String name,
      @Param("auditTimestamp") Timestamp auditTimestamp)
</code>```
```<code>public class StudentEntity {

  private Integer id;

  private String name;

  // java.sql.Timestamp
  private Timestamp auditTimestamp;

  // getters and setters

}
</code>```

The StudentDao.xml method is as follows

```<code><resultMap id="studentMap"
               type="fully-qualified-name-of-StudentEntity ">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="auditTimestamp" column="auditTimestamp"/>
</resultMap>

<select id="getStudent"
    resultMap="studentMap">
    SELECT
      s.id
    , s.name
    , s.audit_timestamp as auditTimestamp
    FROM
      student_audit s
    WHERE
      s.audit_timestamp = #{auditTimestamp}
</select>
</code>```

When I run an integration test against this Dao method, its always returning null. However, the following query in SQL developer is returning the value.

```<code>select * from student_audit
where audit_timestamp = TO_TIMESTAMP('2022-06-22 07:23:59.515462', 'YYYY-MM-DD HH24:MI:SS.FF');
</code>```

I tried the following solutions:

Using the SqlTimestampTypeHandler along with the audit timestamp value

Using jdbcType attribute

I have not been able to resolve this.

Adding logs from the console

```<code>11:44:46.495 [main] DEBUG c.c.w.f.e.p.r.StudentDao.getStudent - ==>  Preparing: SELECT s.id, s.name, s.audit_timestamp as auditTimestamp FROM student_audit s WHERE s.audit_timestamp = ?
11:44:46.551 [main] DEBUG c.c.w.f.e.p.r.StudentDao.getStudent - ==> Parameters: 2022-06-22 07:23:59.515462(Timestamp)
11:44:47.240 [main] DEBUG c.c.w.f.e.p.r.StudentDao.getStudent - <==      Total: 0
</code>```

Body:
I have a student_audit table where I am storing some audit information for the student.

The table has existing data.

ID | NAME | AUDIT_TIMESTAMP
___________________________
1  | TEST | 22-JUN-22 07.23.59.515462000 AM

The DDL for the table is as follows:

CREATE TABLE student_audit (
  id NUMBER(8) NOT NULL,
  name VARCHAR2(20 BYTE) NOT NULL,
  audit_timestamp TIMESTAMP NOT NULL,
  CONSTRAINT pk_stdnt_aud PRIMARY KEY (id)
);

I have a mapper method in StudentDao.java

StudentEntity getStudent(@Param("name") String name,
      @Param("auditTimestamp") Timestamp auditTimestamp)

public class StudentEntity {

  private Integer id;

  private String name;

  // java.sql.Timestamp
  private Timestamp auditTimestamp;

  // getters and setters

}

The StudentDao.xml method is as follows

<resultMap id="studentMap"
               type="fully-qualified-name-of-StudentEntity ">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="auditTimestamp" column="auditTimestamp"/>
</resultMap>

<select id="getStudent"
    resultMap="studentMap">
    SELECT
      s.id
    , s.name
    , s.audit_timestamp as auditTimestamp
    FROM
      student_audit s
    WHERE
      s.audit_timestamp = #{auditTimestamp}
</select>

When I run an integration test against this Dao method, its always returning null. However, the following query in SQL developer is returning the value.

select * from student_audit
where audit_timestamp = TO_TIMESTAMP('2022-06-22 07:23:59.515462', 'YYYY-MM-DD HH24:MI:SS.FF');

I tried the following solutions:

Using the SqlTimestampTypeHandler along with the audit timestamp value

Using jdbcType attribute

I have not been able to resolve this.

Adding logs from the console

11:44:46.495 [main] DEBUG c.c.w.f.e.p.r.StudentDao.getStudent - ==>  Preparing: SELECT s.id, s.name, s.audit_timestamp as auditTimestamp FROM student_audit s WHERE s.audit_timestamp = ?
11:44:46.551 [main] DEBUG c.c.w.f.e.p.r.StudentDao.getStudent - ==> Parameters: 2022-06-22 07:23:59.515462(Timestamp)
11:44:47.240 [main] DEBUG c.c.w.f.e.p.r.StudentDao.getStudent - <==      Total: 0


问:
MongoDB not retrieving file name
I'm trying to store images in the project then use hbs to get the name of the image and use it in the img src file path but the name of the file is not getting stored in MongoDB.

This is my  model:

```<code>const mongoose = require('mongoose');
const playerObj =
{
    ign: {
        type: String,
        require: true
    },
    role: {
        type: String,
        require: true
    },
    team: {
        type: String,
        require: true
    },
    playerIcon: {
        type: String,
        require: true
    },
    playerName: {
        type: String,
        require: true
    },
    playerNumber: {
        type: String,
        require: true
    },
    verificationStatus: {
        type: String,
        require: true,
        default: "No"
    }

}

const playerSchema = new mongoose.Schema(playerObj);
module.exports = mongoose.model('Player', playerSchema);
</code>```

This is my router:

```<code>const express = require('express');
const router = express.Router();
const Player = require('../models/player');
const multer = require('multer');

const storage = multer.diskStorage({
    destination: 'images/',
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname);
    }
});

const upload = multer({
    storage: storage,
    limits: { fileSize: 1000000 },
});

router.post('/add', upload.single('playerIcon'), (req, res, next) => {
Player.create(
    {
        ign: req.body.ign,
        role: req.body.role,
        team: req.body.team,
        playerIcon: req.file.filename.playerIcon,
        playerName: req.body.playerName,
        playerNumber: req.body.playerNumber,
        verificationStatus: req.body.verificationStatus
    },
    (err, newPlayer) => {
        if (err) { console.log(err); }
        else {
            res.redirect('/players');
        }
    }
);
});
</code>```

this my form view:

```<code> <div class="addPlayerCon" id="PlayerForm">

    <form method="POST" class="Form" enctype="multipart/form-data">
      <Label class="fromlabel">{{title}}</Label>
      <label for="playerName" class="inputLabel">Player Name</label>
      <input type="text" name="playerName" placeholder="Enter Player Name" required/>
      <br>
      <label for="playerNumber" class="inputLabel">Player Number</label>
      <input type="text" name="playerNumber" placeholder="Enter Player Number" required/>
      <br>
      <label for="ign" class="inputLabel">In Game Name</label>
      <input type="text" name="ign" placeholder="Enter IGN" required/>
      <br>
      <label for="role" class="inputLabel">Position/Role</label>
      <input type="text" name="role" placeholder="Enter Position or Role" required/>
      <br>
      <label for="playerIcon" class="inputLabel">Player Icon</label>
      <input type="file" name="playerIcon"/>
      <br>
        <label for="team" class="inputLabel">Team</label>
        <select name="team" class="addPlayerDrop" required>
            {{#each teams}}
            <option>{{this.teamName}}</option>
            {{/each}}
        </select>
      <br>
        <label for="verificationStatus" class="inputLabel">Verification Status</label>
        <select name="verificationStatus" class="addPlayerDrop" required>
            <option value="No">No</option>
            <option value="Yes">Yes</option>
        </select>
      <br>
      <button type="submit" class="btnAdd">Add Player</button>
    </form>
  </div>
</code>```

I've read through the multer npm doc here and tried messing around with the req. file and the data type of playerIcon in the model but I'm not sure what causes it to not send the file name to MongoDB my hunch is that it's something I'm missing in the model or the router.

Title: MongoDB not retrieving file name

Body:
I'm trying to store images in the project then use hbs to get the name of the image and use it in the img src file path but the name of the file is not getting stored in MongoDB.

This is my  model:

const mongoose = require('mongoose');
const playerObj =
{
    ign: {
        type: String,
        require: true
    },
    role: {
        type: String,
        require: true
    },
    team: {
        type: String,
        require: true
    },
    playerIcon: {
        type: String,
        require: true
    },
    playerName: {
        type: String,
        require: true
    },
    playerNumber: {
        type: String,
        require: true
    },
    verificationStatus: {
        type: String,
        require: true,
        default: "No"
    }

}

const playerSchema = new mongoose.Schema(playerObj);
module.exports = mongoose.model('Player', playerSchema);

This is my router:

const express = require('express');
const router = express.Router();
const Player = require('../models/player');
const multer = require('multer');

const storage = multer.diskStorage({
    destination: 'images/',
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname);
    }
});

const upload = multer({
    storage: storage,
    limits: { fileSize: 1000000 },
});

router.post('/add', upload.single('playerIcon'), (req, res, next) => {
Player.create(
    {
        ign: req.body.ign,
        role: req.body.role,
        team: req.body.team,
        playerIcon: req.file.filename.playerIcon,
        playerName: req.body.playerName,
        playerNumber: req.body.playerNumber,
        verificationStatus: req.body.verificationStatus
    },
    (err, newPlayer) => {
        if (err) { console.log(err); }
        else {
            res.redirect('/players');
        }
    }
);
});

this my form view:

    <form method="POST" class="Form" enctype="multipart/form-data">
      {{title}}
      Player Name
      <input type="text" name="playerName" placeholder="Enter Player Name" required/>

      Player Number
      <input type="text" name="playerNumber" placeholder="Enter Player Number" required/>

      In Game Name
      <input type="text" name="ign" placeholder="Enter IGN" required/>

      Position/Role
      <input type="text" name="role" placeholder="Enter Position or Role" required/>

      Player Icon
      <input type="file" name="playerIcon"/>

        Team
        <select name="team" class="addPlayerDrop" required>
            {{#each teams}}
            <option>{{this.teamName}}</option>
            {{/each}}
        </select>

        Verification Status
        <select name="verificationStatus" class="addPlayerDrop" required>
            <option value="No">No</option>
            <option value="Yes">Yes</option>
        </select>

      <button type="submit" class="btnAdd">Add Player</button>
    </form>

I've read through the multer npm doc here and tried messing around with the req. file and the data type of playerIcon in the model but I'm not sure what causes it to not send the file name to MongoDB my hunch is that it's something I'm missing in the model or the router.


问:
I am changing the value of a global variable inside a function, but as soon as I get out of that function it is changing back to its previous value
I am changing the value of a global variable inside a function, but as soon as I get out of that function it is changing back to its previous value.
I have created a game in which a rabbit(represented by "r") is moving on a path, whenever it sees a hole("O") it jumps and if it see carrot("c"), it eat and the r is changed to "R".
I have functions for left move, right move and for picking a carrot. Now whenever it picks carrot I am changing the global variable to "R" but whenever it moves again it is keeping it "r"

This is my code

```<code>import random
c="r"

def left_move(track):
    i=track.index(c)
    if (i>0):
        next=i-1
        if (track[next]=="c"):
            track = pick_carrot(track, next, i)
            return track
        if (track[next]=="O"):
            track=jump_hole(track, next, "a", i)
            return track
        track[next]=c
        track[i]="-"
        print(i)
        return track

def right_move(track):
    i=track.index(c)
    if (i<50):
        next=i+1
        if (track[next]=="c"):
            track = pick_carrot(track, next, i)
            return track
        if (track[next]=="O"):
            track=jump_hole(track, next, "d", i)
            return track
        track[next]=c
        track[i]="-"
        print(i)
        return track

def string_track(track):
    string_track = '[' + ' '.join(track) + ']'
    return(string_track)

def pick_carrot(track, carrot, rabit, c):
    c="R"
    print("The value of c is now ")
    print(c)
    track[rabit]="-"
    track[carrot]="R"
    print("carrot picked")
    return track,c

def jump_hole(track, hole, direction, current):
    if (direction=="a"):
        next=hole-1
    if (direction=="d"):
        next=hole+1
    track[next]=c
    track[current]="-"
    print("hole jumped")
    return track

track=["-","-","-","-","-","-","r","-","-","-","-","c","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","O"]

random.shuffle(track)
print(string_track(track))
print(track.index("r"))
val=input()
while val!="0":
    if val=="a":
        track=left_move(track)
        print(c)
    if val=="d":
        track=right_move(track)
        print(c)
    if val=="0":
        break
    else:
        val=input()
print(string_track(track))
</code>```

Body:
I am changing the value of a global variable inside a function, but as soon as I get out of that function it is changing back to its previous value.
I have created a game in which a rabbit(represented by "r") is moving on a path, whenever it sees a hole("O") it jumps and if it see carrot("c"), it eat and the r is changed to "R".
I have functions for left move, right move and for picking a carrot. Now whenever it picks carrot I am changing the global variable to "R" but whenever it moves again it is keeping it "r"

This is my code

import random
c="r"

def left_move(track):
    i=track.index(c)
    if (i>0):
        next=i-1
        if (track[next]=="c"):
            track = pick_carrot(track, next, i)
            return track
        if (track[next]=="O"):
            track=jump_hole(track, next, "a", i)
            return track
        track[next]=c
        track[i]="-"
        print(i)
        return track

def right_move(track):
    i=track.index(c)
    if (i<50):
        next=i+1
        if (track[next]=="c"):
            track = pick_carrot(track, next, i)
            return track
        if (track[next]=="O"):
            track=jump_hole(track, next, "d", i)
            return track
        track[next]=c
        track[i]="-"
        print(i)
        return track

def string_track(track):
    string_track = '[' + ' '.join(track) + ']'
    return(string_track)

def pick_carrot(track, carrot, rabit, c):
    c="R"
    print("The value of c is now ")
    print(c)
    track[rabit]="-"
    track[carrot]="R"
    print("carrot picked")
    return track,c

def jump_hole(track, hole, direction, current):
    if (direction=="a"):
        next=hole-1
    if (direction=="d"):
        next=hole+1
    track[next]=c
    track[current]="-"
    print("hole jumped")
    return track

track=["-","-","-","-","-","-","r","-","-","-","-","c","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","O"]

random.shuffle(track)
print(string_track(track))
print(track.index("r"))
val=input()
while val!="0":
    if val=="a":
        track=left_move(track)
        print(c)
    if val=="d":
        track=right_move(track)
        print(c)
    if val=="0":
        break
    else:
        val=input()
print(string_track(track))


问:
"attempts" field is invalid in concourse version 7.7.1
in concourse 7.7.1, When I setup the pipeline

plan:
- {get: abc, trigger: true}
- get: ttt
- get: library_cache
- in_parallel:
- {task: build-frontend, file: ttt/ci/tasks/build.yml, privileged: true, params: {TARGET_CFG: ((gamma)), SERVICE: frontend}, attempts:2}
- {task: build-backend, file: ttt/ci/tasks/build.yml, privileged: true, params: {TARGET_CFG: ((gamma)), SERVICE: backend}, attempts:2}
- {task: build-worker, file: ttt/ci/tasks/build.yml, privileged: true, params: {TARGET_CFG: ((gamma)), SERVICE: worker}, attempts:2}

I got the below error:

```<code>error: invalid pipeline config:
invalid jobs:
    jobs.build-xyz.plan.do[3].in_parallel.steps[0]: unknown fields ["attempts:2"]
    jobs.build-xyz.plan.do[3].in_parallel.steps[1]: unknown fields ["attempts:2"]
    jobs.build-xyz.plan.do[3].in_parallel.steps[2]: unknown fields ["attempts:2"]
</code>```

In my pipeline config: I replaced "limit" in place of "attempts" but same issue

```<code>error: invalid pipeline config:
invalid jobs:
    jobs.build-xyz.plan.do[3].in_parallel.steps[0]: unknown fields ["limit:2"]
    jobs.build-xyz.plan.do[3].in_parallel.steps[1]: unknown fields ["limit:2"]
    jobs.build-xyz.plan.do[3].in_parallel.steps[2]: unknown fields ["limit:2"]
</code>```

Body:
in concourse 7.7.1, When I setup the pipeline

plan:
- {get: abc, trigger: true}
- get: ttt
- get: library_cache
- in_parallel:
- {task: build-frontend, file: ttt/ci/tasks/build.yml, privileged: true, params: {TARGET_CFG: ((gamma)), SERVICE: frontend}, attempts:2}
- {task: build-backend, file: ttt/ci/tasks/build.yml, privileged: true, params: {TARGET_CFG: ((gamma)), SERVICE: backend}, attempts:2}
- {task: build-worker, file: ttt/ci/tasks/build.yml, privileged: true, params: {TARGET_CFG: ((gamma)), SERVICE: worker}, attempts:2}

I got the below error:

error: invalid pipeline config:
invalid jobs:
    jobs.build-xyz.plan.do[3].in_parallel.steps[0]: unknown fields ["attempts:2"]
    jobs.build-xyz.plan.do[3].in_parallel.steps[1]: unknown fields ["attempts:2"]
    jobs.build-xyz.plan.do[3].in_parallel.steps[2]: unknown fields ["attempts:2"]

In my pipeline config: I replaced "limit" in place of "attempts" but same issue

error: invalid pipeline config:
invalid jobs:
    jobs.build-xyz.plan.do[3].in_parallel.steps[0]: unknown fields ["limit:2"]
    jobs.build-xyz.plan.do[3].in_parallel.steps[1]: unknown fields ["limit:2"]
    jobs.build-xyz.plan.do[3].in_parallel.steps[2]: unknown fields ["limit:2"]


问:
Why does the following function to compare vectors not work?
I have created a function template to compare two inputs. In one case I wanted to make an overload to it to compare two vectors. But it doesn't work. It somehow compares the location of the two vectors.

Please go through the code and debug the issue.

```<code>//Learning

#include<iostream>
#include <vector>

template<typename T> T larger( T first, T second);
int main() {

    std::vector<int>bc{ 1,5,2,3,4,5,6 };
    std::vector<int>ab{ 1,2,3,4,5,8,10 };

    std::vector<int> res{ *larger(&ab,&bc) };
    for (int i : res) {
        std::cout << i << "\t";
    }
}

//Largerfunction begins

template <typename T>
T larger(T first, T second) {
    if (first > second) {               //General definition for any static data type for Larger function
        return first;
    }
    else {
        return second;
    }

}

template<typename T>
std::vector<T>* larger(std::vector<T>*first, std::vector<T>*second) {       //Overload on the Larger function for pas by pointer for std::vector data type
    size_t i{};
    while ((*first)[i] != (*first)[-1] or (*second)[i] != (*second)[-1]) {
        if ((*first)[i] > (*second)[i]) {
            return first;
        }
        else if ((*first)[i] < (*second)[i]) {
            return second;
        }
        else {
            i++;
        }
    }
    if ((*first)[i] == (*first)[-1]) {
        return second;
    }
    else{
        return first;
    }

}
</code>```

Body:
I have created a function template to compare two inputs. In one case I wanted to make an overload to it to compare two vectors. But it doesn't work. It somehow compares the location of the two vectors.

Please go through the code and debug the issue.

//Learning

#include<iostream>
#include <vector>

template<typename T> T larger( T first, T second);
int main() {

    std::vector<int>bc{ 1,5,2,3,4,5,6 };
    std::vector<int>ab{ 1,2,3,4,5,8,10 };

    std::vector<int> res{ *larger(&ab,&bc) };
    for (int i : res) {
        std::cout << i << "\t";
    }
}

//Largerfunction begins

template <typename T>
T larger(T first, T second) {
    if (first > second) {               //General definition for any static data type for Larger function
        return first;
    }
    else {
        return second;
    }

}

template<typename T>
std::vector<T>* larger(std::vector<T>*first, std::vector<T>*second) {       //Overload on the Larger function for pas by pointer for std::vector data type
    size_t i{};
    while ((*first)[i] != (*first)[-1] or (*second)[i] != (*second)[-1]) {
        if ((*first)[i] > (*second)[i]) {
            return first;
        }
        else if ((*first)[i] < (*second)[i]) {
            return second;
        }
        else {
            i++;
        }
    }
    if ((*first)[i] == (*first)[-1]) {
        return second;
    }
    else{
        return first;
    }

}


问:
How to handle chinese charactor when getting user input from stdin using getline
I try to get user input using getline fucntion. User may type chinese charactors, some backspaces and some other charactors. Then I meet an issue. What I get in program is not I typed in termial.

My code likes below:

int main(int argc, chart argv[])
{

```<code>cout << ">>";
char *cmdBuf = (char*)malloc(1024);
while(true)
{
    size_t cmdLen = 1024;
    ssize_t readNum = getline(&cmdBuf, &cmdLen, stdin);
    if (readNum == -1 || readNum == 1)
    {
         cout << ">>";
         continue;
    }
    cout << "readNum: " << readNum << ". The input is: << cmdBuf;
    cout << ">>;
}

free(cmdBuf) ;
return 0;
</code>```

}

Execute the program in shell and get the results below('在' is a chinese charactor):

user input: display
program output: readNum: 8. The input is: display

user input: display在
program output: readNum: 11．The input is：display在

user input: display在[backspace][backspace]   ----------------- The termial shows "display".
program output: readNum: 9. The input is: display[a garbled character]

user input: display在[backspace][backspace][backspace] ----------------- The termial shows "displa".
program output: readNum: 8. The input is: display

From the results, '在' contains 3 charactors. However, if I type '在', I only need type 2 backspaces to clear '在' and then I will get a wrong input in C++ program.

What should I do to make sure what C++ program get from stdin is what user see in the terminal?

Body:
I try to get user input using getline fucntion. User may type chinese charactors, some backspaces and some other charactors. Then I meet an issue. What I get in program is not I typed in termial.

My code likes below:

int main(int argc, chart argv[])
{

cout << ">>";
char *cmdBuf = (char*)malloc(1024);
while(true)
{
    size_t cmdLen = 1024;
    ssize_t readNum = getline(&cmdBuf, &cmdLen, stdin);
    if (readNum == -1 || readNum == 1)
    {
         cout << ">>";
         continue;
    }
    cout << "readNum: " << readNum << ". The input is: << cmdBuf;
    cout << ">>;
}

free(cmdBuf) ;
return 0;

}

Execute the program in shell and get the results below('在' is a chinese charactor):

user input: display
program output: readNum: 8. The input is: display

user input: display在
program output: readNum: 11．The input is：display在

user input: display在[backspace][backspace]   ----------------- The termial shows "display".
program output: readNum: 9. The input is: display[a garbled character]

user input: display在[backspace][backspace][backspace] ----------------- The termial shows "displa".
program output: readNum: 8. The input is: display

From the results, '在' contains 3 charactors. However, if I type '在', I only need type 2 backspaces to clear '在' and then I will get a wrong input in C++ program.

What should I do to make sure what C++ program get from stdin is what user see in the terminal?


问:
connecting multiple VR headsets to each other
what are the possibilities for connecting Multiple VR headsets(of same brand) to each other without using internet.
if possible, please share some resources on how to do it.</p>


问:
Pre-6.9 Gradle adding extra directories to Java home path on M1 Mac
I'm trying to build a Java 8 project on an M1 Mac that uses Gradle 4.9. There are some Maven dependencies that only exist in x86_64 format, so I'm pointing the project at an x86_64 JDK that I've installed in my home directory. This causes it to grab the osx-x86_64.exe variants of those dependencies since the osx-aarm_64.exe ones don't exist.

The problem is that Gradle adds zulu-8.jdk/Contents/Home to the Java home directory, resulting in:

```<code>Expecting: '/Users/ffoobar/Library/Java/zulu8.66.0.15-ca-jdk8.0.352-macosx_x64/Contents/Home' but was: '/Users/ffoobar/Library/Java/zulu8.66.0.15-ca-jdk8.0.352-macosx_x64/Contents/Home/zulu-8.jdk/Contents/Home'.
</code>```

This problem goes away if I specify version Gradle 6.9 (the first to natively support Apple silicon, so likely not a coincidence) or later in my build.gradle, but it breaks the build due to changes in Gradle scripting.

I'm at a loss on how to prevent the appending of zulu-8.jdk/Contents/Home—any ideas?

Body:
I'm trying to build a Java 8 project on an M1 Mac that uses Gradle 4.9. There are some Maven dependencies that only exist in x86_64 format, so I'm pointing the project at an x86_64 JDK that I've installed in my home directory. This causes it to grab the osx-x86_64.exe variants of those dependencies since the osx-aarm_64.exe ones don't exist.

The problem is that Gradle adds zulu-8.jdk/Contents/Home to the Java home directory, resulting in:

Expecting: '/Users/ffoobar/Library/Java/zulu8.66.0.15-ca-jdk8.0.352-macosx_x64/Contents/Home' but was: '/Users/ffoobar/Library/Java/zulu8.66.0.15-ca-jdk8.0.352-macosx_x64/Contents/Home/zulu-8.jdk/Contents/Home'.

This problem goes away if I specify version Gradle 6.9 (the first to natively support Apple silicon, so likely not a coincidence) or later in my build.gradle, but it breaks the build due to changes in Gradle scripting.

I'm at a loss on how to prevent the appending of zulu-8.jdk/Contents/Home—any ideas?


问:
Can node.path handle Windows variables like %LOCALAPPDATA%?
I'm trying to write an installer script using Node and finding it quite frustrating that the Node path module doesn't seem to resolve variables like %LOCALAPPDATA%, nor do the docs mention it. Is there any good way around this problem?


问:
scrollToIndex in primeng virtualscroll table
using primeng virtual scroll table in angular to handle huge set of data [array], here i want to use
scrollToIndex is there any thing like cdk-virtual-scroll-viewport in primeng table, if user clicks on a button I need to scroll to a particular index (eg 100)

```<code><div class="log-console-parent" #logsParentDiv (wheel)="onUserScroll()">
  <p-table [columns]="cols" [value]="getFilteredLogs()" [scrollable]="true" [rows]="100" scrollHeight="flex"
    [virtualScroll]="true" [virtualRowHeight]="27">
    <ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex" let-columns="columns">
      <tr>
        <td>
          <span [innerHTML]="rowData.message"></span>
        </td>
      </tr>
    </ng-template>
  </p-table>
</div>
</code>```

versions : angular:  12, primeng: 12

Body:
using primeng virtual scroll table in angular to handle huge set of data [array], here i want to use
scrollToIndex is there any thing like cdk-virtual-scroll-viewport in primeng table, if user clicks on a button I need to scroll to a particular index (eg 100)

    <ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex" let-columns="columns">

    </ng-template>

versions : angular:  12, primeng: 12


问:
how to draw two connectors in single line in plantuml?
I use follow code to draw my diagram, but the two connector between a <-> b and b <-> c are in two separated line.

```<code>    participant a
    participant b
    participant c

    a -> b: SESSION-x/XXXX_IND-y
    b -> c: SESSION-x/XXXX_IND-y
</code>```

how to draw the two connectors like picture in this link

Body:
I use follow code to draw my diagram, but the two connector between a <-> b and b <-> c are in two separated line.

    participant a
    participant b
    participant c

    a -> b: SESSION-x/XXXX_IND-y
    b -> c: SESSION-x/XXXX_IND-y

how to draw the two connectors like picture in this link


问:
How to use AWS X Ray Service on PHP application
may I ask if there's any way I can use AWS X-RAY service on my PHP application? I tried the official guide posted by AWS https://aws.amazon.com/about-aws/whats-new/2022/09/aws-x-ray-support-tracing-php-applications-opentelemetry-public-preview/ , but I can't seem to get the packages installing using composer...Are there any alternatives that I could use to get this X-Ray running ?


问:
Images cannot load after firebase hosting
I made my portfolio website with NextJS and React, then use Firebase to host it.
However, the logo icon was gone when the site deployed.

I can't find the solution to deal with it. Below is my folder structure

Or I need to set something in the nextConfig.js?

Hope can get help, many thanks.


问:
I have a question when an iOS app and its widget share a database
Currently my app wants to add a widget.
I know that in order to use a database in a widget, I need to use the database in the path created using the app group.
In this case, usually only widgets use a shared database? Or will the app database itself use a shared database as well?

If I use a shared database like this, this database becomes a new database without data. If the app db also uses a shared database, Should I migrate the database data?
Is this the normal way? I don't know if I'm doing it right.


问:
Disable Particular Queries Search in my WordPress website
I want to disable particular results based on specific queries like casino, gambling, or any other related words. I found some particular codes but cannot understand them as I am not so familiar with coding.

Here is the one I found but I want to disable results based on the query not on post ids.

One more thing I want to know is where to add or place the code to perform it.

```<code>add_action('pre_get_posts','wpse67626_exclude_posts_from_search');
function wpse67626_exclude_posts_from_search( $query ){

    if( $query->is_main_query() && is_search() ){
         //Exclude posts by ID
         $post_ids = array(7,19,21);
         $query->set('post__not_in', $post_ids);
    }

}
</code>```

Can you guys please help me, how can I do this?

Thanks in advance, waiting for your reply.

I search for some plugins but don't get any related results and then I search for some codes on StackOverflow but don't understand how and where to perform and add code.

Body:
I want to disable particular results based on specific queries like casino, gambling, or any other related words. I found some particular codes but cannot understand them as I am not so familiar with coding.

Here is the one I found but I want to disable results based on the query not on post ids.

One more thing I want to know is where to add or place the code to perform it.

add_action('pre_get_posts','wpse67626_exclude_posts_from_search');
function wpse67626_exclude_posts_from_search( $query ){

    if( $query->is_main_query() && is_search() ){
         //Exclude posts by ID
         $post_ids = array(7,19,21);
         $query->set('post__not_in', $post_ids);
    }

}

Can you guys please help me, how can I do this?

Thanks in advance, waiting for your reply.

I search for some plugins but don't get any related results and then I search for some codes on StackOverflow but don't understand how and where to perform and add code.


问:
check the folder name and continue from the largest number
I need to do the folders in the directory, but when I add the new images, I cannot create the new folder. I want to check the folder number and then continue from the largest number. What can I do for that?
here the code I have done:

```<code>for file in os.scandir(path_name):
    if str(file.name).endswith(ext) or str(file.name).endswith(ext2):
        new_file = imgPrefix + str(count).zfill(6)+'.'+ext
        # generate the source file path & name
        src = os.path.join(path_name, file.name)
        # create a new sub-folder for this image
        subFolder = subFolderPrefix + str(count)
        print(subFolder)
        splitted = subFolder.split("_")
        print(splitted)
        if splitted[2] in splitted():
            count = splitted[2]
            count += 2
        createFolder(os.path.join(export_folder, subFolder))
        # generate the destination file path & name
        dst = os.path.join(export_folder, subFolder, new_file)
        # perform the move
        os.rename(src, dst)
        count += 1

</code>```

Such as I already have the folders with the names "Image1, Image2,....Image 6", and I want to continue to create folders" Image7 or Image 8". I tried to split the name of the folder to check the name but it's not working.

Body:
I need to do the folders in the directory, but when I add the new images, I cannot create the new folder. I want to check the folder number and then continue from the largest number. What can I do for that?
here the code I have done:

for file in os.scandir(path_name):
    if str(file.name).endswith(ext) or str(file.name).endswith(ext2):
        new_file = imgPrefix + str(count).zfill(6)+'.'+ext
        # generate the source file path & name
        src = os.path.join(path_name, file.name)
        # create a new sub-folder for this image
        subFolder = subFolderPrefix + str(count)
        print(subFolder)
        splitted = subFolder.split("_")
        print(splitted)
        if splitted[2] in splitted():
            count = splitted[2]
            count += 2
        createFolder(os.path.join(export_folder, subFolder))
        # generate the destination file path & name
        dst = os.path.join(export_folder, subFolder, new_file)
        # perform the move
        os.rename(src, dst)
        count += 1

Such as I already have the folders with the names "Image1, Image2,....Image 6", and I want to continue to create folders" Image7 or Image 8". I tried to split the name of the folder to check the name but it's not working.


问:
I asked this question but didn't get any answer for this. Can anyone answer this question?
I asked this question but didn't get any answer for this. Can anyone please answer this question?

How to bypass gitlab-runner asking for password for sudo commands or What is the default password for gitlab-runners


问:
Context Processors in Python Django
context_processors.py

```<code>from .models import Cart, CartItem
from .views import _cart_id

def counter(request):
    item_count=0
    if 'admin' in request.path:
        return {}
    else:
        try:
            cart=Cart.objects.filter(cart_id=_cart_id(request))
            cart_items=CartItem.objects.all().filter(cart=cart[:1])
            for cart_item in cart_items:
                item_count += cart_item.quantity
        except Cart.DoesNotExist:
            item_count=0
    return dict(item_count=item_count)
</code>```

Can someone explain these entire code to me.

How's and what is the working of if loop here, return {}.

Title: Context Processors in Python Django

Body:
context_processors.py

from .models import Cart, CartItem
from .views import _cart_id

def counter(request):
    item_count=0
    if 'admin' in request.path:
        return {}
    else:
        try:
            cart=Cart.objects.filter(cart_id=_cart_id(request))
            cart_items=CartItem.objects.all().filter(cart=cart[:1])
            for cart_item in cart_items:
                item_count += cart_item.quantity
        except Cart.DoesNotExist:
            item_count=0
    return dict(item_count=item_count)

Can someone explain these entire code to me.

How's and what is the working of if loop here, return {}.


问:
How can we get the list of selected dates from days of current year in flutter?
I want to get the list of dates from selected day from calendar.
The scenario is that I have a screen in which I am displaying the weekly days and user can select any of the day from week. Suppose that any user selected "Monday" and "Friday" from that weekly Calendar then I want the dates which is coming on "Monday" and "Friday" during the current whole year in a list. I attached the screen shot of that app for getting better idea.

This functionality I want in flutter. So, if anyone have idea about it then please let me know.

Any type of your help is appreciated.

Thanks in advance.

Image:


问:
TypeError: (0 , tsoa_1.Get) is not a function
I'm using tsconfig-paths and tsoa in a project. I used tsconfig-paths following with document.

Please get code here.

I got error after running debug:

/home/tailt/.nvm/versions/node/v19.1.0/bin/node -r /home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/node_modules/ts-node/register -r /home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/node_modules/tsconfig-paths/register ./dist/index.js
/home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/src/controllers/ping.controller.ts:9
  @Get("/")
      ^
node_modules/@cspotcode/source-map-support/source-map-support.js:590
TypeError: (0 , tsoa_1.Get) is not a function
    at Object.<anonymous> (/home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/src/controllers/ping.controller.ts:9:7)
    at Module._compile (node:internal/modules/cjs/loader:1205:14)
    at Module.m._compile (/home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/node_modules/ts-node/src/index.ts:1455:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1259:10)
    at Object.require.extensions.<computed> [as .ts] (/home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/node_modules/ts-node/src/index.ts:1458:12)
    at Module.load (node:internal/modules/cjs/loader:1068:32)
    at Function.Module._load (node:internal/modules/cjs/loader:909:12)
    at Module.require (node:internal/modules/cjs/loader:1092:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/src/routes/index.ts:2:1)
node_modules/@cspotcode/source-map-support/source-map-support.js:594
Process exited with code 1
```

If if don't use tsconfig-paths, it works.

How can I fix this error?

Body:
I'm using tsconfig-paths and tsoa in a project. I used tsconfig-paths following with document.

Please get code here.

I got error after running debug:

/home/tailt/.nvm/versions/node/v19.1.0/bin/node -r /home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/node_modules/ts-node/register -r /home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/node_modules/tsconfig-paths/register ./dist/index.js
/home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/src/controllers/ping.controller.ts:9
  @Get("/")
      ^
node_modules/@cspotcode/source-map-support/source-map-support.js:590
TypeError: (0 , tsoa_1.Get) is not a function
    at Object.<anonymous> (/home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/src/controllers/ping.controller.ts:9:7)
    at Module._compile (node:internal/modules/cjs/loader:1205:14)
    at Module.m._compile (/home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/node_modules/ts-node/src/index.ts:1455:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1259:10)
    at Object.require.extensions.<computed> [as .ts] (/home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/node_modules/ts-node/src/index.ts:1458:12)
    at Module.load (node:internal/modules/cjs/loader:1068:32)
    at Function.Module._load (node:internal/modules/cjs/loader:909:12)
    at Module.require (node:internal/modules/cjs/loader:1092:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/home/tailt/Workspace/projects/private-projects/New Folder/test-tsconfig-paths-tsoa-bugs/src/routes/index.ts:2:1)
node_modules/@cspotcode/source-map-support/source-map-support.js:594
Process exited with code 1

If if don't use tsconfig-paths, it works.

How can I fix this error?


问:
Apache Camel Reducing Number though each Split Iteration
I have a directory of three files in the body of a Camel exchange, and I'm going to iterate through those 3 files using a Split. What I would like to do, is for each iteration, update a property with the total of all files (3 for this example) minus the current iteration. So at the some point, the goal is to have a property set to 1, so on another part of the code I can do logic based on this. I've tried a couple of different approaches but failed, and here I am. Here's a snippet of something I tried (simplified):

`private void test() {
from("timer:test?fixedRate=true&period=10000")
.process(exchange -> {

```<code>    Path pathD = FileSystems.getDefault().getPath("Lmao").toAbsolutePath();
    File folder = new File(pathD.toString());

    String[] fileList = folder.list();

    if (fileList != null) {
        exchange.setProperty("PROPERTY", fileList.length);
    }

    exchange.getIn().setBody(fileList);

})
    .split(body(), new AggregationStrategy() {
        @Override
        public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
            if (oldExchange == null) {
                Integer iterationsLeft = newExchange.getProperty("PROPERTY", Integer.class);
                Integer iterationsLeftMinusOne = iterationsLeft - 1;
                newExchange.setProperty("PROPERTY", iterationsLeftMinusOne);
                return newExchange;
            } else {
                Integer iterationsLeft = oldExchange.getProperty("PROPERTY", Integer.class);
                oldExchange.setProperty("PROPERTY", iterationsLeft - 1);
                return oldExchange;
            }
        }
    })
        .process(exchange -> {
            Integer test = exchange.getProperty("PROPERTY", Integer.class);
            System.out.println(test);
        })
.end();
</code>```

}
`

This code keeps printing 3 all the time and I wanted 3,2,1

Body:
I have a directory of three files in the body of a Camel exchange, and I'm going to iterate through those 3 files using a Split. What I would like to do, is for each iteration, update a property with the total of all files (3 for this example) minus the current iteration. So at the some point, the goal is to have a property set to 1, so on another part of the code I can do logic based on this. I've tried a couple of different approaches but failed, and here I am. Here's a snippet of something I tried (simplified):

`private void test() {
from("timer:test?fixedRate=true&period=10000")
.process(exchange -> {

    Path pathD = FileSystems.getDefault().getPath("Lmao").toAbsolutePath();
    File folder = new File(pathD.toString());

    String[] fileList = folder.list();

    if (fileList != null) {
        exchange.setProperty("PROPERTY", fileList.length);
    }

    exchange.getIn().setBody(fileList);

})
    .split(body(), new AggregationStrategy() {
        @Override
        public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
            if (oldExchange == null) {
                Integer iterationsLeft = newExchange.getProperty("PROPERTY", Integer.class);
                Integer iterationsLeftMinusOne = iterationsLeft - 1;
                newExchange.setProperty("PROPERTY", iterationsLeftMinusOne);
                return newExchange;
            } else {
                Integer iterationsLeft = oldExchange.getProperty("PROPERTY", Integer.class);
                oldExchange.setProperty("PROPERTY", iterationsLeft - 1);
                return oldExchange;
            }
        }
    })
        .process(exchange -> {
            Integer test = exchange.getProperty("PROPERTY", Integer.class);
            System.out.println(test);
        })
.end();

}
`

This code keeps printing 3 all the time and I wanted 3,2,1


问:
ms-settings:signinoptions command is not open the sign in setting in Windows 11
we tried to launch the sign-in option page Uri (ms-settings:signinoptions) programmatically, but it is launching the System settings page instead of Sign in the option settings page.

The same issue getting while running the same command using run. it's open the system setting page and when hits the same command in the run then opens the sign-in option page without closing the system setting page.

Note: this is happening in some system only

System details Edition :Windows 11 Pro Version : 22H2

I tried the below things

Sfc /ScanNow
DISM /Online /Cleanup-Image /ScanHealth
Dism /Online /Cleanup-image /RestoreHealth
Application setting reset
recovery reset this PC.
My expectation is, this command should open the sign-in option page.


问:
How to save sprintf(..) arguments to string or file
```<code>
`template<typename... Args>
void func(Args...args)
{
    string argsStr = argsToString(args);
    ...
    sprintf(parrtern, stringToArgs(argsStr));
}
`

Please tell me who can?
</code>```

I tried using tuples, folding expressions, storing arguments as a list in a string, where the prefix indicates the types of arguments. Tried to store in binary form.
But, almost always stopped at the stage of parsing arguments from a string and passing the sprintf function. Also uses va_list, but this is unsafe.
In the code, I need to save the arguments for the delayed formation of a string from a pattern. Because language of the pattern may change.

Body:
`template<typename... Args>
void func(Args...args)
{
    string argsStr = argsToString(args);
    ...
    sprintf(parrtern, stringToArgs(argsStr));
}
`

Please tell me who can?

I tried using tuples, folding expressions, storing arguments as a list in a string, where the prefix indicates the types of arguments. Tried to store in binary form.
But, almost always stopped at the stage of parsing arguments from a string and passing the sprintf function. Also uses va_list, but this is unsafe.
In the code, I need to save the arguments for the delayed formation of a string from a pattern. Because language of the pattern may change.


问:
How to prune skeleton in image using Julia
I've a road skeleton (from thinning) as shown below:

The original image was

I couldn't find pruning in Julia. Is there a away to remove small segments (streets) from continuous longer ones (main roads )? The red dots show the corner points whose Index is known.


问:
How to handle dependencies in docker compose file
I have a docker compose file with multiple services, the services are dependent on each other, for example if my previous service fails, still i want my next service to be executed, how can i handle these kind of scenarios?</p>


问:
React Native Mobile Application Security Test
After archive react-native ios appication, I had test it on Immuniweb mobile application testing tool. I have got security issue given bellow.

EXPOSURE OF POTENTIALLY SENSITIVE DATA [DAST] [M2] [CWE-200]
Potentially sensitive or internal information is detected in the mobile application via tracing its system calls.
[POTENTIAL HEROKU API KEY FOUND]

We did not use HEROKU anyway.

This is my package.json contents.

```<code>{
  "name": "",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "postinstall": "rn-nodeify --install fs,util,path,tls,stream,buffer,global,process --hack && patch-package",
    "android": "ENVFILE=.env react-native run-android",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint .",
    "build:ios": "react-native bundle --entry-file='index.js' --bundle-output='./ios/main.jsbundle' --dev=false --platform='ios'"
  },
  "dependencies": {
    "@gorhom/bottom-sheet": "^4.4.3",
    "@invertase/react-native-apple-authentication": "^2.2.2",
    "@react-native-async-storage/async-storage": "^1.17.9",
    "@react-native-community/checkbox": "^0.5.12",
    "@react-native-community/cli": "^8.0.5",
    "@react-native-community/datetimepicker": "^6.3.2",
    "@react-native-community/push-notification-ios": "^1.10.1",
    "@react-native-masked-view/masked-view": "^0.2.6",
    "@react-native-picker/picker": "^2.4.4",
    "@react-navigation/bottom-tabs": "^6.3.2",
    "@react-navigation/native": "^6.0.10",
    "@react-navigation/stack": "^6.2.1",
    "@rneui/base": "^0.0.0-edge.2",
    "@rneui/themed": "^0.0.0-edge.2",
    "@types/jest": "^29.0.0",
    "asyncstorage-down": "^4.2.0",
    "aws-iot-device-sdk": "^2.2.12",
    "aws-sdk": "^2.1203.0",
    "axios": "^0.27.2",
    "buffer": "^4.9.1",
    "global": "^4.4.0",
    "jsonwebtoken": "^8.5.1",
    "jwt-decode": "^2.2.0",
    "lodash.clonedeep": "^4.5.0",
    "lodash.get": "^4.4.2",
    "lodash.isempty": "^4.4.0",
    "lodash.max": "^4.0.1",
    "lodash.min": "^4.0.1",
    "lodash.omit": "^4.5.0",
    "lodash.unionby": "^4.8.0",
    "moment": "^2.29.4",
    "patch-package": "^6.4.7",
    "path-browserify": "0.0.0",
    "process": "^0.11.0",
    "react": "18.0.0",
    "react-native": "^0.69.2",
    "react-native-config": "^1.4.6",
    "react-native-date-picker": "^4.2.5",
    "react-native-device-info": "^10.0.2",
    "react-native-encrypted-asyncstorage": "^2.1.3",
    "react-native-flash-message": "^0.3.1",
    "react-native-fs": "^2.20.0",
    "react-native-gesture-handler": "^2.4.2",
    "react-native-iap": "^11.0.0-rc.7",
    "react-native-modal-datetime-picker": "^14.0.0",
    "react-native-pager-view": "^6.0.0",
    "react-native-paper": "^4.12.4",
    "react-native-picker-select": "^8.0.4",
    "react-native-progress": "^5.0.0",
    "react-native-push-notification": "^8.1.1",
    "react-native-reanimated": "^2.13.0",
    "react-native-safe-area-context": "^4.3.1",
    "react-native-screens": "^3.15.0",
    "react-native-svg": "^12.4.3",
    "react-native-tab-view": "^3.1.1",
    "react-native-vector-icons": "^9.2.0",
    "react-native-webview": "^11.25.0",
    "react-redux": "^7.2.2",
    "readable-stream": "1.0.33",
    "reanimated-bottom-sheet": "^1.0.0-alpha.22",
    "redux": "^4.2.0",
    "redux-logger": "^3.0.6",
    "redux-persist": "^6.0.0",
    "redux-saga": "^1.1.3",
    "rn-swipe-button": "^1.3.7",
    "save": "^2.4.0",
    "stream": "^0.0.2",
    "stream-browserify": "^1.0.0",
    "toggle-switch-react-native": "^3.3.0",
    "util": "~0.10.3",
    "victory-native": "^36.5.3"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "7.13.8",
    "@react-native-community/eslint-config": "1.1.0",
    "babel-jest": "25.5.1",
    "eslint": "^8.23.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-prettier": "^4.2.1",
    "jest": "^28.1.1",
    "metro-react-native-babel-preset": "^0.70.3",
    "prettier": "^2.7.1",
    "react-test-renderer": "18.0.0",
    "rn-nodeify": "^10.3.0"
  },
  "jest": {
    "preset": "react-native"
  },
  "rnpm": {
    "assets": [
      "./app/assets/fonts"
    ]
  },
  "react-native": {
    "path": "path-browserify",
    "_stream_transform": "readable-stream/transform",
    "_stream_readable": "readable-stream/readable",
    "_stream_writable": "readable-stream/writable",
    "_stream_duplex": "readable-stream/duplex",
    "_stream_passthrough": "readable-stream/passthrough",
    "stream": "stream-browserify",
    "tls": false,
    "fs": "react-native-fs"
  },
  "browser": {
    "path": "path-browserify",
    "_stream_transform": "readable-stream/transform",
    "_stream_readable": "readable-stream/readable",
    "_stream_writable": "readable-stream/writable",
    "_stream_duplex": "readable-stream/duplex",
    "_stream_passthrough": "readable-stream/passthrough",
    "stream": "stream-browserify",
    "tls": false,
    "fs": "react-native-fs"
  }
}

</code>```

I need help to overcome this security issue?

Body:
After archive react-native ios appication, I had test it on Immuniweb mobile application testing tool. I have got security issue given bellow.

EXPOSURE OF POTENTIALLY SENSITIVE DATA [DAST] [M2] [CWE-200]
Potentially sensitive or internal information is detected in the mobile application via tracing its system calls.
[POTENTIAL HEROKU API KEY FOUND]

We did not use HEROKU anyway.

This is my package.json contents.

{
  "name": "",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "postinstall": "rn-nodeify --install fs,util,path,tls,stream,buffer,global,process --hack && patch-package",
    "android": "ENVFILE=.env react-native run-android",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint .",
    "build:ios": "react-native bundle --entry-file='index.js' --bundle-output='./ios/main.jsbundle' --dev=false --platform='ios'"
  },
  "dependencies": {
    "@gorhom/bottom-sheet": "^4.4.3",
    "@invertase/react-native-apple-authentication": "^2.2.2",
    "@react-native-async-storage/async-storage": "^1.17.9",
    "@react-native-community/checkbox": "^0.5.12",
    "@react-native-community/cli": "^8.0.5",
    "@react-native-community/datetimepicker": "^6.3.2",
    "@react-native-community/push-notification-ios": "^1.10.1",
    "@react-native-masked-view/masked-view": "^0.2.6",
    "@react-native-picker/picker": "^2.4.4",
    "@react-navigation/bottom-tabs": "^6.3.2",
    "@react-navigation/native": "^6.0.10",
    "@react-navigation/stack": "^6.2.1",
    "@rneui/base": "^0.0.0-edge.2",
    "@rneui/themed": "^0.0.0-edge.2",
    "@types/jest": "^29.0.0",
    "asyncstorage-down": "^4.2.0",
    "aws-iot-device-sdk": "^2.2.12",
    "aws-sdk": "^2.1203.0",
    "axios": "^0.27.2",
    "buffer": "^4.9.1",
    "global": "^4.4.0",
    "jsonwebtoken": "^8.5.1",
    "jwt-decode": "^2.2.0",
    "lodash.clonedeep": "^4.5.0",
    "lodash.get": "^4.4.2",
    "lodash.isempty": "^4.4.0",
    "lodash.max": "^4.0.1",
    "lodash.min": "^4.0.1",
    "lodash.omit": "^4.5.0",
    "lodash.unionby": "^4.8.0",
    "moment": "^2.29.4",
    "patch-package": "^6.4.7",
    "path-browserify": "0.0.0",
    "process": "^0.11.0",
    "react": "18.0.0",
    "react-native": "^0.69.2",
    "react-native-config": "^1.4.6",
    "react-native-date-picker": "^4.2.5",
    "react-native-device-info": "^10.0.2",
    "react-native-encrypted-asyncstorage": "^2.1.3",
    "react-native-flash-message": "^0.3.1",
    "react-native-fs": "^2.20.0",
    "react-native-gesture-handler": "^2.4.2",
    "react-native-iap": "^11.0.0-rc.7",
    "react-native-modal-datetime-picker": "^14.0.0",
    "react-native-pager-view": "^6.0.0",
    "react-native-paper": "^4.12.4",
    "react-native-picker-select": "^8.0.4",
    "react-native-progress": "^5.0.0",
    "react-native-push-notification": "^8.1.1",
    "react-native-reanimated": "^2.13.0",
    "react-native-safe-area-context": "^4.3.1",
    "react-native-screens": "^3.15.0",
    "react-native-svg": "^12.4.3",
    "react-native-tab-view": "^3.1.1",
    "react-native-vector-icons": "^9.2.0",
    "react-native-webview": "^11.25.0",
    "react-redux": "^7.2.2",
    "readable-stream": "1.0.33",
    "reanimated-bottom-sheet": "^1.0.0-alpha.22",
    "redux": "^4.2.0",
    "redux-logger": "^3.0.6",
    "redux-persist": "^6.0.0",
    "redux-saga": "^1.1.3",
    "rn-swipe-button": "^1.3.7",
    "save": "^2.4.0",
    "stream": "^0.0.2",
    "stream-browserify": "^1.0.0",
    "toggle-switch-react-native": "^3.3.0",
    "util": "~0.10.3",
    "victory-native": "^36.5.3"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "7.13.8",
    "@react-native-community/eslint-config": "1.1.0",
    "babel-jest": "25.5.1",
    "eslint": "^8.23.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-prettier": "^4.2.1",
    "jest": "^28.1.1",
    "metro-react-native-babel-preset": "^0.70.3",
    "prettier": "^2.7.1",
    "react-test-renderer": "18.0.0",
    "rn-nodeify": "^10.3.0"
  },
  "jest": {
    "preset": "react-native"
  },
  "rnpm": {
    "assets": [
      "./app/assets/fonts"
    ]
  },
  "react-native": {
    "path": "path-browserify",
    "_stream_transform": "readable-stream/transform",
    "_stream_readable": "readable-stream/readable",
    "_stream_writable": "readable-stream/writable",
    "_stream_duplex": "readable-stream/duplex",
    "_stream_passthrough": "readable-stream/passthrough",
    "stream": "stream-browserify",
    "tls": false,
    "fs": "react-native-fs"
  },
  "browser": {
    "path": "path-browserify",
    "_stream_transform": "readable-stream/transform",
    "_stream_readable": "readable-stream/readable",
    "_stream_writable": "readable-stream/writable",
    "_stream_duplex": "readable-stream/duplex",
    "_stream_passthrough": "readable-stream/passthrough",
    "stream": "stream-browserify",
    "tls": false,
    "fs": "react-native-fs"
  }
}

I need help to overcome this security issue?


问:
how to get contacts details to our app after changing details in contacts?
I have created an app and displaying contact details like name and number. I want to update these details right after changing details from the phone contact app. Basically myContact app will be running in background while I'm changing or adding contact details in phoneContact, after changing when I return to myContact, it should display updated or added contact details too.

Didn't get any relevant answers


问:
OpenXML Custom Properties Set new value and refresh
I have followed below two post and trying to update Custom properties in MS word.
Open XML Custom Property doesn't work and
Custom Properties are not updated for the word
The problem with this approach is that if I don't use this line updateFields.Val = new OnOffValue(true); document still store old values and user needs to manually refresh fields. The disadvantage of above line is that users get this message every time they open the document

Is there a better solution to programmatically set Custom Properties values and refresh them automatically?

My code in C#

```<code> public void AddCustomPropertyToWordDocument(string filename, string propertyName, string propertyValue,ILogger log)
        {
            if (String.IsNullOrEmpty(filename))
                throw new Exception("Filename not specified.");

            // Open Wordprocessing document.
            using (WordprocessingDocument doc = WordprocessingDocument.Open(filename, true))
            {
                // Add a main document part.
                MainDocumentPart mainPart = doc.MainDocumentPart;

                //CustomFilePropertiesPart
                CustomFilePropertiesPart customProps = doc.CustomFilePropertiesPart;

                //add part if it doesn't exist
                if (customProps == null)
                {
                    customProps = doc.AddCustomFilePropertiesPart();
                    customProps.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties();
                }

                DocumentFormat.OpenXml.CustomProperties.Properties props = customProps.Properties;

                //check if property already exists
                var prop = props.Where(p => ((CustomDocumentProperty)p).Name.Value == propertyName).FirstOrDefault();

                //remove property, if it exists
                string currentPropValue;
                if (prop != null)
                {
                    currentPropValue = prop.InnerText;
                    prop.Remove();
                }

                //create custom property
                CustomDocumentProperty customProp = new CustomDocumentProperty();
                customProp.Name = propertyName;
                customProp.VTLPWSTR = new VTLPWSTR(propertyValue);
                customProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";

                // Append the new property, and
                // fix up all the property ID values.
                // The PropertyId value must start at 2.
                props.AppendChild(customProp);
                int pid = 2;
                foreach (CustomDocumentProperty item in props)
                {
                    item.PropertyId = pid++; //increment
                }

                props.Save();

                // Save changes to the main document part.
                DocumentSettingsPart settingsPart = doc.MainDocumentPart.GetPartsOfType<DocumentSettingsPart>().First();
                UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();
                updateFields.Val = new OnOffValue(true);
                settingsPart.Settings.PrependChild<UpdateFieldsOnOpen>(updateFields);
                settingsPart.Settings.Save();
                doc.MainDocumentPart.Document.Save();

            }

        }
</code>```

Body:
I have followed below two post and trying to update Custom properties in MS word.
Open XML Custom Property doesn't work and
Custom Properties are not updated for the word
The problem with this approach is that if I don't use this line updateFields.Val = new OnOffValue(true); document still store old values and user needs to manually refresh fields. The disadvantage of above line is that users get this message every time they open the document

Is there a better solution to programmatically set Custom Properties values and refresh them automatically?

My code in C#

 public void AddCustomPropertyToWordDocument(string filename, string propertyName, string propertyValue,ILogger log)
        {
            if (String.IsNullOrEmpty(filename))
                throw new Exception("Filename not specified.");

            // Open Wordprocessing document.
            using (WordprocessingDocument doc = WordprocessingDocument.Open(filename, true))
            {
                // Add a main document part.
                MainDocumentPart mainPart = doc.MainDocumentPart;

                //CustomFilePropertiesPart
                CustomFilePropertiesPart customProps = doc.CustomFilePropertiesPart;

                //add part if it doesn't exist
                if (customProps == null)
                {
                    customProps = doc.AddCustomFilePropertiesPart();
                    customProps.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties();
                }

                DocumentFormat.OpenXml.CustomProperties.Properties props = customProps.Properties;

                //check if property already exists
                var prop = props.Where(p => ((CustomDocumentProperty)p).Name.Value == propertyName).FirstOrDefault();

                //remove property, if it exists
                string currentPropValue;
                if (prop != null)
                {
                    currentPropValue = prop.InnerText;
                    prop.Remove();
                }

                //create custom property
                CustomDocumentProperty customProp = new CustomDocumentProperty();
                customProp.Name = propertyName;
                customProp.VTLPWSTR = new VTLPWSTR(propertyValue);
                customProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";

                // Append the new property, and
                // fix up all the property ID values.
                // The PropertyId value must start at 2.
                props.AppendChild(customProp);
                int pid = 2;
                foreach (CustomDocumentProperty item in props)
                {
                    item.PropertyId = pid++; //increment
                }

                props.Save();

                // Save changes to the main document part.
                DocumentSettingsPart settingsPart = doc.MainDocumentPart.GetPartsOfType<DocumentSettingsPart>().First();
                UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();
                updateFields.Val = new OnOffValue(true);
                settingsPart.Settings.PrependChild<UpdateFieldsOnOpen>(updateFields);
                settingsPart.Settings.Save();
                doc.MainDocumentPart.Document.Save();

            }

        }


问:
React Native - How can I save my local image in IOS simulator/devices
I'm having a problem using this package @react-native-community/cameraroll. I cannot save my asset image in my IOS device or simulator.

Here's my code:

```<code> const savePicture = async () => {
        if (Platform.OS === 'android' && !(await hasAndroidPermission())) {
          return;
        }

        CameraRoll.save('../assets/images/share.png');
  };
</code>```

Code for calling the function

```<code>    <TouchableOpacity onPress={savePicture}>
      <Text>
       Save to device
      </Text>
    </TouchableOpacity>
</code>```

Body:
I'm having a problem using this package @react-native-community/cameraroll. I cannot save my asset image in my IOS device or simulator.

Here's my code:

 const savePicture = async () => {
        if (Platform.OS === 'android' && !(await hasAndroidPermission())) {
          return;
        }

        CameraRoll.save('../assets/images/share.png');
  };

Code for calling the function

    <TouchableOpacity onPress={savePicture}>
      <Text>
       Save to device
      </Text>
    </TouchableOpacity>